0

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?

0

2 Answers 2

2

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);
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

PHP's header() function must be called like this: header('Content-Type: application/json');
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.