0

I am trying to load from a PHP file using ajax, some JSON objects but my problem is that my javascriptcode is not working on the correct order. Here is my code:

var requests;
$(document).ready(function(){
   setInterval(function(){
       $.ajax({
         url: "test2.php", 
         success: function(result){
         requests = JSON.parse(result);
         alert(requests);
         }
       });
   })
});
alert(requests);

Here is the first alert i'm getting on page load and here is the second alert

My question is why the alert in the last line is executed before the ajax

Note: this is a small example of my project, my real error is that i cannot load some arrays i need using ajax, because it shows as undefined at console, even if the ajax is in the beginning of the script.

Nikos12071
  • 51
  • 1
  • 1
  • 9
  • because first one needs time to load – Özgür Ersil Jan 16 '17 at 11:29
  • 3
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – freedomn-m Jan 16 '17 at 11:29
  • Because it's *asynchronous* - ie starts the ajax request, then carries on before the request has completed. Even more so, your 2nd alert runs before the `$(document).ready()` fires, which is an event that occurs later, when the document is ready. – freedomn-m Jan 16 '17 at 11:30
  • better you try using the `complete` handler in `$.ajax` – Muhammed Shevil KP Jan 16 '17 at 11:30

3 Answers3

1

The best way to avoid this is to create a function in which second alert would be placed. And call this function inside ajax call's success method. e.g.

ajax({
...
success: function(){
...
secondAlert();
};
...
});

function secondAlert(){
alert("alert after jax call");
};
vishal kokate
  • 126
  • 3
  • 12
1

try this cod for ajax call with php

 $.ajax({
  type: "method", // post or get
  url: "file url",
  dataType: "json",
  success: function(data){
 
  },
  error: function(){

  }
});
Trushar Narodia
  • 366
  • 4
  • 19
0

As for

My question is why the alert in the last line is executed before the ajax

AJAX is an acronym for Asynchronous JavaScript and XML. The keyword here is asynchronous. AJAX sends the HTTP request and keeps executing the code in async fashion. The callback function of the AJAX request is executed after the request is finished and the corresponding response has been received. More info is available here

Community
  • 1
  • 1
sid-m
  • 1,504
  • 11
  • 19