Reputation: 209
I have these code:
show.php:
<div id="show" style="background-color: white; color: #2b2b2b "></div>
<script>
$(document).ready(function(){
$('#btnsearch').click(function(){
var key = {
'command': 'search',
'data': $("#inputsearch").val()
};
$.ajax({
type: 'POST',
url: 'query.php',
data: key,
dataType: 'json',
success: function(msg){
$('#show').html(msg);
}
})
});
});
</script>
and query.php:
$command = $_SESSION['command'];
if($command == 'search'){
$db = Db::getInstance();
$str = $_POST['data'];
$records = $db->query("SELECT * FROM m_cinfo LEFT OUTER JOIN m_jinfo ON m_cinfo.cinfo_id=m_jinfo.cinfo_id where fullName LIKE '%$str%'");
//echo json_encode($records, JSON_UNESCAPED_UNICODE);
echo 'تست';
}
Parrams and Responce are correct and input text + search send to query.php and تست returns but nothing shows in my div. It doesn't even alert anything in the success area.
Like i want to use the data from my db. what should i do? i get json like this:
[{"cinfo_id":"1","fullName":"علی علوی","phone":"09151234576","mail":"[email protected]","description":"در نمایشگاه آشنا شدیم","jinfo_id":"1","jobTitle":"شرکت","jobName":"بازرگانی","city":"مشهد"}]
and echo that but when i say
$('#show').html(msg.fullName);
for example, nothing would show.
Thanks in advance.
Upvotes: 0
Views: 1336
Reputation: 273
That's because ajax expects json response and the query.php script does not return json. If you add error callback to your ajax you will see that it's triggered.
$.ajax({
type: 'POST',
url: 'query.php',
data: key,
dataType: 'json',
success: function(msg){
$('#show').html(msg);
},
error: function (err) {
console.log(err);
}
To fix this in your query.php you should echo json_encoded string like this
echo json_encode(array('message' => 'تست'));
And then in your success callback you can access the message like this
success: function(response){
$('#show').html(response.message);
}
Update: okay if your $db->query method returns json as string then you can do the following
$records = $db->query("SELECT * FROM m_cinfo LEFT OUTER JOIN m_jinfo ON m_cinfo.cinfo_id=m_jinfo.cinfo_id where fullName LIKE '%$str%'");
$decoded = json_decode($records, true);
echo json_encode($decoded);
Note that your query is vulnerable to SQL injection . You should escape the $str variable or use prepared statements. For example if somebody enters this string in the search field it could drop your 'm_cinfo' table
somestring'; DROP TABLE m_cinfo; #
^ this will comment the rest of your query
Upvotes: 3