saurabh sharma saurabh sharma - 4 months ago 8
Javascript Question

pass the value to database

I want to pass the value from the Ajax code to the database as this program is to show the details of the user, but there is an error in the code in passing the value. What can I do now?



function showUser() {
httpRequest = new XMLHttpRequest();

if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
var id = document.getElementById("id").value;
httpRequest.onreadystatechange = alertContents;

httpRequest.open("GET", "http://localhost/cart/guser.php?id=" + id + "&rand=" + , true);
httpRequest.send();
}

function alertContents() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
document.getElementById("txtHint").innerHTML = httpRequest.responseText;
}
}
var id = document.getElementById('id').value;

}

<form>
enter digit :
<input type="text" id="id" name="id" />
<br />
<input type='button' onclick='showUser(this.value)' value='select' />

</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b>
</div>





below code is for guser.php



<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}

table, td, th {
border: 1px solid black;
padding: 5px;
}

th {text-align: left;}
</style>
</head>
<body>

<?php
$q = intval($_GET['q']);

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "cart";

$conn = mysqli_connect($servername, $username, $password, $dbname);

if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}


mysqli_select_db('cart',$con);

$sql="SELECT * FROM user_details WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);

echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>email</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>




Answer

Try This:

Add in head:<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>

you have to type person id in inputbox and user info in texthint div:

you will get id in guser.php of user from post and run query.and echo user info into guser.php file

<script type="text/javascript">
    function showUser($id){

    $("#email").keyup(function(){
        $.ajax({
        type: "POST",
        url: "http://localhost/cart/guser.php",
        data:'keyword='$id,
        success: function(data){
            $("#txtHint").html(data);

         }
        });
    });
}
   </script>