1

I am banging my head against the wall with this one. The answer to my question should be here and here, and I don't want to post a duplicate. But for some reason, my code, though seemingly exactly the same as these examples, won't work.

I'm trying to pass an ID from a Javascript function to a PHP function via an xmlhttprequest. Here is my Javascript function:

function acceptRequest(id_Request)
{
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "acceptRequest.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function()
{
    if (xhttp.readyState == 4 && xhttp.status == 200)
    {
        alert("Request accepted.");
    };
};
xhttp.send("id_Request="+id_Request);
}    

My PHP file, acceptRequest.php, looks like this:

<?php
echo $_POST['id_Request'];
?>

What happens is that the Javascript function does send the alert: "Request accepted." But, the PHP function doesn't echo anything out. What am I missing here???

1 Answer 1

0

I guess the problem is that your function isn't passing any id. I'm sure in your php/javascript. The id you want to pass is in some input box.

Then in your js function, you can say

Var id = document.getElementById("id-of_input").value;

You can then append this to you Ajax request.

I also noticed that your Ajax get no response from the php.

 if(xmlhttp.readyState == 4 &&.      xmlhttp.status == 200){
   document.getElementById(where).innerHTML = xmlhttp.responseText;

}

In your case, it'ld be xhttp.responseText;

That line just means where you wish to display the results of the Ajax request.

Sign up to request clarification or add additional context in comments.

3 Comments

This makes sense, but even if I have it echo "test" or some other constant, it still does not print anything.
I see the problem. In your php script, not the one conned to your Ajax request. The response is going no where create a div,and give it an id. Now in your js function, where the code say if xhttp=4&200... put this code inside that statement, var theDiv = document.getElementById("id_of_the_new_div"). Then theDiv.innerHTML = xhttp.responseText; now you can get a reply from the Ajax php.
Code, modified... hope you find it useful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.