0

I'm trying to get the data out of the success part of an AJAX call. So I tried to write a callback function for that purpose. I have this code :

  var data2;
  $(function () {
    function callback(data) {
      console.log(data);
      data2 = JSON.parse(data);
      console.log(data2);
    }

    $("myForm")
      .submit(function (event) {
        $.ajax({
          type: 'POST',
          url: "/...",
          data: "JASON",
          success: callback
        });
      });

    console.log(data2);

  });

In the console I see this in that order : undefined, content of data and content of data2.

What I can't understand is, why am I getting undefined at first? Shouldn't I be geting the value of data first? Why is the last console.log is executed first? And most importantly, is my approach to get data from AJAX call is correct? What else can I do to get data? Thanks.

starrr
  • 41
  • 9

5 Answers5

2

The AJAX-call is asynchronous, which means that after the call has been made, the code continue to the next step before the call is completed.

So when the AJAX-call has been made, console.log(newdata2); is reached and my guess is that newdata2 is undefined.

When, after som time (even though it is a very short time) the call will get its response and the callback-function will be called.

Cleared
  • 2,490
  • 18
  • 35
  • Thanks for the answer, can you tell me what to do in this situation? – starrr May 04 '17 at 11:38
  • You call for the data, and you get the data. So what is the problem? What behaviour do you want? – Cleared May 04 '17 at 11:39
  • I want `console.log(newdata2);` not to return undefined, when I call it, it should be defined. – starrr May 04 '17 at 11:44
  • @starrr Check the duplicate – Andreas May 04 '17 at 11:44
  • 1
    @starrr But you do not define `newdata2` anywhere, so how can you expect it to be defined? – Cleared May 04 '17 at 11:45
  • It's `data2` not `newdata2` – starrr May 04 '17 at 11:47
  • `data2` seems undefined – starrr May 04 '17 at 11:48
  • Put `console.log(data2);` in the callback function instead, thats the only place you know that it will be defined. The purpose of an AJAX-call is for the code to continue, even if you do not have the data. If you need to use the data, do so in the callback function. – Cleared May 04 '17 at 11:53
  • @Cleared I tried to write in the callback function. But it still gives undefined. Could you give a simple example please? I'm very new to JavaScript. – starrr May 04 '17 at 12:25
  • @starrr In your question you state "In the console I see this in that order : undefined, content of data and content of data2". The last "content of data2" is from the callback function, so it should not give you undefined inside the callback function. – Cleared May 04 '17 at 13:43
2

The JavaScript as you have it is non blocking. As the code gets run by the event loop, it'll log out whatever it needs to. Once the Ajax request gets completed, data2 will get its new value... but by then, you would have have already run the outer most console.log(data2)

 var data2;                      // no value gets assigned thus is undefined
 $(function () {

    function callback(data) {
      console.log(data);         // I get logged second
      data2 = JSON.parse(data);
      console.log(data2);        // I get logged last (now with a value, as I'm the success callback)
    }

    var frm = $("myForm");
    frm.submit(function (event) {
      $.ajax({
        type: 'post',           // post: meaning we're submitting/sending something
        url: "/...",
        dataType: "json",       // not JASON but json, (Java Script Object Notation)
        data: frm.serialize(),  // get data from the form
        success: callback
      });

     event.preventDefault();    // stop actual form submission.
    });

   console.log(data2);          // I get logged first (no value yet)

 });

Visual demo of this event loop,

Have a look at the above, the whole process is visualized using a tool that'll hopefully make things a bit clearer. (Open up the dev console, then click on run and see the magic)

As @MarcosPrez mentioned, you also have a syntax error. dataType should be json, unless you actually want to submit a text value of JASON to whatever API you're calling.

To be clear, the code you want to run next in your app (post call completion), SHOULD be in the callback, and not just next to the Ajax call.

Rohan Büchner
  • 5,333
  • 4
  • 62
  • 106
1

This statement:

 console.log(newdata2);

is out of the ajax call, it is after. This means it's executed right after the call starts but not after the call ends.

jackstrapp
  • 195
  • 10
0

This is happening due to async nature of javascript. Since the ajax call is async, console.log(newdata2); is executed first (as said by Cleared in above answer). On success of ajax call (async), your callback functions are called.

Abhishek Sharma
  • 2,485
  • 1
  • 21
  • 35
-1
  1. Set normal url for request.
  2. Set response data type.
$.ajax({    
    type: 'POST',
    url: "/request/",
    dataType: "text", // json etc.
    success: function (data) {
        callback(data);
    }    
});

Manual

brasofilo
  • 25,496
  • 15
  • 91
  • 179
Alexey Samara
  • 131
  • 1
  • 13
  • I did what you said, nothing changed. – starrr May 04 '17 at 11:40
  • 1
    read answer ) you don't need data2 = JSON.parse(data); - you can set dataType, also you don't send response of ajax callback to your function. I've try my answer and it's work – Alexey Samara May 04 '17 at 12:07