I've been looking for a way to include an object from a JSON file, and I've found several pages summarizing how to use $.getJSON(), and even a few answers here, but none have worked. Some have suggested I do it this way:
var json;
$.getJSON("dir/1.json", function(response){
json = response;
});
And some have suggested it this way:
var json = $.getJSON("dir/1.json");
Neither of these work. When I try to call a property of json, such as json.title, it just gives me an error saying the variable is undefined. No one else seems to be having this problem, so what am I doing wrong?
Try using this:
var json = $.getJSON( "dir/1.json" )
.done(function( response ) {
json = response;
console.log( "json variable ready" );
})
.fail(function() {
console.log( "error" );
});
Update
The response object returned by $.getJSON() implements the promise interface, giving it all the properties, methods, and behavior of a promise. So json isn't ready until a response is returned or the done function is fired.
The response is deferred. At the time you're reading the variable, the response likely hasn't responded yet. Try accessing the variable inside the function callback, right after json = response;
Related
I'm trying to implement a function that will do something based off of the response text given by a certain ajax call. But I can't access the response text field. Here is my code:
var response = $.getJSON('/add_participant',{
email : uemail,
password : upassword
})
and I've tried to access it this way:
response.responseText
But when I log it out to the console, it says it's undefined.
I think it has something to do with the ajax call needing to resolve first, before I access the response text. That's because if I save it to a global variable, when I pull up the webpage and use the inspection tools, I am able to access the responseText in that way.
How can I get that response text during my function? Is there a way I can have the script wait for it to resolve or whatever?
Thanks in advance!
Since this gets executed asynchronously, you need to handle it in .done callback. Here is the sample code.
var response = null; // assign to [] if you think you will receive an array
$.getJSON('/add_participant',{
email : uemail,
password : upassword
}).done(function (data) {
response = data;
console.log('response: ', data);
})
Hey I figured out what was wrong with my code, and it was actually a problem with the python code I was calling. I'm setting up my website with the Flask library in Python, and I was using the ajax call to use a python function in the back end and get the output it returned. The problem was that when I returned the output in the python function, I was returning a string, just like this:
return ("It worked!")
The rest of the function was still operating and doing the things I wanted it to do, and I could still check out the response when I used the inspection tools. But the returned value was in the incorrect format. It seems that this resulted in something along the lines of the Javascript code on the front end not getting the message from Python that the Python function had finished. And for that reason, nothing in the .done(function (data) { } ) block would get executed.
To fix this, I had to instead return a jsonified dictionary. jsonify is a function from the flask library. Here's how it should look:
return(jsonify({'result': 'It worked!'}))
And then if you want to access that data back in the javascript, access the result property of the data object inside the
.done(function (data) { } ) block. For me, it looked like this:
var response = $.getJSON('/add_participant',{
email : uemail,
password : upassword
}).done(function (data) {
if (data.result ='It Worked!'){
console.log("It worked!!");
// Do whatever else you wanted
}
else{
console.log("It didn't work.");
// Do something else
}
})
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.
I am sending a JSON encoded array from my controller to my view page. I am doing this on my view page to get the data:
function () {
$.get('http://localhost/Location/loc', function(data){
alert(data[0].message);
});
}
The data is like this
{"message":"hello!"}
I am alerting the value of message but my alert giving me undefined. My question is how can I access values of JSON array?
I am new to JSON so I don't know much about JSON.
Try changing your function to:
function () {
$.get('http://localhost/Location/loc', function(data){
alert(data.message);
}, 'json');
}
This is because jQuery probably doesn't know that the response data is JSON, so it's assuming that it's plaintext. You can explicitly specify it in $.get as the last parameter as in the revised code, or configure your server to send the response with the HTTP Content-Type header of application/json.
I'm assuming this because message is not a property of a String and that's why you're getting undefined.
Alternatively, you may use $.getJSON:
function () {
$.getJSON('http://localhost/Location/loc', function(data){
alert(data.message);
});
}
Also note that I have changed the alert to data.message. See Knaģis' answer for explanation.
You data contains a single object, not an array.
In your case use alert(data.message); instead.
An array is defined using [] brackets, for example [{message:"hello"}, {message:"world"}] is an array with two objects in it.
OK, if this does not work:
function () {
$.get('http://localhost/Location/loc', function(data){
alert(data.message);
});
}
try this:
function () {
$.get('http://localhost/Location/loc', function(data){
alert(data.message);
}, 'json');
}
I have a backbone object that I'm calling save on. How do I know what comes back in the ajax call. Looking at the code for the project I got put on, I see some people just have a generic
success: function (data) {
console.log(data);
Then other times, I see:
success: function (library, response) {
console.log(library);
console.log(response)
I'm confused on how you would know you would have I presume a library or response object, vs a general data. When I look at the second example, I am looking at the output of
console.log(response);
and I see response has three attributes:
Notifications
Response
ResponseStatus
Response itself looks like Object {Id="12345", href="the/href", Name="asdf"}
So it looks like a Javascript object to me, but then when I try to do
console.log(response.Name);
I always get undefined even though I can see the value.
So I'm trying to understand how the callback in an ajax calls. Like when you can use an actual library object, response object, vs a data object, and how I can go about parsing the results properly. Thanks in advance!
You should either
$.ajax({
dataType : 'json',
..
})
or
$.ajax({
..
success : function(data) {
var result = JSON.parse(data);
});
Then I think you will be good
This is the json result I get from my controller
{"data":"Sunday"}
The data can say any day of the week (Sunday, Monday, etc...)
On success I want to do this in ajax call
success: function(Response){
var myresponse = Response.data;
alert(myresponse);
}
However, it gives me undefined.
If you are sure that you are getting a JSON response from the server, you can make use of the Ext.JSON class to decode the JSON.
You can use the decode() method to convert a string to an object. Then you should be able to easily access it.
Example:
var jsonObject = Ext.JSON.decode(Response.responseText);
var myData = jsonObjet.data;
If you are using jQuery to load this string you could just use $.getJSON which will automatically parse the string and pass the object as the return value to the 'success' function.
try to use a
console.log(Response);
to check the content of Response
It might be considering your response to be a string. I would do something like this:
success: function(Response){
alert(typeof Response);
var myresponse = Response.data;
alert(myresponse);
}
If it tells you that Response is string, you need to make sure that your framework knows you are getting back JSON. For instance with jquery it might be $.getJSON().