jQuery ajax request: how to access sent data in success function?
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);
}
});
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
}
});