How to read AJAX response variable? - javascript

The following is the response I'm receiving in my AJAX success function:
"{"success":true,"data":{"id":1841,"title":"atitle","filename":"filename.jpg","url":"http:\/\/example.com\/wp-content\/uploads\/2014\/11\/filename.jpg","link":"http:\/\/example.com\/?attachment_id=1841","alt":"","author":"21","description":"","caption":"","name":"filename-39","status":"inherit","uploadedTo":0,"date":1415555051000,"modified":1415555051000,"menuOrder":0,"mime":"image\/jpeg","type":"image","subtype":"jpeg","icon":"http:\/\/example.com\/wp-includes\/images\/media\/file.png","dateFormatted":"November 9, 2014","nonces":{"update":"b832c2939d5","delete":"83dda46357e","edit":"51ac41b11c6"},"editLink":"http:\/\/example.com\/wp-admin\/post.php?post=1841&action=edit","meta":false,"authorName":"Some One","filesizeInBytes":10755,"filesizeHumanReadable":"11 kB","sizes":{"thumbnail":{"height":90,"width":90,"url":"http:\/\/example.com\/wp-content\/uploads\/2014\/11\/filename-90x90.jpg","orientation":"landscape"},"full":{"url":"http:\/\/example.com\/wp-content\/uploads\/2014\/11\/filename.jpg","height":260,"width":236,"orientation":"portrait"}},"height":260,"width":236,"orientation":"portrait","compat":{"item":"","meta":""}}}"
I'm trying to update the src attribute of a particular image on my page using the data that is returned in this response. For example:
$( '#myimage' ).attr( 'src', response.data.url );
The problem is, I get the error Uncaught TypeError: Cannot read property 'url' of undefined
I'm sure response.data.url is wrong. How can I get the URL from the response so that I can update the image's src attribute?

You might be able to take advantage of jQuery's getJSON method. When you're using ajax, you are only receiving a string response, so you would first have to parse it as json using parseJSON. However, getJSON will do parseJSON for you.
$.getJSON('my/service', function(data) {
$('#myimage').attr('src', data.url);
});

yo could use
x=$.parseJSON(response)
and this will convert the json string to a valid json objet, if there is an error will throw an exception you can use try{}catch(e){} to fix it
try{
var x=$.parseJSON(response);
}catch(e){
console.log(e);
}

use JSON.parse to parse as an object, your returned data is string:
response=JSON.parse(response);
$( '#myimage' ).attr( 'src', response.data.url );

The simple way is to use an AJAX request like this:
$.post('remote_url', {key:value}, function(response){
if(response.success) {
$('#myimage').attr('src', response.data.url);
}
}, 'json');
In this example, I've used $.post and you didn't provide enough information about the request type so it could be a $.getJSON request as well. Also, {key:value} is an object which will be passed to the server if required. So, use it if you pass any data to server, otherwise remove it.
In this example, 'json' is being used as data type so the response will be parsed by jQuery also if you use $.getJSON then the response will be parsed but in this case, you don't need to use 'json' as the last parameter. For example:
$.getJSON('remote_url', function(response) {
if(response.success) {
$('#myimage').attr('src', response.data.url);
}
});
Note: getJSON loads JSON-encoded data from the server using a GET HTTP request. So, for a POST request use $.post instead.

Related

Issue about getting response in $.get()

$('#requestButton').click(function() {
$.get('ajax.php', function(data) {
alert(data);
});
});
alert() doesn't showing. What's the problem?
The problem is that your server is claiming:
content-type: application/javascript
But you are sending back a JSON document. jQuery won't populate data when it gets (what it thinks is) a JavaScript program back from the server.
You need to send the correct content type, which is application/json.
Using getJSON or specifying "json" are hacks to tell jQuery to disbelieve the content type and parse in a different data format, but you should fix the server so it tells the truth about the content instead.
Instead of :
$.get
use :
$.getJSON
As you mentioned in the comment section about returned data is json.
Or add a dataType in the $.get() call:
$.get( "ajax.php", function( data ) {
console.log(data);
}, "json" ); //<-----------add dataType here

Filter JSON response on a jQuery ajax request, for XSS text

I am falling into a silly issue where the server is giving JSON response with XSS safe text added.
The server gives only 2 kinds of response:
HTML page with hidden input field that contains the value I want
JSON String with the value which can be preferably converted to JS
Object.
The problem is, for preventing JavaScript XSS attacks, the JSON response is made like this:
while(1);{
"name": {
"abc": "123",
...
}
}
So this goes to parseerror in jQuery ajax method and therefore in the error callback.
How do I fix this?
Also, I tried putting a hook in the error function and change the JSON data:
error: function(jqXHR) {
removeJSCode (jqXHR.responseText);
}
// ...
function removeJSCode(json) {
.. Code to filter the response
}
But this does not work.
jQuery's $.ajax has dataFilter property in its configuration. Pass it a function and it runs after jQuery receives ajax data, but before jQuery has a chance to touch it.
The function is provided the string response as first argument and data type as second argument. The second argument will depend if you passed dataType in the configuration.
There, you can use .replace('while(1);','') and return the string from the function for jQuery to parse.
$.ajax({
...
dataType : 'json',
dataFilter : function(response,type){
//if not JSON, don't do anything with it
if(type !== 'json') return response;
//otherwise, replace and return
return response.replace('while(1);','');
}
...
});

