John Smith John Smith - 2 months ago 8
PHP Question

How should variables be passed through from JavaScript to PHP when using Ajax?

Firstly, I'm aware that variations of this question has been asked before. However, in all prior example, the asker of the question has been using Ajax looking something like this:

$.ajax({
type: "POST",
url: 'logtime.php',
data: "userID=" + userID;
});


However I am unfamiliar with this style. The way I have been taught to make Ajax requests is using code of the following form:

var xhr = new XMLHttpRequest();
xhr.open("GET", "data.php");
xhr.send();

xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
//DEFINE CALLBACK FUNCTION
}
}


So, using the above Ajax style that I am familiar with, how should data be sent to the server to be processed by my php file data.php? I know it's something to do with including it in the
xhr.send()
parenthesis, but I'm not sure how exactly this is done?

Also, can the
GET
method be used if we wish to retrieve data from a database, but must provide a variable to the php in order for it to select the correct data from the database?

Lastly, what is the difference between the Ajax method I have been taught, and the other method I mentioned, which I often see mentioned on SO?

Thanks.

Answer

Please try:

  `xhr.send('you_user=user&your_password=password');`

... or can use something more elegant:

var d = new FormData();
d.append('you_user', 'person');
d.append('your_passowrd', 'password');
// ...
xhr.send(d);
Comments