I have a simple click function with the code below, but I can’t seem to get the data on the first click.
$.ajax({
type: 'POST',
url: 'test/get/1',
success: function (result) { testit = result; },
dataType: 'json',
data: 'js=1'
});
alert(testit);
In my callback function I simply have return drupal_json(‘hello’); but it doesn’t show up until the 2nd time around. For example, if I click the button, nothing will happen, but if I click it again, it will alert ‘hello’. In a case where there is dynamic data, then it will also be delayed by one click. For example, let’s say clicking the first time should alert 1, 2nd time should alert 2, and so on. Instead, the first click will do nothing, the 2nd click will alert 1, the 3rd click will alert 2, etc. Any ideas why that is happening? Thanks.
the
ainajaxstands for asynchronous. therefore,testitwill not be set to the result of the ajax’s response until thesuccess:function is called (when the ajax call is successfully completed)if you’d like it to work synchronously, you can also set
aysnc:falsein jQuery’s.ajaxoptions, like so:in the second method, ALL javascript will be delayed until the ajax call is complete (usually noticeably slow). I’d recommend just doing your code in the
success:callback from the first example. however, you may want to create anerror:callback, too, just in case something fails (otherwise your callback may NEVER get called, because there was no success).