Shaam Shaam - 14 days ago 6
Ajax Question

Not getting any response when using AJAX

This is my html page

<html>
<head>
<title>Using AJAX</title>
</head>
<script type="text/javascript" src="ajax.js"></script>
<body>
<form action="searchItems.php" name="searchItem" method="post">
Enter item name : <input type = "text" name = "itemName" id = "itemName" placeholder = "Enter item name" onblur="ajax()" />
<input type = "submit" name="submit" id="submit" value="Search" />
<input type = "reset" name = "reset" id= "submit" value = "Reset" />

<div id="desc"></div>
</form>
</body>




This is the php page when the form is submitted. The results are as expected.

<?php
include('dbconnect.php');
if (isset($_POST["submit"])) {
//echo "<pre>".print_r($_POST,1)."</pre>";
$conn = db_connect();
$name = $_POST['itemName'];
$query = "SELECT * FROM itemreceived where name = '" . $name . "'";
$result = $conn->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_object()) {
echo $row->description;
}
} else {
echo "No result";
}
}
?>


This is the dbconnect.php page used in the searchItems.php page

<?php
function db_connect()
{
$conn = null;
$servername = "localhost";
$username = "root";
$pwd = "";
$db_name = "ebay_db";
$conn = mysqli_connect( $servername, $username, $pwd, $db_name );
if ( !$conn ) {
die( "Connection failed :" . $conn->connect_error );
}
If ( $conn ) {
//echo '<script type="text/javascript"> alert("Connection successful"); </script>';
}
return $conn;
}
?>


This is the ajax() function used in the html page to get the result in the div "desc".

function ajax(){
var itemName = document.getElementById('itemName').value;
console.log(itemName);
var url="searchItems.php";
envelop = new XMLHttpRequest();
envelop.open("POST",url,true);
envelop.onreadystatechange=displayResult;
envelop.setRequestHeader("Content-type","application/x-www-form-urlencoded");
envelop.send('itemName='+itemName);
alert("Calling ajax");


}

function displayResult(){
if((envelop.readyState==4) &&( envelop.status==200)){
document.getElementById('desc').innerHTML=envelop.responseText;
alert("Part 2");
}
}


When I submit the form, I get the expected result in the page searchItems.php
The ajax() function is not working. The objective is to get the result in div "desc" as soon as the function blur() is activated.

Answer

remove isset($_POST["submit"]) because its just only for submiting form and it returns fals for your ajax function!