My new code with the updated changes. Clicking the button after inserting a number has no effect on the form.
Front-End
$(document).ready(function(){
$("#go").click(function() {
var id=$("#myid").val();
$.getJSON('find.php',{num:id},function(obj){
alert(obj.toSource());
$("input.fname").val(obj.FirstName);
$("input.sname").val(obj.Surname);
$("input.age").val(obj.Age);
});
});
});
Form
ID: <input type="text" name="id" class="myid">
<input type="button" value="Go" id="go" />
First Name: <input type="text" name="FirstName" class="fname"><br>
Surname: <input type="text" name="Surname" class="sname"><br>
Age: <input type="text" name="Age" class="age"><br>
Back-End
$id = $_GET['num'];
$result = array('FirstName' => 1, 'Surname' => 2, 'Age' => 3);
echo json_encode($result);
I think it's here
$id = $_GET['num'];
instead of
$id = $_GET['id'];
because your querystring should be something like
find.php?num=3
end then looking better at your code the error should be
jQuery("input.fname").val(obj.FirstName);
jQuery("input.sname").val(obj.Surname);
jQuery("input.age").val(obj.Age);
without obj.length
as stated correctly in anothe ranswer
obj.length
will be undefined
and you're calling the response object obj
not data
. What you'll get back from PHP is this;
{
"FirstName": 1,
"Surname": 2,
"Age": 3
}
To cater for this, update your JS to:
// if (obj.length>0){ remove this
jQuery("input.fname").val(obj.FirstName);
jQuery("input.sname").val(obj.Surname);
jQuery("input.age").val(obj.Age);
// } and this...
Note the case-sensitivity of JavaScript.
Additionally, as pointed out by Nicola Peluchetti, you should be checking for $_GET['num']
rather than $_GET['id']
.
You should also have more protection against SQL injection attacks. Escape your input with mysql_real_escape_string
at least:
$query = "SELECT * FROM Customers WHERE ID = '" . mysql_real_escape_string($id) . '"';
Replace {num:id}
with {id:id}
Checkout below code with your code.
<script type="text/javascript">
$(document).ready(function(){
$("#go").click(function() {
var id=$("#myid").val();
$.getJSON('http://localhost/test/test/json_action.php',{num:id},function(obj){
//alert(obj.toSource());
$("input.fname").val(obj.FirstName);
$("input.sname").val(obj.Surname);
$("input.age").val(obj.Age);
});
});
});
</script>
<input type="hidden" name="myid" id="myid" value="2" />
<input type="button" value="Go" id="go" />
<input type="text" class="fname" />
<input type="text" class="sname" />
<input type="text" class="age" />
json_action.php
$result = array('FirstName' => 1, 'Surname' => 2, 'Age' => 3);
echo json_encode($result);
Above is almost same as your code and i can fill up value by clicking go button. And you are getting this error ' an undefined index error -> Notice: Undefined index: num in :***********\website\find.php on line 10 ' cause your are not passing id in your query. By the way i cant see any use of query so i have eliminated in my json_action.php file. Hope this will help you.