Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing ajax POST response in javascript

I'm making ajax POST request from javascript function:

function UpdateMetrics() {
   $.ajax({
              type: "POST",
              url: "MyHandler.ashx?Param1=value1",
              data: "{}",
              contentType: "text/json; charset=utf-8",
              dataType: "text",
              success: function (msg) {
                  var jsonUpdatedData = msg;
                  ...
              }
          });
}

From my handler, I'm sending json string with:

context.Response.write(json);

I think I'll get it in msg.

I also want to send other string (count). So I'm trying to use header info along with json data. So I added this line:

context.Response.Headers.Add("MaxCount",Convert.ToString(tempList.Count)); 

If this is right way to do it, how can I access it in my success function?

like image 299
mike44 Avatar asked Mar 07 '26 11:03

mike44


1 Answers

To access headers in your success function, add in 2 more arguments to your function, the status code and the jqXHR object, which you can read the documentation for at api.jquery.com.

So, your function should look like:

success: function (msg, status, jqXHR) {
    var jsonUpdatedData = msg;
    ...
}

However, as pointed out in comments, it's probably best not to use the header to send data. You should probably just include it in the json you send out.

You also need to tell jQuery to interpret the response as json by setting

dataType: "json"

Otherwise, it will just be returned to you as text.

like image 127
Xymostech Avatar answered Mar 09 '26 01:03

Xymostech