1

I'm trying to print out the value of a PHP variable in the browser's console by using jQuery and AJAX. The $.ajax function seems to be the way. The main problem is that I don't know what am I supposed to assign to the data parameter and what to pass as the success function parameter.

This is the PHP file:

<?php
    $foo = "Hello, World!";
?>

And this is my attempt at AJAX:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Lorem ipsum</title>
        <meta charset="utf-8">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    </head>
    <body>
        <script>
            $.ajax({
                url: "../scr/main.php",
                type: "POST",
                data: /* What am I supposed to put here? */
                success: function(/* And what am I supposed to put here? */) {
                    console.log(/* The value of $foo */);
                }
            });
        </script>
    </body>
</html>

1 Answers1

0

Taking each line in turn:

data: /* What am I supposed to put here? */

data should contain the data you want to send to the PHP file. In your case you are not sending any so it can be omitted. If you did want to send data, use an object like this:

data: { foo: 'bar' }

Then you would read it from your PHP like this:

$_POST['foo'] // = 'bar'

success: function(/* And what am I supposed to put here? */) {

The success handler function accepts the content of the response as an argument. As such, you can provide any valid variable name. Generally 'response' is used.


To actually return the information I would suggest you use a formal data structure as returning plain text has a lot of pitfalls which can cause issues. A common choice for this is to use JSON.

To return JSON from PHP simply use json_encode. This will return the message you require with a key you can use to access it through the response object in the success function.

Putting all that together looks like this:

<?php
  $foo = "Hello, World!"
  echo json_encode(array('message' => $foo));
?>
$.ajax({
  url: "../scr/main.php",
  type: "POST",
  success: function(response) {
    console.log(response.message);
  }
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • I tried your PHP code with the `$.ajax` function, but it doesn't do anything. The console says, that line 15, which has this chunk of code `console.log(response.message);` is undefined. EDIT: I fixed it. I had to replace the function parameter parameter and the `console.log` value with `message`. –  Nov 12 '20 at 19:19
  • I have one more question. The content loaded with the `$.ajax` function completely replaced all original content on the page (headers, paragraphs etc.). Can I somehow load the AJAX content without it replacing anything on the page? –  Nov 12 '20 at 20:00