Abu P R
Abu P R

Reputation: 41

responseText doesn't return the success message

I am trying to insert data into database using Ajax and PHP. Now what's the problem is that the responseText doesn't return any message but the insertion done sucessfully Here is my script

    <script type="text/javascript">
    function aa() 
    {
        var x=new XMLHttpRequest();
        x.open("GET","ajax.php?na="+document.getElementById("t1").value+" &ag="+document.getElementById("t2").value+"&des="+document.getElementById("t3").value+"&em="+document.getElementById("t4").value+" ",true);
        x.send(null);
        document.getElementById("d1").innerHTML=x.responseText;
    }
</script>

This is my ajax.php

<?php 

$mysql_host = 'localhost'; 
$mysql_database = 'proj1'; 
$mysql_user = 'root'; 
$mysql_password='';
$mysqli = mysqli_connect($mysql_host, $mysql_user, $mysql_password, $mysql_database);
if (mysqli_connect_errno($mysqli))
{
    echo 'Failed to connect to MySQL: ' . mysqli_connect_error();
}
$name = $_GET['na'];
$ag = $_GET['ag'];
$des = $_GET['des'];
$em = $_GET['em'];
$sql=mysqli_query($mysqli,"insert into ajax_sample (id,name,age,desig,email) values ( '', '$name', '$ag' ,'$des', '$em'  )");
if($sql)
{
    echo "Successfully Inserted....";
}
?>

and this is my html page

     <form name="f1" method="post">
    <input type="text" id="t1" placeholder="enter name"><br><br>
    <input type="text" id="t2" placeholder="enter age"><br><br>
    <input type="text" id="t3" placeholder="enter designation"><br><br>
    <input type="text" id="t4" placeholder="enter email"><br><br>
    <input type="button" id="b1" value="submit" onclick="aa();">
    <div id="d1"></p></div>
</form>

Upvotes: 2

Views: 263

Answers (1)

Cymen
Cymen

Reputation: 14419

You need to hook into async change callback with onreadystatechange to handle the case when the XHR request is done. Then .responseText will be set on it.

function aa() 
{
    var x=new XMLHttpRequest();
    x.open("GET","ajax.php?na="+document.getElementById("t1").value+" &ag="+document.getElementById("t2").value+"&des="+document.getElementById("t3").value+"&em="+document.getElementById("t4").value+" ",true);
    x.onreadystatechange = function() {
      if (x.readyState == 4 && x.statusCode == 200) {
        document.getElementById("d1").innerHTML=x.responseText;
      }
    };
    x.send(null);
}

It is important to understand that an XMLHttpRequest is asynchronous. That basically means you request a URL to be access via JavaScript and the browser/JS engine goes off and does that. You can hook into when the request is finished by using onreadystatechange. The MDN page linked below has a table with the potential values for readyState.

MDN: XMLHttpRequest and tutorial Using XMLHttpRequest

Upvotes: 3

Related Questions