This question already has an answer here:
I am using this js code for an ajax request and getting the data, this code works well & show the data in the textbox. But for some reasons, I want to get the value of js variable id1 into php code(index.php). I tried but not able to get the value of id1 into php code, plz help.
HTML CODE:(index.php)
<body>
<input type="text" name="urn_no" ID="urn_no" value=""/>
<input type="number" name="mob_1" ID='mob_1' value="" onkeydown="getData(this.value);" />
</body>
JS CODE:(code in index.php)
function getData(val) {
$.ajax({
type: "POST",
url: "test.php",
dataType: "json",
data:'dt='+val,
success: function(data){
var len = data.length;
if(len > 0){
var id1 = data[0]['id1'];
// Set value to textboxes
document.getElementById('urn_no').value = id1;
}
}
});
}
PHP CODE(test.php)
<?php
if (! empty($_POST["dt"])) {
$sql="SELECT * FROM call_data WHERE U_no = '".$_POST["dt"]."'";
$result = mysqli_query($con,$sql);
if(!$result || mysqli_num_rows($result)<=0) {
}
$users_arr = array();
while( $row = mysqli_fetch_array($result) ) {
$r1=$row['URN_Number'];
$users_arr[] = array("id1" => $r1);
}
echo json_encode($users_arr);
exit;
}
?>
</div>
Here's a way to keep loading relevant data while the user is typing:
<?php
$mob_1 = filter_input(INPUT_GET, 'mob_1');
// if we're responding to an AJAX call, send back HTML fragment
if ($mob_1) {
$sql = "SELECT URN_Number FROM call_data WHERE U_no = $mob_1 LIMIT 1";
$result = mysqli_query($con, $sql);
if (!$result || mysqli_num_rows($result) <= 0) {
echo "Nothing found";
exit();
}
$URN = mysqli_fetch_array($result)['URN_Number'];
echo "<p>Here's some content related to URN $URN</p>";
exit();
}
// if not, send back main document
?><!doctype html>
<html>
<head>
<title>URN Lookup</title>
<meta charset="utf-8">
</head>
<body>
<input type="number" id="mob_1" />
<div id="result"></div>
<script>
$('#mob_1').on('keyup', function () {
// load HTML fragment
$('#result').load("index.php?mob_1=" + $(this).val());
});
</script>
</body>
</html>