John Smith John Smith - 5 months ago 15
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:

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();"GET", "data.php");

xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {

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
parenthesis, but I'm not sure how exactly this is done?

Also, can the
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?



Please try:


... or can use something more elegant:

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