Page is a not externally linkable
- Code, Content, and Presentation
-- JavaScript and AJAX
---- PHP Search Using AJAX


LinusIT - 6:10 pm on Sep 23, 2012 (gmt 0)


I've been working on this and it's come along quite well until I had another idea. Basically 3 result sets: 1 result - multiple results - no results. It was previously working fine with just 1 result and no results.

AJAX:

$.ajax({
type: 'POST',
url: 'includes/process.php',
data: dataString,
dataType: "json",
cache: false,
success: function(response) {
//alert (JSON.stringify(response)); //Show JSON Alert
if (response.success) {
$("#search-form").html("<p><span class=\"label\">Date:</span> " + response.date + "</p>" +
"<p><span class=\"label\">Reference:</span> " + response.ref + "</p>" +
"<p><span class=\"label\">Amount:</span> &pound;" + response.amount + "</p>" +
"<p><span class=\"label\">Detail:</span> " + response.detail + "</p>");
} else if (resonse.multiple) {
$("#search-form").html("<div class=\"info\">Multiple Results Found<br />Please Use Advanced Search</div>" );
} else if (response.error) {
$("#search-form").html("<div class=\"warning\">No Results Found</div>" );
}
}
});


PHP Search:

$num_rows = mysql_num_rows($result);
if ($num_rows == 1) {
while ($row=mysql_fetch_array($result)) {
$date = date("d F Y",strtotime($row['tl_date']));
$ref = $row['tl_ref'];
$in = $row['tl_in'];
$out = $row['tl_out'];
$detail = $row['tl_detail'];
}
if ($in > 0) {
$amount = $in;
} else {
$amount = $out;
}
$arr = array("success" => "true", "date" => $date, "ref" => $ref, "amount" => number_format($amount,2), "detail" => $detail);
echo json_encode($arr);
} else if ($num_rows > 1) {
$arr = array("multiple" => "true");
echo json_encode($arr);
} else {
$arr = array("error" => "true");
echo json_encode($arr);
}


Using alert (JSON.stringify(response)); I can see that it's working fine on the PHP side, the alerts show the correct result. There must be something wrong in my success function.

What's happening is when you search "xxxxxx" it should show "No results" warning but doesn't show anything, when searching for "Start" it should show "Multiple Results" warning but again I get an empty dialog box. When I search for something I know there is only one of I get the correct information in the dialog box.

Another thing I'd like to ask.. You'll notice I've got "success = true", "multiple = true" & "error = true" in my PHP code. I would like to change this to

$arr = array("result" => "success");
$arr = array("result" => "multiple");
$arr = array("result" => "error");


What would I need to change in my success function to act on the data inside the result key?


Thread source:: http://www.webmasterworld.com/javascript/4488694.htm
Brought to you by WebmasterWorld: http://www.webmasterworld.com