Well I would like to check answer from server every 5 seconds. But my success function inside $.ajax just does not work. Although ajax sends requests and gets response. Time limit is not exceeded since function is run every 5 seconds and response is received within 1 second.
If i put something inside checkMyCreatedGame function after $.ajax it does work but success function does not.
var checkMyGame;
checkMyGame =setInterval(checkMyCreatedGame,5000);
var checkMyCreatedGame = function(){
$.ajax({
url :'../cgi-bin/lobby.py',
type :"GET",
cache :false,
data {
"checkMyGameId":createdGameId,
"player":playerName
},
dataType:"json",
success:function(jsonData){
console.log(jsonData)
}
});
};
Here is my firebug console logs when I run this code (do not pay attention to what is above those gets):
Here is same screenshot but not resized by stackoverflow: https://i.stack.imgur.com/e9HBa.png
As you can see console.log inside success function is not executed.
In your AJAX call, you tell jQuery to expect JSON data:
dataType:"json",
Then your server returns non-JSON data:
waiting
jQuery then tries to parse it as JSON, and unsurprisingly, fails. If you tell jQuery to expect text instead, it will work fine:
dataType:"text",
The message of this is: if you are finding that an AJAX call is failing silently, put an error handler in. If you had, you would have received a message telling you that you had a parsererror.
Related
I'm running into a strange problem on my webpage using the jQuery $.get function. The code below is executed on page load:
$.get(urls.validateSession, function(data){
console.log(data);
});
I would expect this to make a GET request to urls.validateSession each time the page is loaded, then log the response data to the console.
It does this on the initial page load with no problems. But on subsequent page loads, jQuery does not make a new request to urls.validateSession. It instead just prints the exact same response data from the previous request (identical response timestamp and everything!)
Interestingly, when reloading the page with Shift + F5, jQuery does make a new request to urls.validateSession and I can see a new response timestamp.
Can anyone explain this behavior?
I think this previous question might help get you the desired result.
The JQuery get() method's cache is, by default set to true.
cache (default: true, false for dataType 'script' and 'jsonp')
And it sounds like your results are getting cached, that's why it doesn't bother to run the function each page load.
You can check out more ajaxSettings here
The snippet from #KevinB in the linked question:
$.get({
url: url,
cache: false
}).then(function(rdata){
console.log(rdata);
});
If you do not want caching on any of your AJAX requests, you could also set this field in your initial AJAX setup before running any AJAX functions.
$.ajaxSetup({
cache: false
});
I am trying to put a url from an ajax response into a variable in jquery.
I have written the following code:
var thumb = $.ajax({
dataType: 'json',
url: 'https://www.googleapis.com/books/v1/volumes?q=isbn:' + isbn,
success: function(response){
return $(response).volumeInfo.imageLinks.thumbnail;
}}).responseText;
It was my understanding from looking at other answers that I must add .responseText at the end, or the code will continue without waiting for the ajax response.
However, thumb variable remains undefined.
I tried implementing the following solution with relevant changes (As I am passing only one ISBN at a time, there shouldn't be an array. The response should contain only one imageLinks.thumbnail url), but I cannot seem to catch the response correctly.
I looked into other answers, especially this one, but I am still not clear about how to reach the ajax response.
$.ajax is asynchronous, meaning the code will execute completely and the success callback will be fired at a later time.
var thumb is evaluated immediately. Do some reading on "callbacks" and "promises" to get more familiar with this topic.
A solution to your issue is:
function setThumbnail(thumbnail){
// this will evaluate later, when the ajax returns success
console.log('thumbnail gotten!');
var thumb = thumbnail; // do something with in in this function
}
$.ajax({
dataType: 'json',
url: 'https://www.googleapis.com/books/v1/volumes?q=isbn:' + isbn,
success: function(response){
setThumbnail($(response).volumeInfo.imageLinks.thumbnail);
}
});
// This line will evaluate immediately and carry on
console.log('ajax executed');
I threw in some logs for you to help you understand the order of execution here.
I would also note that $(response) looks odd to me, without testing it I think it should probably be just response.volumeInfo....
console.log(response) in the success callback to make sure you understand what data you are getting back.
This question already has answers here:
Easy to understand definition of "asynchronous event"? [closed]
(11 answers)
Closed 7 years ago.
I have the following Javascript and it's returning results out of the order I would expect them.
function getCurrentItems(id){
alert("2");
$.ajax({
url: "somePHPurlthatspitsoutajsonencodedArray.php",
type: "POST",
dataType: "json'",
data: {id:id},
success: function(data){
alert("3");
}
});
alert("4");
}
$(document).on('click', '.eventClass', function(e){
alert("1");
var id = "someID";
var results = getCurrentItems(id);
alert("5");
});
I would think I'd get alerts in the order of 1, 2, 3, 4, 5.
Instead I get them in the order of 1, 2, 4, 5, 3.
I just can't figure out why that success alert (5) fires last?
AJAX is short for asynchronous JavaScript and XML. Asynchronous is the keyword here. I'll use an allegory to explain async.
Lets say you're washing dishes manually. You can't do anything else while doing that, so it is synchronous.
Lets say you put your dishes in a dishwasher. You can do other things, you've delegated the task to the dishwasher, so this is asynchronous. Asynchronous is generally better, because you can do multiple things at one time. Javascript only asyncs when requesting info from the server, as Javascript is single threaded (it only runs on 1 CPU core and can only do one thing at a time on it's own).
A callback is a function that is called when the async task completes. The dishwasher finishes, so now you have to empty it as soon as you complete what you're doing when it finshed.
So in your code, you start the dishwasher, say you're going to alert("3") when the dishwasher finishes running, and then you go alert 4 and 5. Then when the dishwasher finishes/your server returns data, you alert 3 like you said you would.
That make sense?
The reason that you give a success callback function in an ajax request is that the request might take some time to return, but your code can continue running. In this case the ajax request is sent, and the success function is remembered for later, then your code continues (alerting 4 and 5). When the browser receives the response to the ajax request it calls the success function (alerting 3).
The way that Javascript works, only one thread is run per browser tab, so event handlers are not called until any previously running code is completed. Therefore, even if your getCurrentItems function were to take several seconds to complete, by which time the server response had returned, the success function would still not be called until after your function had completed.
Edit: Because an ajax call can take some time, it is not generally desirable to be able to call a function like getCurrentItems which includes an ajax request, and wait for the response. If you do this, then you are likely to leave your browser window unresponsive, and you will have to deal with potential errors from the ajax call. Instead, you should put any code that you wish to run which relies on the ajax result in the success function, or in another function which you call from there. As languages go, Javascript is very good for doing this kind of thing. You could even take a callback function as an argument to getCurrentItems, and run it from the success function.
As others have mentioned, you're getting the results in the order you see because the ajax request doesn't return with it's data and call your success callback until the response is received, but code continues to execute immediately after the $.ajax call.
To get the workflow you're probably expecting, you could use promises, or simply pass in a callback:
function getCurrentItems(id, onSuccess){
alert("2");
$.ajax({
url: "somePHPurlthatspitsoutajsonencodedArray.php",
type: "POST",
dataType: "json'",
data: {id:id},
success: function(data){
alert("3");
onSuccess(data);
}
});
alert("4");
}
$(document).on('click', '.eventClass', function(e){
alert("1");
var id = "someID";
var results = getCurrentItems(id, function(data){
console.log('data',data);
alert("5");
});
});
I have the follow code using jQUery's getjson methods
function Share(){
var title = 'Hello';
var description = 'hi description';
var url = "www.facebook.com"
$.getJSON("http://getTitle/1", function(data){
title = data.Name;
});
callShare(title,description,url,imageUrl);
}
function callShare(title,description,url,imageUrl){
window.open(
'http://www.facebook.com/sharer.php?s=100&p[title]='+title+'&p[summary]='+description+' &p[url]='+url+'&p[images][0]='+imageUrl+'','facebook-share-dialog',
'width=626,height=436')}
However, it seems that the method finishes running and does the callShare function before the getJson method has finished running. Would require some help here. I understand that there might be duplicate question here and I apologize but I am not able to apply it here.
Thanks
$.getJSON("http://getTitle/1", function(data){
title = data.Name;
callShare(title,description,url,imageUrl);
});
Being an async function $.getJson() doesn't wait for the response and executes the next line.
If you want to do some things after the response has been received from the server put it in the success function. Like I have mentioned in the code.
if you also want to execute code on error or before sending the request. Use $.ajax() instead
Althoug the question has been answered by Parv but here are some explanation
First of all the correct way to call functions in such senarios
$.getJSON("http://getTitle/1", function(data){
title = data.Name;
callShare(title,description,url,imageUrl);
});
Now the question is why?
$.getJSON is an extension of $.ajax method i.e. Asynchronous, so the browsers expect of waiting for the request to complete by $.getJSON they move on to the next line of codes so that the user dont get stuck with lock browser waiting for a request to complete.
Now what is the solution in that case?
Such Asynchronous requests have a or couple of special methods called call backs, so all you need is to call such methods in those call backs that are required to be called after the successful failed or complete of the request, you will find more in the above link
$.getJSON is just a shorthand for $.ajax. As others pointed out, its an async call which will run in a separate thread(kind of) and rest of the code will keep on executing without worrying for the JSON result.
So you can add a success function which will be called when the async call succeeds. You can use $.ajax too.
$.ajax({
dataType: "json",
url: url,
data: data,
success: callShare(title,description,url,imageUrl),
error: alert('error');
});
I use $.ajax because it gives more clarity over the things that are happening.
I've got the following code to call a json web service in a separate functions.js file.
function getMajorGroups(){
var element = $(".item-group-button");
$.ajax({
type:"GET",
url:"localhost:6458/posApplication/getAllMajorGroups",
data:"{}",
contentType:"application/json; charset=utf-8",
dataType:"json",
done:successResult(majorGroups),
fail:errorResult(error)
});
}
function successResult(majorGroups){
var mGroups = response.d;
$("#item-groups").empty();
$.each(majorGroups ,function(){
var h3 = $('h3').append(majorGroups.code);
element.append(h3);
$("#item-groups").prepend(element);
});
}
function errorResult(error){
alert("error");
}
When I run the web page and I use firebug to trace the steps I can see the script is executed. But it does not execute the success or failure code inside the ajax call. Am I doing anything wrong here?
Below is an example of the string which the service return.
{"majorGroups":[{"update":"false","hasMore":"false","status":"A","description":"Beverage","majorGroupId":"48","code":"Beverage"},{"update":"false","hasMore":"false","status":"A","description":"Laundry","majorGroupId":"51","code":"Laundry"},{"update":"false","hasMore":"false","status":"A","description":"Cigarette","majorGroupId":"50","code":"Cigarette"},{"update":"false","hasMore":"false","status":"A","description":"Food","majorGroupId":"47","code":"Food"},{"update":"false","hasMore":"false","status":"A","description":"Health Center","majorGroupId":"52","code":"Health Center"}],"failure":"false"}
$.ajax has no property named failoure. error should be used so it looks like error: errorResult
Besides that check that request is made via Network tab in Chrome dev tools or some similar tool. Check what is in the the raw response and make sure that is what you wanted. If request failed you will see way or at least have error code.
If everything is fine so far then make sure your adding DOM elements when DOM is ready so wrap your stuff with $(function(){ /* your stuff here */ })
Edit:
That's not the way done and fail should be used. jQuery ajax call returns promise.
$.ajax({
url : "..."
/* omitted */
}).done(successCallback).fail(failCallback)
where successCallback can be either function name like your defined succes function or just anonymous function like
.done(function(response){
// do stuff with response
}
I think you should carefully read jQuery documentation.
Also your $.each call is kinda broken - you skipped parameter in function provided to $.each