I have two jQuery AJAX request being made when the use searches for customer information.
I can get the customer name via .autocomplete and I can get JSON data from addressSearch.php, but when I cannot get the values i need from the second JSON set.
The user should simply select the address from the drop down and i should fill in the form.
When I console.log(address) I do not get the correct multidimensional array.
How do I select the correct sub-array to send data to the form fields?
HTML
<label>Customer Search:</label><input id="cSearch" type="text" /><br />
<label>Name:</label><input id="name" /><br />
<select id="addresses">
<option>Please Select Address</option>
</select>
<label>Street:</label><input id="street" type="text" /><br />
<label>City:</label><input id="city" type="text" /><br />
<label>State:</label><input id="state" type="text" /><br />
<label>Zip:</label><input id="zip" type="text" /><br />
JavaScript
$(document).ready(function() {
$("input#customerSearch").autocomplete({
source:'inc/customerSearch.php',
select: function(event, ui) {
$('#name').val(ui.item.name);
getAddresses(ui.item.addressid);
},
minLength:2
});
});
var address = [];
function getAddresses(id){
$.getJSON(
'inc/addressSearch.php',
{ id: id },
function(data) {
$('#addresses').children().remove().end().append('<option>Please Select Address</option>');
$.each(data, function(x, val) {
$('#addresses').append('<option value="' + val['addressid'] + '">'+ val['street1'] +'</option>');
address[x] = [];
$.each(val, function(key, value) {
address[x][key] = value;
});
});
}
);
$('select#addresses').change(function() {
var j = $(this).val();
//fill in fields when select
});
}
addressSearch.php
$id = explode(',', $id);//explode address ids
$data = array();//data array
foreach($id as $id) {//evaluate each address
$query = "SELECT * FROM `address` WHERE address_id = '". $id ."'";//query
$result = mysql_query($query);//run query
if (mysql_num_rows($result)) {//results exist
while($row = mysql_fetch_assoc($result)) {//loop
$data[$id] = array(//build array
'addressid' => $row['address_id'],
'street1' => $row['address_street1'],
'street2' => $row['address_street2'],
'city' => $row['address_city'],
'region' => $row['address_region'],
'country' => $row['address_country'],
'code' => $row['address_code']
);
}
}
}
print json_encode($data);// jQuery wants JSON data
JSON
{
"101":{
"addressid":"101",
"street1":"123 ABC St",
"street2":"",
"city":"Somewhere",
"region":"AB",
"country":"USA",
"code":"12345"
},
"102":{
"addressid":"102",
"street1":"123 10th St",
"street2":"Apt 101",
"city":"Nowhere",
"region":"AB",
"country":"USA",
"code":"12345"
}
}
I just had to walk away and look at it again. There was nothing wrong with the code above, it was the second parts that wasn’t working.
Here is the final function
JavaScript