14

So I'm trying to achieve the following, but I can't figure out how to make this work.

$.ajax({
  url: "whatever.php",
  method: "POST",
  data: { myVar: "hello" },
  success: function(response) {
    console.log('received this response: '+response);
    console.log('the value of myVar was: '+data.myVar); // <<<< data.myVar is not accessible from here
    console.log('the value of myVar was: '+myVar); // <<<< myVar is not accessible from here
  }
});

Is there a way to access the value of myVar in the .success() function? Can I somehow get to the original data object that was sent in this ajax request, in the .success() function?

Hoping for your solutions. Thanks!

Xriter
  • 160
  • 1
  • 1
  • 8
  • did you test just console.log(myVar) ? – Gabriel Rodrigues Feb 13 '16 at 22:17
  • @Gabriel Rodrigues Yes I did, but that didn't work... – Xriter Feb 13 '16 at 22:18
  • No. There is no way to access that argument to `$.ajax()` from within the success handler. You can certainly assign that argument to a higher scoped variable and then pass that variable. Then, you will be able to access that variable from within the `success` handler. – jfriend00 Feb 13 '16 at 22:19
  • @jfriend00 That was the only thing I could think of either. – Xriter Feb 13 '16 at 22:23
  • Does this answer your question? [Access "data" object in AJAX request inside success function](https://stackoverflow.com/questions/37818214/access-data-object-in-ajax-request-inside-success-function) – Zeeshan Eqbal Jan 21 '20 at 17:03
  • DUPLICATE = Please refer to the below question: [Access “data” object in AJAX request inside success function](https://stackoverflow.com/questions/37818214/access-data-object-in-ajax-request-inside-success-function) – Zeeshan Eqbal Jan 21 '20 at 17:04
  • DUPLICATE = Refer to the below Question [Access “data” object in AJAX request inside success function](https://stackoverflow.com/questions/37818214/access-data-object-in-ajax-request-inside-success-function) – Zeeshan Eqbal Jan 21 '20 at 17:05

6 Answers6

6

You can use this to access the whole object. So you can do something like this:

$.ajax({
  url: "whatever.php",
  method: "POST",
  data: { myVar: "hello" },
  success: function(response) {
    console.log('received this response: '+response);
    console.log('the value of myVar was: '+this.data.myVar);
  }
});
Piyin
  • 1,823
  • 1
  • 16
  • 23
6

All of the other answers, except for Piyin's, are unreliable and a bad practice.

AJAX requests are, by their very nature, asynchronous. That means that by the time the response gets back from the server, the variable that they set may have been changed. If you want an example, just make two buttons that both fire the same code, but set myData to a different value, and click them each quickly before the response gets back... now the variable has been changed and you'll get unreliable results.

Piyin's answer is good as well, but sometimes you get different formats of the sent data. It might be a JSON object that's been stringify'd, it might be in GET format with query strings, etc.

The easiest way on the coder (although it does create a bit more overhead in RAM) is to assign a new property of the AJAX object and access it in the callback, like this (using Piyin's example):

var dataToSend = { myVar: "hello" };
$.ajax({
  url: "whatever.php",
  method: "POST",
  data: dataToSend,
  sentData: dataToSend, //add this property
  success: function(response) {
    console.log('received this response: ' + response);
    console.log('the value of myVar was: '+ this.sentData.myVar); //access sentData property
  }
});
Sean Kendle
  • 3,538
  • 1
  • 27
  • 34
  • 1
    Many thanks! This is actually the only method that worked reliably for me. I had the issue because I was using this in a loop. This is where async shows you that the external scope is not a good idea. And even this.data seemed to fail me for some reason. – Mig Mar 21 '22 at 14:36
  • 1
    If you `console.log` your `this.data` variable, is it a string? That's happened to me, and you have to `JSON.parse()` it. – Sean Kendle Mar 21 '22 at 15:30
  • no it does like an external scope variable. I almost always get the previous value of the iteration, and consequently twice the same thing on the last 2 iterations. – Mig Mar 22 '22 at 08:48
  • 1
    Well, I'm glad my solution worked for you! I've been using it for years. – Sean Kendle Mar 22 '22 at 15:46
0

Just store the data you are posting in a variable first.

var data = {myVar: "hello"}
 $.ajax({
  url: "whatever.php",
  method: "POST",
  data: data,
  success: function(response) {
    console.log('received this response: '+response);
    console.log('the value of myVar was: '+data.myVar); 
  }
});
powerc9000
  • 2,030
  • 19
  • 30
  • As mentioned in other comments, this is not reliable because Ajax is async. If you use this in a loop for example, what you'd get is very often the value of the previous iteration, not the current one. – Mig Mar 21 '22 at 14:00
0

Create a data object so that you can then access in various parts of the request

var postData ={ myVar: "hello" };

$.ajax({
  url: "whatever.php",
  method: "POST",
  data: postData ,
  success: function(response) {
    console.log('received this response: '+response);
    console.log('the value of myVar was: '+postData.myVar); 
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • As mentioned in other comments, this is not reliable because Ajax is async. If you use this in a loop for example, what you'd get is very often the value of the previous iteration, not the current one. – Mig Mar 21 '22 at 13:59
0

Generally, if you want to be able to reference data more than once, you need to make sure it's in the proper scope. The scope of the json data object you're passing inside .ajax() is the ajax function. If you want to be able to reference the value of data: outside of that, for example the scope in which you're calling .ajax(), the simplest way is just to assign it to a variable. eg

myData = { myVar: "hello" };
$.ajax({
  url: "whatever.php",
  method: "POST",
  data: myData,
  success: function(response) {
    console.log('received this response: '+response);
    $("#response").html(response);
    console.log('the value of myVar was: '+myData.myVar); // <<<< data.myVar is not accessible from here
    $("#myVar").html(myData.myVar);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="response"></p>
<p id="myVar"></p>
JustCarty
  • 3,839
  • 5
  • 31
  • 51
Lindsay Ryan
  • 433
  • 3
  • 9
  • 2
    One thing I don't understand then: the json `data` object is in the `.ajax()` scope. The `.success()` function is the `.ajax()` scope **as well** right? So why then can't I access the `data` object in the `.success()` function? – Xriter Feb 13 '16 at 22:36
  • 1
    okay so the JSON object is anonymously passed in as an input parameter in `.ajax()`. let's say we defined it as a variable outside instead, though. `var ajaxJSON = { ... success: function(response){//your console calls}, ...};` you don't have control over the logic inside `.ajax()` but at some point it _calls_ the function we defined as `ajaxJSON.success()`. and it passes the `response` to that. So you're not really still in the scope of `.ajax()` at that point. you're inside the scope of `ajaxJSON.success()`. Does that help? – Lindsay Ryan Feb 13 '16 at 22:39
  • 1
    This is a sloppy way to get "myData" within the success function. Ajax is asynchronous. The value of "myData" could well have changed by the time the response is returned, say, if a user is clicking multiple elements that run the same function... do not do this. You can get it via `this.data`, as Piyin explains. – Sean Kendle Jan 04 '20 at 19:04
  • Or, check out my solution below, which may be a bit more reliable than Piyin's example. (https://stackoverflow.com/a/59845123/1410567) – Sean Kendle Jan 21 '20 at 16:15
  • 1
    @SeanKendle Indeed. I used something similar in a loop and because it is asynchronous I got twice the same value for the variable. Accessing the outside scope is definitely not reliable. – Mig Mar 21 '22 at 13:57
-1

You can always do something like the following:

var myData = '{ myVar: "hello" }';

$.ajax({
    url: "whatever.php",
    method: "POST",
    data: myData,
    success: function(response) {
        console.log('the value of myVar was: ' + myData.myVar);
    }
});

Or even better

var myData = {
    myVar: "hello"
};

$.ajax({
    url: "whatever.php",
    method: "POST",
    data: JSON.stringify(myData),
    success: function(response) {
        console.log('the value of myVar was: ' + myData.myVar);
    }
});