Skip to content
Advertisement

AJAX calls server but POST fails (PHP)

just trying to implement a basic ajax request. the js calls the server and will recieve a response back but now i need to send a parameter to get a specific value back from the server so i send form data via POST. the PHP script recognizes that a $_POST request was submitted but if i access the data in $_POST i get error “Undefined array key “item”” Any help? I get one s

//javascript script
function doTHIS()
{
    var data = new FormData();
    data.append('item', 'apple');
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function()
    {
        if (this.readyState == 4 && this.status ==200)
        {
    
            document.getElementById("idName").innerHTML = this.responseText;
        }
    }
    xhttp.open("POST", "ajaxScript.php", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send(data);
}


//php script
if( $_SERVER['REQUEST_METHOD'] == 'POST')
{   
    if($_POST["item"]=='apple')
        echo "sucess";
    else
        echo "fail";
}

I get fail everytime. I have been reading w3school and various other resources ALL DAY! I am handling the form data wrong i think but dont see how. I have varied the syntax 100 different ways.

Advertisement

Answer

Everything looks good except FormData object, you are not passing any form element, if you need to send just parameter use below for creating data & you should be good

var data = ‘item=apple&item2=mango’;

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement