Okay, so I'm a bit of a newb to JSON. I'm trying to cobble together an AJAX call(a PHP mssql query) that returns the values back to the original form through JSON. I'm getting [object Object] instead of the actual value of the variable. Through some searching I think the issue is related to parsing, but I thought json_encode handled this. Or maybe it does and I haven't structured this correctly.
Here's what Im trying to accomplish: An html form has 3 fields: Account Number, Account Name and Address1. I want the user to be able to enter the Account Number and then have the Name and Address fields populate on blur with the results of the mssql query.
Here's what I have: HTML
<body>
<label>Account Number:</label><input type="text" id="acctnumber" />
<label>Account Name:</label><input type="text" id="acctname" />
<label>Address 1:</label><input type="text" id="address1" />
</body>
Jquery (I put the acctnumber input value in just for testing)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#acctnumber").blur(function(){
$.ajax({
url: "ajaxtestscript.php?acctnumber=hfi01",
dataType: "json", //the return type data is jsonn
success: function(data){ // <--- (data) is in json format
$("#acctname").val(data.Name);
$("#address1").val(data.Address);
//parse the json data
}
});
});
});
</script>
PHP
<?php
header('Content-Type: application/json');
//mssql connection info//
$acctnumber = $_GET["acctnumber"]; // we received this from the json call
//declare the SQL statement that will query the database
$query = "select[description],[daddr1] from trCustomer where company = '$acctnumber' and archived = 0";
//execute the SQL statement and return records
$rs = $conn->execute($query);
$test = array();
$test['Name'] = $rs[description];
$test['Address'] = $rs[daddr1];
echo json_encode($test);
//echo $name.$address; put this in to test the query was working, which it was
//close the connection and recordset objects freeing up resources
$rs->Close();
$conn->Close();
$rs = null;
$conn = null;
?>
When I actually try this on the html form, I enter in the Account number value (hardcoded at this point) and click out of the element to fire blur, and in the other two input fields I get [object Object]. Although if I just echo my query back I can see the values so I'm thinking I have done something wrong or left something out with my json_encode. Any assistance would be greatly appreciated.
datafor more clarity.jsonas the dataType, the string returned from your php script will be parsed as json so thatdatais a javascript object. If the string is valid json of course... To see what is inside, you can doconsole.log(data);in the success function.