Reputation:
I have some problem with this part of a code:
<script>
function komenty(photoid) {
var xmlhttp=new window.XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var x = xmlhttp.responseText;
$.post('main.php', {x: "foo"});
}
}
xmlhttp.open("GET", "comments.php?id=" + photoid, true);
xmlhttp.send();
}
</script>
I am trying to send this variable to my php script on the same page which is main.php The responseText is not empty, there are few strings inside of it. But in my php script it says that "variable x is undefined"
<?php
echo "<a href='#' class='my-button' onclick='komenty(".$photoid.")'>komentarze</a>";
$x = $_POST['x'];
echo $x;
?>
I am not sure if i clearly understand the jquery manuals
Upvotes: 2
Views: 60
Reputation: 780724
You should either use a different script for the AJAX call than displaying the main page. Or the main.php
script needs to check whether it was called using GET
or POST
.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Respond to AJAX call
$x = $_POST['x'];
echo $x;
} else {
// Display normal HTML
echo "<a href='#' class='my-button' onclick='komenty(".$photoid.")'>komentarze</a>";
}
Upvotes: 1