Reputation: 59
I have this code that searches on a DB if a name exists:
<?php
$name = $_POST['name'];
$get_search_results_q= "SELECT * FROM `users`.`info` WHERE `info`.`fullname` LIKE '%$name%' ";
$get_search_results_run=mysql_query($get_search_results_q);
if($get_search_results_run==0){
echo "No results were found";
}else{
while($rows = mysql_fetch_assoc($get_search_results_run,MYSQL_NUM)){
$com_array[] = $rows[3];
}
echo json_encode($com_array);
}
?>
It works fine when i type a name that exists in DB.
But when i type something that doesn't exist nothing is returned.
This is the jQuery AJAX code that displays the data:
.done(function(data) {
var result = eval(data);
if(!result){
$(".results").empty();
$(".results").append('<div class="horizontal result_element">'+result+'</div>');
$("#search_result_box").show();
}else{
$(".results").empty();
for (var i = 0; i < result.length; i++) {
$(".results").append('<div class="horizontal result_element"><div class="result_photo"></div><div class="result_data">'+result[i]+'</div></div>');
}
$("#search_result_box").show();
}
});
I tried many things,like to display the data on jQuery and the mysql_query result but nothing happens.
Upvotes: 0
Views: 104
Reputation: 535
Try this
$total_rows = mysql_num_rows($get_search_results_run);
if(!$total_rows){
echo "No results were found";
}else{
while($rows = mysql_fetch_assoc($get_search_results_run,MYSQL_NUM)){
$com_array[] = $rows[3];
}
echo json_encode($com_array);
}
EDIT
I think because you send error type not in object json format, try this :
$name = $_POST['name'];
$get_search_results_q= "SELECT * FROM `users`.`info` WHERE `info`.`fullname` LIKE '%$name%' ";
// I missing this before
$get_search_results_run = mysql_query($get_search_results_q);
$total_rows = mysql_num_rows($get_search_results_run);
if(!$total_rows){
$error['message_message'] = "No results were found";
echo json_encode($error);
}else{
while($rows = mysql_fetch_assoc($get_search_results_run,MYSQL_NUM)){
$com_array[] = $rows[3];
}
echo json_encode($com_array);
}
.done(function(data) {
var result = eval(data);
if(result.error){
$(".results").empty();
$(".results").append('<div class="horizontal result_element">'+result.error+'</div>');
$("#search_result_box").show();
}else{
$(".results").empty();
for (var i = 0; i < result.length; i++) {
$(".results").append('<div class="horizontal result_element"><div class="result_photo"></div><div class="result_data">'+result[i]+'</div></div>');
}
$("#search_result_box").show();
}
});
Upvotes: 1