2

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

14
  • What happens if you change to {x: "foo"}? Commented Dec 23, 2014 at 2:17
  • @Barmar The same: "Notice: Undefined index: x in /main.php on line 627" Commented Dec 23, 2014 at 2:20
  • Undefined index is usually associated with POST variables and not having a name attribute for it, and/or an id for the form element. Commented Dec 23, 2014 at 2:21
  • @Fred-ii- He's not using a form, he's using AJAX. Commented Dec 23, 2014 at 2:23
  • Is there some way that you could be executing main.php without going through that $.ajax call? Do you ever access the script directly using the browser? Commented Dec 23, 2014 at 2:25

1 Answer 1

1

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>";
}
Sign up to request clarification or add additional context in comments.

8 Comments

The else is being executed, but im not sure how to use that information :D
Glad to see a solution was found. Way to go.
@Fred-ii- Well, this shows that the variable didn't go through POST right? so where did it go then XD
@asdasdasd That, I couldn't tell you. Ask Barmar ;-)
@asdasdasd When you load the page in the browser, it's a GET request, not a POST. You can access URL parameters with $_GET['paramname'], e.g. main.php?foo=bar would set $_GET['foo'].
|