craft9861
craft9861

Reputation: 214

php doesn't receive string value from ajax

I'm trying to send the id of a clicked element via ajax to php. But it isn't working. The value is being sent from php file (contacts.php) to the javascript function callMessage(id) (which does return the right id when clicked), it is then calling the php file (get_message.php) which is supposed to query the result which has the right id. But when I echo the id it returns "Undefined variable".

Here's my code:

contacts.php

<div id="<?php echo $row['id']; ?>" onclick="callMessage(this.id)">
</div>
<div id="createMsg"></div>

contacts.js

function callMessage(id) {
    var http = new XMLHttpRequest();
    var url = 'includes/get_message.php';
    http.open('GET', url, true);

    http.onreadystatechange = function() {
        if(http.readyState == 4 && http.status == 200) {
            document.getElementById("createMsg").innerHTML = this.responseText;
        }
    }
    console.log(id);
    http.send('id='+id);
}

here console.log(id) does return the id of the element that was clicked.

get_message.php

if(isset($_GET['id'])) {
    $msg_id = $_GET['id'];
}
echo $msg_id;

The echo here returns "Undefined variable: msg_id". I've also tried using POST request to send the id value but that hasn't worked either.

Upvotes: 1

Views: 46

Answers (2)

ADyson
ADyson

Reputation: 61849

A couple of issues:

  1. echo $msg_id; should be inside the if in the PHP. Logically you don't want to echo that if it isn't populated, I would expect.

  2. As per https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send, the 'id='+id will be added to the request body, whereas $_GET in PHP tries to retrieve values from the querystring. Therefore you need to attach the value to your url variable, and url-encode it.

So

if(isset($_GET['id'])) {
    $msg_id = $_GET['id'];
    echo $msg_id;
}
else echo "No ID supplied";

and

var url = 'includes/get_message.php?id=' + encodeURIComponent(id); 
... 
http.send();

is the correct solution here.

Upvotes: 1

Gal Gur-Arie
Gal Gur-Arie

Reputation: 394

You are placing the data in a GET request with the 'send' function. Submitting data via send is relevant for POST & PUT. Data under send() for GET & HEAD will be replaced with NULL. If you're using GET method use the URL parameter:

var url = 'includes/get_message.php?id=' + encodeURIComponent(id);

Upvotes: 1

Related Questions