In jQuery, parsing a bunch of points to draw on a HTML5 canvas. Encountered a strange bug -- but my knowledge of this area is pretty limited so perhaps there's a good explanation.
This works every time:
var json = $.getJSON( "../models/" + id + ".json");
alert("fjkld");
paths = JSON.parse(json.responseText);
This fails every time:
var json = $.getJSON( "../models/" + id + ".json");
paths = JSON.parse(json.responseText);
Anyone have any idea why? Is it because the alert pauses something while the parser 'catches up'? That doesn't make intuitive sense to me but it's the only explanation.
Actually I know this is correct because if I hit "OK" on the alert really fast it fails again.
Can someone please explain to me why this is happening?
getJSON is asynchronous. This means that it returns immediately, before the XMLHTTPRequest has completed. Because alert is a blocking function, all code is halted until you press OK. If you take a while, the request has completed, so responseText is available; if alert isn't present, or you press OK very quickly, the HTTP request has not completed, so the text has not completed.
You need to use a callback function instead: this is a function that will be executed when the AJAX request is complete:
$.getJSON( "../models/" + id + ".json", function(paths) {
// access paths here
});
See the documentation for $.getJSON.
This happens because the getJSON call is asynchronous. Once the call to getJSON is complete all you know is that the browser has kicked off the request for the file. You do not know if the request has been completed or not. Sure, the call to the alert function gives the browser enough time (usually) to get the full file, but as you discovered sometimes that's not true.
Far better is to supply a callback that will be called once the file has been downloaded:
$.getJSON(fileName, function(data) {
paths = JSON.parse(data);
..do something with paths..
});
Although note that paths won't be available until the callback executes.
You need to set up a callback function in the getJSON call to ensure that the response has had time to complete. In the flow of the ajax call the function that generates the getJSON call continues while the getJSON happens. There is no guarantee that the json request has completed when teh JSON.parse() is being called. The proper syntax for the call is :
jQuery.getJSON( "../models/" + id + ".json", function(data, status, xhr){ JSON.parse(data);} )
Check out the api for the getJson call here: http://api.jquery.com/jQuery.getJSON/
Put your logic inside the callback.
$.getJson("../models/" + id + ".json", function(response) {
paths = JSON.pars(response.responseText);
});
Or something like that. As a request API call is an asynchronous call, you have to wait for the server response before you can move forward. That's where callbacks come in. They're called by the asynchronous API when the request is complete. They usually also have success status flags to tell you if your request was successful.
http://api.jquery.com/jQuery.getJSON/
Related
zip = 12345
url = "http://zip.elevenbasetwo.com/v2/US/"+zip;
res = $.get(url)
When I run above code in the browser console then I can access res.responseJSON but
When I run this code in my application.js then I can't access res.responseJSON I am getting undefine.
Does anybody know what's the issue or how can I access in my application.js ?
$.get is asynchronous. The response isn't immediatement available in the jqXHR object.
Pass a success callback to $.get :
$.get(url, function(data){
// use data
});
The reason why it seems to work in the console is because you don't instantly open the object which is logged : the server answers before. That's not the case in your normal code : while the request is sent, the following line in your code is immediately executed, without waiting for the answer.
I've been pulling my hair out with this function. It's a function within a function which is why I think it's not returning anything, heres the code:
function getEventImageNormal(data) {
$.getJSON("https://graph.facebook.com/fql?access_token=" + access_token + "&q=SELECT pic FROM event WHERE eid=" + data, function(data){
console.log(data.data[0].pic);
return data.data[0].pic;
});
}
The correct item, the URL of the image, is being set to the console log, but not being returned?
If anyone is wondering why I'm not using https://graph.facebook.com/object_id/picture to get the events image, it's because this functionality is currently not working and the only method is to use FQL for event images.
By default getJSON() performs asynchronous call.
You can call a function right within the success callback handler to treat the response.
$.getJSON("https://graph.facebook.com/fql?access_token=" + access_token + "&q=SELECT pic FROM event WHERE eid=" + data, function(data){
console.log(data.data[0].pic);
getResponse(data);
});
function getResponse(data) {
// handle your data here.
}
You need to add callback=? parameter to your url to let remote url and jQuery know it is a jsonp call. If it is only json sent, it is against cross domain security policies and browser won't accept it into the DOM.
This is in addition to processing the data within the sucecss callback of request, due to asynchronous nature of ajax.
var data=/* your value*/
$.getJSON("https://graph.facebook.com/fql?callback=?&access_token=" + access_token + "&q=SELECT pic FROM event WHERE eid=" + data, function(data){
/* process data here*/
})
I find myself having to get around waiting for AJAX in jQuery often these days. Problem is, I have to do loops and crap to wait for them. What are some ways that I can wait for the AJAX event to finish before executing code (preferably without making extra functions)?
Generally, if there is a chance that a repeating AJAX request may not be finished before it is called again, I use a flag to prevent overlapping requests.
First, define the flag and set it initially as false. Whenever you are sending your AJAX request, check to see if this flag is false. If it is, then proceed with the request - not before setting the flag to true mind. Once the AJAX request has completed, set the flag back to false.
Using the above method, only one instance of the AJAX query will run at once. I'm sure jQuery must have a way of seeing if there is an AJAX request being processed already or not, but I'm a MooTools man.
What method are you using to make AJAX calls? If you use the built in $.ajax(), you can set the success property to a callback function which will be called once the AJAX request returns successfully. There is also the complete callback which will always be called whether it succeeds or fails.
From the jQuery API:
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
There is also a complete option that you can use.
http://api.jquery.com/jQuery.ajax/
Newbie here..
I just want to ask how can I accomplish my homework in school.
I basically have this need.
I want to send an ajax request every 10 seconds but I dont want to initiate another request if my previous request has not returned yet.
I am thinking that the connection to DB might be that bad sometimes so I would like to wait for my previous request to be finished (success/failed/error) before I fire up another.
I check on javascript and and found the setinterval method. But how can I line up my ajax request so that the server doesnt get fired up by many ajax request?
I am studying jquery right now and is using JSON.
One method would be to set a variable to false when you send out a request. When you get it back set it back to true. When you go to send out a new ajax request make sure the value is true. If not add it to a queue of some sort so that it will be called when the request is finished. However if every request takes longer then ten seconds your queue will get pretty backed up. So you may not want a queue. So instead when you go to send out the ajax request if the variable is false you just wait another ten seconds.
I'll even help more:
var isWatingForResponse = false;
$.ajax({
url: 'wherever'
,dataType: 'json'
,beforeSend: function() {
if(isWatingForResponse) {
return false;
}
isWatingForResponse = true;
}
,complete: function() {
isWatingForResponse = false;
}
,success: function (data) {
//process data
}
});
Or follow #qw3n answer. This should work with jQuery 1.4.2
As I see the OP question:
How to set up fault-tolerance on the client-side because of Db-server issues, using jQuery Ajax?
This IMHO, is a really good question.
If I may, I would like to map out the pipe:
web-client->network->web-server->network->Db-server
Db-server->network->web-server->network->web-client
Your solution to this problem of handling issues with the db-server in the client is workable, but really does not address the actual problem. It could really cripple you for future extension of your client.
You should really be handling this issue as close to the problem as possible. In the web-server.
In my application i am using asp.net3.5,ajax.dll.
I am calling all functionalities using ajax from javascript.
Sometimes i need to get the condition results from server side, only then i will be able to pass to next condition.
for the above case, javascript passes to next condition before executing the first condition.
So i added the following code to make it work,
setTimeOut("finddefaultvideo()",1000);.
Can anyone please help me to get rid of this issue?
One thing i understood that,it won't wait for the time until server returns the value.
any idea to overcome the above one?
I don't know if I understood you correctly but this might be the solution you are looking for (however it is using jquery)
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
the alert message is shown as soon as your ajax request was success full and the server sent response data.
setTimeout is not reliable for this unless you do some kind of recursive polling technique. You need to invoke finddefaultvideo after the ajax callback has returned. You could place finddefaultvideo() inside of your ajax callback, the one that's fired onreadystatechange and where the readyState is 4 and 'complete'.
ajaxCallback: function(html) {
if ( something ) {
executeRestOfCode();
}
}
function executeRestOfCode() {
// your code that needs to be invoked after the ajax callback
}