php - Auto fill input boxes with data from JSON in CodeIgniter
Sorry I am racking my brain and I have not worked with this in a long time. I have a form that you put a phone number in and on change submits an AJAX call to the database which post's the data and query's the database. Then sends a response back to the page which I am seeing the response values via Firebug in Firefox, but for the life of me I can not figure out how to get the data to update the text box fields with the information. Any help would be great. Also this is using CodeIgniter's framework and the data is beingjson_ecoded
.
Here are my input fields, the user fills thecustomer_phone
and on change it submits the AJAX call and sends back a response which looks like this:
<input type="text" name="customer_phone" id="customer_phone" value="" />
<input type="text" name="customer_name" id="customer_name" value="" />
<input type="text" name="customer_address" id="customer_address" value="" />
Here is the ajax call.
$('#customer_phone').change(function() {
var form_data = {
customer_phone : $('.customer_phone').val(),
ajax : '1'
};
$.ajax({
url: "<?php echo site_url('home/customer_search'); ?>",
type: 'POST',
async : false,
data: form_data,
dataType: 'json',
success: function(datas) {
$('.customer_name').val(datas['customer_name']);
}
});
return false;
});
I just can not figure out once the page receives the response from the back-end how do I update the text box fields with the values from the database.
This is the response I am receiving via Firebug
[{
"customer_phone_number": "4124020388",
"id": "2",
"customer_name": "Fudgie Wudgie",
"customer_address_1": "3811"
}]
Answer
Solution:
It looks like the JSON being returned is multidimensional, as in all of your values (customer_name, etc) are under a key, in this case 0.
So you can access it with:
Here's a jsfiddle where the first popup is the way in your code, and the second popup is using the [0]: http://jsfiddle.net/wqfp1k1b/
Also as stated before, use # instead of . in the selector for the ID of the field.
EDIT
See that you have solved the issue on your own. Sorry didn't see that you had replied with an answer about seeing the issue.
Answer
Solution:
Change this line:
to this one:
Answer
Solution:
First of all there should be a
#
as you are using ids here,and in your php page, convert the array into json with
json_encode
function.then ajax call should return json data without square brackets and your current code will work.
Answer
Solution:
Why are you using return false. Remove that:
Instead use: