Seth J. Freeman
Seth J. Freeman

Reputation: 35

Passing Javascript Variable To PHP Using Ajax Echo's Undefined Index

I minimized the code snippets to show only the code needed, and the url for the server side file is actually connected to a url on my server.


HTML FILE

<head>
    <script>
        var btid = 1;
        $.ajax({
            url: "serverSide.php",
            method: "POST",
            data: { "btid": btid }
        });
    </script>
</head>
<body>
    <?php include("serverSide.php"); ?>
</body>

serverSide FILE

<?php
    $btid = $_POST['btid'];
    echo($btid);
?>

DESCRIPTION

So what is going on is when the page loads, the javascript code runs. It creates a variable named btid equal to 1. This variable is then sent to a file on my server that is a php file. I want to echo that variable through php. But when I load the page, I get an error log stating that the code $btid = $_POST['btid']; has an Undefined Index.

Upvotes: 1

Views: 98

Answers (2)

Pedro Henrique
Pedro Henrique

Reputation: 619

When you use PHP's include as in <?php include("serverSide.php"); ?> PHP will execute the code on the file being included. That is what is causing your error, when the code is first evaluated it has no $_POST['btid'] because you haven't called it yet.

Your javascript will run on page load and make the ajax call correctly, but you are not using the response anywhere. In order to store the response from the Ajax call you need to add a success handler.

If I understood what you are trying correctly, your code should look more like this:

HTML FILE

<head>

</head>
<body>
    <div id="response"></div>

    <script>
        var btid = 1;
        $.ajax({
            url: "serverSide.php",
            method: "POST",
            data: { "btid": btid },
            success: function(res) {
                $('#response').text(res);
            }
        });
    </script>
</body>

What we are doing is making the ajax call and when the call is successful we assign the returned value as the div content. Also, I switched the script tag to the end of the body because we need to be sure all the document has loaded before changing anything (could have used $( document ).ready()).

Upvotes: 0

Mr Glass
Mr Glass

Reputation: 1306

I don't think your code is going to work as designed. You are using include("serverSide.php"); in the body of the HTML, but it is never going to have any $_POSTvalues unless you are posting a form.

Your ajax call is not doing anything with the value that is being returned.

I think you should remove the include("serverSide.php"); from the body of your HTML (it is serving no purpose in its current incarnation) and use the returned value of your ajax call to put the value of btid in the HTML (if that is where you want it).

Upvotes: 2

Related Questions