Azad
Azad

Reputation: 5264

unable to get POST data in php 'undefined index' error

I am using plain javascript for Ajax request. when sending data by post method php throwing an error.

index.php

<html>

    <header>

        <script>
            function submit(){

                var userName = document.getElementById("username").value;
                var passWord = document.getElementById("password").value;


                var data = "username=" + userName + "&password=" + passWord;

                //send ajax request
                var xmlHttp = new XMLHttpRequest();
                xmlHttp.onreadystatechange = function()
                {
                    if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
                    {
                        console.log(xmlHttp.responseText);
                    }
                }
                xmlHttp.open("post", "validateuser.php");
                xmlHttp.send(data);
            }
        </script>

    </header>

    <body>

            <label>User Name : </label>
            <input type="text" name="username" id="username"/>

            <label>Password : </label>
            <input type="text" name="password" id="password"/>

            <button onClick="submit()"> Login</button>

    </body>

</html>

validateuser.php

<?php

    $userName = $_POST["username"];
    $password = $_POST["password"];

echo $userName . $password;

Upvotes: 1

Views: 1042

Answers (2)

user5570620
user5570620

Reputation:

In Javascript ajax for post you need to add following line in your code:

xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

You can check documentation and example W3schools and developer mozilla

And for more reliable code just add following line to your php code

if(isset($_POST['username']) && isset($_POST['password'])){
     //your code
}

Upvotes: 5

Nijraj Gelani
Nijraj Gelani

Reputation: 1466

You need to set the headers on your xmlHttp object. Add the following line before xmlHttp.send(data); line :

xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

Upvotes: 1

Related Questions