I dont get any data from the getJSON function

I am trying to get a JSON object from a .jsp page. But I dont know what to do with it. I've googeled this for some time now, but I can't find out what this getJSON functions does.
Does it return a string representation of a JSON object?
Or is the parameter 'json' that is passed into the function the JSON Object?
Is the function (the second parameter) equivalent to the function that one write when using XMLHttpRequests? In other words; is this function the asynchronous part?
The alert with "JSON stuff" doesnt print.
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">
function checkUni() {
var URL = "http://localhost:8080/GradSchoolApp/test.jsp";
var jso = $.getJSON(URL, function(json) {
alert("JSON stuff " + json.name);
});
alert(jso);
//alert(jso.name);
}
A few things to check:
Is the webapp also running at localhost:8080? If not, you might be running afoul of the same origin policy, in which case you would need to encode to jsonp.
You should also check in firebug/inspect element/whatever to make sure you are actually getting something returned from your request. You can do this in the network or resources tab depending on which browser you are using. Also stick a breakpoint in your script before the alert and inspect the json object to see if anything was returned.
The second alert isn't firing because the json object doesn't exist yet when you call it.
The relevant docs for getJSON is here. The callback parameter (that you named json) is the already decoded data (i.e. it's a JavaScript object, not a string).
As for why your alert isn't doing anything, see Charles Bandes's answer. To better debug your code you can also use console.log (will work on Firebug or on Chrome), and/or set a handler to ajaxError - so if the problem is with your request you can be notified of the error (instead of the browser ignoring it by default).
Does it return a string representation of a JSON object?
The respone will come as JSON format. getJSON method is a short form of jQuery ajax with datatype as json . The datatype decides what is the format to receive the result from the ajax call.
is the parameter 'json' that is passed into the function the JSON
Object?
The variable json in your callback function will get the response from your ajax call. The data should in a valid JSON Document( if your server pages returns like that properly)
is this function the asynchronous part?
As i told you earlier, getJSON is a shortform of jquery ajax with datatype as Json. It is asynchronous.

How can I access responseText of a jqXHR object from a successfull AJAX call?

I have following ajax call in my JavaScript code
url = 'http://news.ycombinator.com/?callback=?';
$.ajax({url:url ,async:!1,dataType:'script', complete:function(result)
{alert(JSON.stringify(result));}
});
Following is printed out in alert.
{'readyState':4, status:200, statusText:'success'}
It doesn't have responseText.But still, in the chrome console I can see all of the return HTML data of ycombinator page.How can I access this text?
On the other hand if I change the url variable to a url which returns a valid json object like following,
urll = 'http://gdata.youtube.com/feeds/api/videos?q=basshunter&format=5&max-results=5&v=2&alt=jsonc';
$.ajax({url:urll ,async:!1, complete:function(result)
{alert(JSON.stringify(result));}
});
this returns all of the responseText as expected.
One thing to note is if I don't point the url to a valid JSON returning url as in first case, I have to provide option dataType:'script'(or JSON).Otherwise it will throw a cross-domain request error.In second case it didn't throw any cross-domain error even if I didn't specify dataType.
Replace your complete callback with success. Success callback executed when ajax request completed successfully.
Also in your dataType use "json" instead of "script"
if you use "script" in dataType it will return like "{\"key\":\"value\"}".
if you use "json" in dataType it will return like {"key":"value"}.

Invalid Label Error with JSON request

I've read about this a lot and I just can't figure it out. It has nothing to do with MY code, it has to do with the feed or something because if I swap it with a Twitter feed it returns an Object object which is perfect.
$.getJSON('http://rockbottom.nozzlmedia.com:8000/api/portland/?count=1&callback=?',function(json){
console.log(json)
});
And i get an "invalid label" error. Any ideas?
Also, a side note, I've tried the AJAX method as well:
$.ajax({
url: 'http://rockbottom.nozzlmedia.com:8000/api/portland/',
dataType: 'jsonp',
data: 'count=1',
success: function(msg){
console.log(msg)
}
});
and both give the same exact error, and both work fine with Flickr and Twitter examples, so it must be something to do with the feed, but I dont have access to the feed, but I could ask them to fix something IF it's their issue.
Make sure that the server side can handle the JSONP request properly. See here for example.
Edit: It seems that the server doesn't wrap the returned JSON object with the callback function name. The server should return:
callback( { json here } )
and not
{ json here }
That URL looks like it's expecting you to provide a JSONP callback (from the callback=? bit). That's probably the problem; it's returning Javascript rather than JSON (because that's how JSONP works). See the $.ajax docs for more about using JSONP services.
The returned content has unescaped double-quotes in one of the strings. It's invalid JSON:
..."full_content":"just voted "with Mandy " on...

Categories