Reputation: 67
I just started studying PHP and Ajax and I can't figure out how to bring a single variable from PHP file to my html file using Ajax. Can you please explain me how it works?
So far I understood that you create the request:
var xhttp = new XMLHttpRequest();
And that you send it to the server:
xhttp.open("GET", "demo_get.php", true);
xhttp.send();
Then you get the data from the PHP file using
xhttp.responseText
Now, I only want to send a variable from the server, for example
$name = "John"
How should my php code look like in order to send only that specific variable?
Upvotes: 0
Views: 288
Reputation: 1033
I suggest using JSON as data interchange format, here is the javascript part:
let request = new XMLHttpRequest();
request.open('GET', 'demo_get.php', true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success
let parsed_response = JSON.parse(this.response.trim());
console.log(parsed_response.my_var);
} else {
// Error
console.log(this.response);
}
};
request.onerror = function() {
console.log('Connection error!');
};
request.send();
The PHP part then would look like this:
<?php
header('Content-Type: application/json');
$my_response_data = ['my_var' => 'foo'];
echo json_encode($my_response_data);
exit;
... and some useful info about XMLHttpRequest.responseText vs XMLHttpRequest.response
Upvotes: 0
Reputation: 3730
As a beginner, it would be a lot easier to use jQuery for your AJAX requests. I've been in this industry for over half my life and I still use it alot.
getstuff.php
header('Content-type: application/json');
echo json_encode(["FirstName" => "John"]);
exit;
jquery:
$.ajax({
url: '/getstuff.php',
success: function (response) {
console.log(response);
alert(response.FirstName);
}
});
Upvotes: 2