Here is the scenario: I am getting data from database through web server. Based on that data page sends another request to the same server to perform some action. Simplified structure is the following:
var datacon;
$.post('method',function(data){
datacon = data;
// populating some tags;
}) // end of post
//some other staff happening;
$.post('other',{datacon}, function(env){
...// taking data from populated tags
$("div").load(env);
...
}) // end of post
This happens every time user enters the page. This code doesn't work in a sense that datacon is empty when the page is opened. But if I will refresh it once or twice, it starts working. Second $.post works perfectly, checked hundreds of times. I changed first $.post with $.get, but it doesn't help.
Probably it concerns asynchronous / synchronous calls. I don't understand much why it happens. Please help.
p.s. server is CherryPy.
As these calls are asynchronous, it possible that the second call is running before the first has completed. To ensure that they run in the correct order, place the second ajax call in a done() function at the end of the first. That way, the second will only be run when the first is finished.
Here is a sample from a project I'm working on:
$("#leftcolumn").activity(); $.ajax({ type: "GET", url: "/search", cache: false, data: {searchterm: searchterm} }).done( function(reply) { $("#leftcolumn").activity(false); showSearchResults(reply); });
The first line shows a progress indicator on the screen. Then the ajax call does a search. At the end in .done, I then disable the progress indicator I was showing and then display the search results. Putting the code I want to execute in .done guarantees that it won't run until the ajax call is finished.