1

I'm calling a method that is in the code-behind. Once I got the data, I'm not able to copy the data to a local variable.

I've created a local variable. I've tried to console.log the result of the Ajax call in 2 places. First, inside the success callback method, and secondly outside.

Inside the success method, I get something like [object, object, object ]. However, outside, I'm getting just an empty array [].

var rowArray=[];

$.ajax({

     type: "POST",
     url: "Default.aspx/GetData",
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     data: '{ dataId: 1 }',
     success: function (response) {
            rowArray = JSON.parse(response.d);     

            //console.log(rowArray); --> this logs [object, object, object ]
     },
     failure: function (response) {
                alert(response.d);
     }
   });

 //console.log(rowArray); --> this logs []

Any reason why I'm not able to copy the response to a local variable?

Thanks for helping

Richard77
  • 20,343
  • 46
  • 150
  • 252
  • 1
    Note that `$.ajax` is asynchronous, so your second console log, outside of the `success` function is logging the initial value of the variable, since the `$.ajax` call has not finished yet. – Heretic Monkey Apr 11 '17 at 14:42
  • 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) – Heretic Monkey Apr 11 '17 at 14:42

3 Answers3

1

Your success callback signature is wrong and you should not need to parse the JSON. Try this:

var rowArray=[];

$.ajax({
    type: "POST",
    url: "Default.aspx/GetData",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: '{ dataId: 1 }',
    success: function (response, textStatus, jqXHR) {
        rowArray = response.d;     
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log("Could not get data")
    }
});

Also, as ADyson pointed out in a comment, there is no failure callback in a jQuery.ajax call. The correct name is error and has the signature shown above. I put a simple error message in the error function, but you could use something more complicated like the example in ADyson's answer.

Community
  • 1
  • 1
  • Worth pointing out also that there's no such callback as "failure". The correct callback is "error", and the first parameter to it is a jqXHR object, which means that `response.d` will not exist in that context. `response.responseJSON` might, though. http://api.jquery.com/jquery.ajax/ . This will help the OP if debugging calls that don't succeed. I'd also argue that "errorThrown" isn't a particularly good name for the 3rd parameter in the "success" callback. The request succeeded, so no error was thrown. The actual object returned is, again, a jqXHR object and might be better named as such. – ADyson Apr 11 '17 at 14:27
  • Thank you for the correction. Error, not failure. Also, I tried to debug, and was able to experience for myself what you just said. The execution didn't wait for the ajax to complete, it went the next line. And later, it went back inside the `$.ajax function`. Amazing! – Richard77 Apr 13 '17 at 13:38
-1

Outside the "success" callback, you're getting an empty variable because ajax calls are async, so your logging of rowArray happens before the "success" callback has executed.

Inside it, since you specified "json" as the data type expected in the response, jQuery will automatically parse "response" as JSON, and therefore it will automatically become a usable object. There's no reason to parse it again. In any case, the JSON.parse method expects a string, not an object, so such a call would not succeed. See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

It's also worth pointing out, for future reference, that your error handling is incorrect. There's no such callback as "failure" in the jQuery ajax context. The correct callback is "error", and the first parameter to it is a jqXHR object, which means that response.d will not exist in that context. response.responseJSON should, though. See https://api.jquery.com/jquery.ajax for the full documentation. This will help you if debugging calls that don't succeed in future.

So overall, it's worth changing your code to the following:

var rowArray=[];

$.ajax({
  type: "POST",
  url: "Default.aspx/GetData",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  data: '{ dataId: 1 }',
  success: function (response) {
    rowArray = response.d;  
  },
  error: function (jqXHR, textStatus, errorThrown ) {
    alert("Ajax Error: " + textStatus + " " + errorThrown);
    console.log(jqXHR.status + " " + JSON.stringify(jqXHR.responseJSON));
  }
});
ADyson
  • 57,178
  • 14
  • 51
  • 63
-1

Your last console.log(rowArray) // this logs [] is executed before ajax call is terminated. If you need to execute a synchronous ajax call, just use:

$.ajax({
        type: "POST",
        url: "Default.aspx/GetData,
        async: false,
        ......

async: false will do the magic :)

...but I strongly recommend to not use this because is a bad practice.

  • 1
    Don't do this. This is really bad practice. Read it very carefully http://stackoverflow.com/a/16569628/4121714. – SouXin Apr 11 '17 at 14:55