I am familiarizing myself with ajax and json.
My page is addAccount.php and inside, I have a FORM with the INPUTs below:
<input type="text" id="partnerCode" />
<input type="button" id="pCodeSearch" value="Search" />
I have a JavaScript page called global.js the gets the information:
$('input#pCodeSearch').on('click' , function()
{
var partnercode = $('input#partnerCode').val();
if($.trim(partnercode) != '')
{
$.post('api/pCodeSearch.php', {partnercode: partnercode}, function(data)
{
$('div#partner-data').text(data);
});
}
});
In the above code, you will see the processing page called pCodeSearch.php. Here is that code:
<?php
if(isset($_POST['partnercode']) === true && empty($_POST['partnercode']) === false)
{
require "../include/database.php";
require "../include/sessions.php";
$search = "SELECT FULL_NAME, PARTNER_CODE from partner WHERE PARTNER_CODE = '"htmlentities(stripslashes(trim($_POST['partnercode'])))."'";
$query = mysqli_query($dbc, $search); // $dbc is the connection string
if(mysqli_num_rows($query) !== 0)
{
$out = array();
while($row = $query->fetch_assoc())
{
$out[] = $row;
}
echo json_encode($out);
mysqli_free_result($query);
}
else
{
echo 'Partner not found';
}
}
?>
With all of the above code, I can display in a DIV tag called #partner-data, as you saw in my JavaScript code above.
But this is the output:
[{"FULL_NAME":"PARTNER SA","PARTNER_CODE":"0000011182"}]
I would like to echo out just PARTNER SA and 0000011182.
I attempted this on my JavaScript page:
$.each(data, function(index, item)
{
$('<div>').
attr('value', item.PARTNER_CODE).
text(item.FULL_NAME).
appendTo($('#partner-data'));
});
But nothing returns to the screen.