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);
obj.lengthwill beundefinedand you’re calling the response objectobjnotdata. What you’ll get back from PHP is this;To cater for this, update your JS to:
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_stringat least: