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.
echo $msg_id;should be inside theifin the PHP. Logically you don't want to echo that if it isn't populated, I would expect.'id='+idwill be added to the request body. Whereas $_GET tries to retrieve values from the querystring. Sovar url = 'includes/get_message.php?id=' + id; ... http.send();is probably the correct solution. Try it and let me know.