Live Search results from database using AJAX, JSON - php

my script returns an array of JSON, and not individual results from the database. The script is designed to retrieve from the database records that match the text you typed. Below my codes, what could be wrong?
PHP:
//after connect to database (succesfull)
if($_GET['search_data'])
{
$search = ltrim($_GET['search']);
$limit = 15;
header("Content-type: application/json; charset={$charset}");
$res = $conn->query("SELECT aid, name FROM titles WHERE LIKE '%".$search."%'");
$data = array();
while($row = $res->fetch_accoss())
{
$row['name'] = htmlspecialchars_uni($row['name']);
$data[] = array('id' => $row['aid'], 'text' => $row['name']);
}
echo json_encode($data);
exit;
}
HTML
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#search").keyup(function(){
var text = $(this).val();
$.ajax({
type: "POST",
url: "search.php?get=search_data",
dataType: 'JSON',
data: "text=" + text,
async: false,
success: function(text) {
if(text)
{
$('#display').append(JSON.stringify(text))
}
else
{
$('#display').append('No results!');
}
}
});
});
});</script>
<title>Live search</title>
</head>
<body>
<br />
search: <input type="textbox" value="" name="search" placeholder="Write here..." id="search" />
<br />
<div id="display"></div>
</html>
and results:
[{"id":"10","text":"Dropdowns"},{"id":"9","text":"Accordions"},{"id":"5","text":"Convert Weights"},{"id":"3","text":"Animated Buttons"},{"id":"8","text":"Side Navigation"},{"id":"6","text":"Parallax"},{"id":"2","text":"HTML Includes"},{"id":"7","text":"Progress Bars
"},{"id":"4","text":"Top Navigation"},{"id":"1","text":"Range Sliders"},{"id":"11","text":"Google Maps"}]
My problem is that it shows when you type some letters the whole array of JSON, and not only the record, which we expect. What can I do?

You're trying go get the search parameter with $_GET['search'] you need to use $_POST['text']. Try this :
if($_GET['search_data'])
{
$search = ltrim($_POST['text']);
$limit = 15;
header("Content-type: application/json; charset={$charset}");
if(!empty($search)
$res = $conn->query("SELECT aid, name FROM titles WHERE LIKE '%".$search."%'");
$data = array();
while($row = $res->fetch_accoss())
{
$row['name'] = htmlspecialchars_uni($row['name']);
$data[] = array('id' => $row['aid'], 'text' => $row['name']);
}
echo json_encode($data);
exit;
}
And it's a good practice to use object in your ajax data
$(document).ready(function () {
$("#search").keyup(function () {
var text = $(this).val();
$.ajax({
type: "POST",
url: "search.php?get=search_data",
dataType: 'JSON',
data: {
text: text
},
async: false,
success: function (text) {
if (text)
{
$('#display').append(JSON.stringify(text))
} else
{
$('#display').append('No results!');
}
}
});
});
});

Related

Get ajax json data individually

I have a slight problem with my code, lets say i have a json like this one :
[{"img":"john.png","name":"John","username":"#john"},
{"img":"mark.png","name":"mark","username":"#mark"}]
I wanna get data organized like :
John #john john.png
Mark #mark mark.png
But every time the data comes out like this:
John Mark #john #mark john.png mark.png
This is my Php Code:
<?php
class search{
public function gettingvalues($search_value){
require_once('conx.php');
$dir = "usersimage/";
$sql = "SELECT name,img,username FROM users WHERE username like '$search_value%' || name like '$search_value%'";
$query = mysqli_query($conx,$sql);
if ($query) {
if (mysqli_num_rows($query) > 0) {
while ($row = mysqli_fetch_array($query)) {
$img = $row['img'];
$name = $row['name'];
$username = $row['username'];
$json = array('img' => $img, 'name' => $name, 'username' => $username);
$results[] = $json;
}
echo json_encode($results);
}
}
}
}
?>
This the index code:
<?php
if (isset($_POST['data'])) {
require('search.php');
$search = new search;
$search->gettingvalues($_POST['data']);
header('Content-Type: application/json; charset=utf-8');
die();
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input').keyup(function(){
var value= $('input').val();
$.ajax({
type: "POST",
url: "",
data: {data: value},
datatype: "json",
success: function(json_data) {
var img = [];
var username = [];
var name = [];
$.each(json_data, function(index, element) {
img.push(element.img);
username.push(element.username);
name.push(element.name);
})
$('#feedback').html('');
$('#feedback').html(name+username+img);
}
});
});
});
</script>
<input type="text" name="search" placeholder="looking for?">
<div id="feedback"></div>
Actually this is my first time with json, i don't know what is the problem or maybe i missed something, I hope getting some answers.
You need to build the HTML in the order that you want it displayed.
var html = '';
$.each(json_data, function(index, element) {
html += `${element.name} ${element.username} ${element.img}<br>`;
}
$("#feedback").html(html);

Can not retrieve data json from the server using ajax on cordova

I tried to call / search data by ID , from the server using ajax in cordova , but when I click to display the data " undefined" , what's wrong ???
This my html
<input type="text" id="result" value=""/>
<button>get</button>
<div id="result2"></div>
function get (){
var qrcode = document.getElementById ("result").value;
var dataString="qrcode="+qrcode;
$.ajax({
type: "GET",
url: "http://localhost/book/find.php",
crossDomain: true,
cache: false,
data: dataString,
success: function(result){
var result=$.parseJSON(result);
$.each(result, function(i, element){
var id_code=element.id_code;
var qrcode=element.qrcode;
var judul=element.judul;
var hasil2 =
"QR Code: " + qrcode + "<br>" +
"Judul: " + Judul;
document.getElementById("result2").innerHTML = hasil2;
});
}
});
}
This my script on server
include "db.php";
$qrcode= $_GET['qrcode'];
$array = array();
$result=mysql_query("select * from book WHERE qrcode LIKE '%{$qrcode}%'");
while ($row = mysql_fetch_array($result)) { //fetch the result from query into an array
{
$array[] =$row['qrcode'];
$array[] =$row['judul'];
$array[] =$row['jilid'];
}
echo json_encode($array);
}
try to change your parameter in calling ajax
var dataString = {qrcode : qrcode };
Change your php code as below
include "db.php";
$qrcode= $_GET['qrcode'];
$array = array();
$result=mysql_query("select * from book WHERE qrcode LIKE '%{$qrcode}%'");
while ($row = mysql_fetch_array($result)) { //fetch the result from query into an array
{
$array[] =['qrcode'=>$row['qrcode'],'judul'=>$row['judul'],'id_code'=>$row['jilid']];
}
echo json_encode($array);
}
RESOLVED the problem is. I try to replace with this script and the result was the same as I expected.
while ($row = mysql_fetch_object($result)){
$array[]=$row++;
}
echo json_encode($array);

I'm stucked in this ajax post

result:
This ajax can't give me a result. I'm struggling with this issue. I don't know why and I couldn't find where is the mistake. I was tried another ajax and it works, but i don't know with this one. How's this? somebody help me, thanks.
ztest1.php:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style></style>
<script>
function checkemail() {
var status = document.getElementById("emailudahada");
var u = document.getElementById("email").value;
if (u != "") {
document.getElementById("email").style.backgroundColor = "yellow";
status.innerHTML = "<img src='/img/loading.GIF'></img>";
$.ajax({
url: '/ztest2.php',
type: "POST",
data: ({
email: u,
cekemailsignup: 'yes'
}),
success: function(result) {
status.innerHTML = result['result'] + "," + result['cekemailsignup'] + "," + result['email'];
}
});
} else {
document.getElementById("email").style.backgroundColor = "white";
}
}
</script>
</head>
<body>
<div id='emailudahada'></div>
<input type='text' id='email' onblur='checkemail()'></input>
</body>
</html>
ztest2.php:
<?php
include('ckcon.php');
$cekemailsignup=isset($_REQUEST['cekemailsignup'])?$_REQUEST['cekemailsignup']:null;
if($cekemailsignup=='yes'){
$email=isset($_REQUEST['email'])?$_REQUEST['email']:null;
$q=mysql_query("SELECT COUNT(email) AS ce FROM t_un WHERE email='$email' LIMIT 1");
$f=mysql_fetch_object($q);
$ce=$f->ce;
if($email==null){
$result="<img src='/img/xred.png'></img> <font color='red'>Cant be null value</font>";
}
if(strlen($email) < 4){
$result="<img src='/img/xred.png'></img> <font color='red'>4 digit at minimum</font>";
}
if(is_numeric($email[0])){
$result="<img src='/img/xred.png'></img> <font color='red'>1st character must be letter</font>";
}
if($ce<>0){
//$result="<img src='/img/xred.png'></img> <font color='red'><strong>".$email."</strong> is taken</font>";
$result="kampret lu";
}
echo "
cekemailsignup=$cekemailsignup<br>
email=$email<br>
ce=$ce<br>
result=$result<br>
";
$ar = array(
'result' => $result,
'cekemailsignup' => $cekemailsignup,
'email' => $email
);
echo json_encode($ar);
}
?>
Here is changed js function
<script>
function checkemail() {
var status = document.getElementById("emailudahada");
var u = document.getElementById("email").value;
if (u != "") {
document.getElementById("email").style.backgroundColor = "yellow";
status.innerHTML = "<img src='/img/loading.GIF'></img>";
$.ajax({
url: '/ztest2.php',
type: "POST",
dataType: "json", //need to tell that response will as json
data: ({
email: u,
cekemailsignup: 'yes'
}),
success: function(result) {
status.innerHTML = result.result + "," + result.cekemailsignup. + "," + result.email;
}
});
} else {
document.getElementById("email").style.backgroundColor = "white";
}
}
</script>
result is string, to use it like object you need to parse it to JSON.
var obj = JSON.parse(result);
You can also set dataType: 'json', in the $.ajax configuration options to set it by default and then you don't need to parse the response, it can be directly used.
As jQuery is included on page, use it for DOM manipulation.
Complete Code:
$('#email').on('blur', function() {
var $status = $('#emailudahada');
email = $.trim($(this).val());
if (email) {
$(this).css('backgroundColor', 'yellow');
$status.html('<img src=\'/img/loading.GIF\'></img>');
$.ajax({
url: '/ztest2.php',
type: 'POST',
dataType: 'json',
data: ({
email: email,
cekemailsignup: 'yes'
}),
success: function(result) {
$status.html(result.result + ',' + result.cekemailsignup. + ',' + result.email);
}
});
} else {
$(this).css('backgroundColor', 'white');
}
});
HTML File
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style>
</style>
<script>
function checkemail(){
var status = document.getElementById("emailudahada");
var u = document.getElementById("email").value;
if(u != ""){
document.getElementById("email").style.backgroundColor = "yellow";
status.innerHTML = "<img src='/img/loading.GIF'></img>";
$.ajax({
url: '/ztest2.php',
type: "POST",
data: ({
email: u,
cekemailsignup: 'yes'
}),
success :
function(result2){
var result = JSON.parse(result2);
status.innerHTML=result['result']+","+result['cekemailsignup']+","+result['email'];
}
});
}else{
document.getElementById("email").style.backgroundColor = "white";
}
}
</script>
</head>
<body>
<div id='emailudahada'></div>
<input type='text' id='email' onblur='checkemail()'></input>
</body>
PHP file (ztest2.php)
<?php
$ar = array(
'result' => "123",
'cekemailsignup' => "true",
'email' => "ririnputrian#gmail.com"
);
echo json_encode($ar);
?>

PHP - variable from GET is changing

I have a svg.php file with some shapes.
<rect onclick="window.location='search.php?filter=1'" width="50" height="50">
<rect onclick="window.location='search.php?filter=2'" width="50" height="50">
Search.php
div class="container">
<textarea class="search" id="search_id"></textarea>
<div id="result"></div>
<?php include("svg.php"); ?>
</div>
//This is for a autocomplete search, took it from http://www.2my4edge.com/2013/08/autocomplete-search-using-php-mysql-and.html
<script type="text/javascript">
$(function(){
$(".search").keyup(function() {
var search_id = $(this).val();
var dataString = 'search='+ search_id;
if (search_id=='') {
$.ajax({
type: "POST",
url: "search_database.php",
data: dataString,
cache: false,
success: function(html) {
$("#result").html(html).hide(); }
});
};
if(search_id!='') {
$.ajax({
type: "POST",
url: "search_database.php",
data: dataString,
cache: false,
success: function(html) {
$("#result").html(html).show(); }
});
}return false;
});
jQuery("#result").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#search_id').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$('#search_id').click(function(){
jQuery("#result").fadeIn();
});
});
</script>
Then a search_database.php
$search = isset($_GET['filter']) ? $_GET["filter"] : 1;
echo $search; //echos "2".
if ($search=="1") {
echo $search; //enters if, and it's not supposed to, and echos "1"
Select * from table;
}
Search_database.php
$search = isset($_GET['filter']) ? $_GET["filter"] : "1";
echo $search //echos "2";
if ($search=="1") {
$q = $_POST['search'];
$q_length = strlen($q);
$sql = <<<SQL
SELECT * FROM table
LIMIT 6
SQL;
if(!$result = $con->query($sql)){
die('There was an error running the query [' . $con->error . ']');
}
while($row = $result->fetch_array()) { ?>
<div class="show_search">
<?php echo $row['name'] ?> </a>
</div>
<?php } } ?>
I'm on search.php?filter=2 and the first echo is correct ("2") but for some reason it keeps entering the If Clause and echos that $search is "1".
I'm not defining the $search variable anywhere else. Thank you for your help.
Your code is a bit too complicated.
$search = isset($_GET['filter']) ? $_GET["filter"] : 1;
if($search == 1) {
echo $search;
}
Thats enough, you don't need the check if $_POST is available. That make not so much sense because you don't send a form and you don't have post data in that case when you it with window.location.
If there is no other code between following two lines:
echo $search; //echos "2".
AND
if ($_POST AND $search=="1") { ... }
Then, its not possible to go inside if condition. its only possible if your if condition is like if($_POST AND $search=1). Check that, whether you have single = or double == in comparing $search variable.
If there is some php code in between, then show us, whatever it is, so that we can help you.

PHP and AJAX search results into a table

I am trying to make a webapp and I have used a php, ajax and mysql search function from another site.
It currently allows me to search the database and return what I want. The only problem I am having is that it returns the results in a simple text box. I want to be able to return the results in a table.
The search simply searches the database for forename, surname, address etc... This is the code I have.
php:
<?php
include('config.php');
if(isset($_GET['search_word']))
{
$search_word=$_GET['search_word'];
$sql=mysql_query("SELECT * FROM info WHERE CONCAT(Forename,' ',Surname) LIKE '%$search_word%'or Address1 LIKE '%$search_word%' or Address2 LIKE '%$search_word%' or Postcode LIKE '%$search_word%' or DOB LIKE '%$search_word%' ORDER BY ID DESC LIMIT 20 ");
$count=mysql_num_rows($sql);
if($count > 0)
{
while($row=mysql_fetch_array($sql))
{
$result = $row['Forename'].' '.$row['Surname'].' '.$row['DOB'].' '.$row['Address1'].' '.$row['Address2'].' '.$row['Postcode'];
$bold_word='<b>'.$search_word.'</b>';
$final_msg = str_ireplace($search_word, $bold_word, $result);
?>
<li><?php echo $final_msg; ?></li>
<?php
}
}
else
{
echo "<li>No Results</li>";
}
}
?>
This is connecting into the database and pulling out the results. I then have my html etc...:
script:
$(function() {
//-------------- Update Button-----------------
$(".search_button").click(function() {
var search_word = $("#search_box").val();
var dataString = 'search_word='+ search_word;
if(search_word=='')
{
}
else
{
$.ajax({
type: "GET",
url: "searchdata.php",
data: dataString,
cache: false,
beforeSend: function(html) {
document.getElementById("insert_search").innerHTML = '';
$("#flash").show();
$("#searchword").show();
$(".searchword").html(search_word);
$("#flash").html('<img src="ajax-loader.gif" align="absmiddle"> Loading Results...');
},
success: function(html){
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
// $("#MainTable").append(data);
if(html.length > 0)
{
$("#MainTable tr:not(:first-child)").remove();
}
for(var i = 0; i < html.length; i++)
{
var date = new Date(html[i]["Timestamp"]*1000);
html[i]["Timestamp"] = date.getHours()+":"+date.getMinutes();
$("#MainTable").append("<tr><td><a href='#' id='info"+data[i]["ID"]+"' data-role='button' data-theme='b' data-icon='check' data-iconpos='notext' class='id'></a></td><td>"+data[i]["Timestamp"]+"</td><td>"+data[i]["ID"]+"</td><td>"+data[i]["Forename"]+" "+data[i]["Surname"]+"</td><td class='hidden'>"+data[i]["ID"]+"</td><td>"+data[i]["DOB"]+"</td><td class='hidden'>"+data[i]["Address2"]+"</td><td class='hidden'>"+data[i]["Town"]+"</td><td class='hidden'>"+data[i]["City"]+"</td><td class='hidden'>"+data[i]["County"]+"</td><td>"+data[i]["Address1"]+"</td><td>"+data[i]["Postcode"]+"</td><td class='hidden'>"+data[i]["Phone2"]+"</td><td class='hidden'>"+data[i]["DOB"]+"</td></tr>");
if(data[i]["Completed"] == "1")
{
$("#MainTable tr:last-child td").addClass("lineThrough");
}
$("#MainTable tr:last td:first a, #MainTable tr:last td:last a").button();
}
}
});
}
return false;
});
//---------------- Delete Button----------------
});
I have tried a few different things such as changing the +Data+ in the table script to html or tried adding append(html) but I am having no luck and when I search I am instead getting undefined in my table or it is blank completely.
This is the HTML for my table:
<table data-role="table" id="MainTable" data-mode="columntoggle">
<tr><th> </th><th>ID Number</th><th>Name</th><th>DOB</th><th>Address</th><th>Postcode</th></tr>
<tr><td colspan='7'>No data currently available, connect to the internet to fetch the latest appointments.</td></tr>
</table>
Would appreciate any help with this. Hope this makes sense.
Instead of outputting this in your php page:
while($row=mysql_fetch_array($sql))
{
$result = $row['Forename'].' '.$row['Surname'].' '.$row['DOB'].' '.$row['Address1'].' '.$row['Address2'].' '.$row['Postcode'];
$bold_word='<b>'.$search_word.'</b>';
$final_msg = str_ireplace($search_word, $bold_word, $result);
?>
<li><?php echo $final_msg; ?></li>
Loop through the results outputting them in the table format you need, e.g:
echo "<tr>";
echo "<td>".$row['Forename']."</td>";
echo "<td>".$row['Surname']."</td>";
//etc
echo "</tr>"
Then take that response and fill the containing table with (jquery AJAX) something like:
.done(function( response ) {
$('#MainTable').html(response);
}
Changes:
if($count > 0)
{
while($row=mysql_fetch_array($sql))
{
$result = $row['Forename'].' '.$row['Surname'].' '.$row['DOB'].' '.$row['Address1'].' '.$row['Address2'].' '.$row['Postcode'];
$bold_word='<b>'.$search_word.'</b>';
$final_msg = str_ireplace($search_word, $bold_word, $result);
?>
<tr>
<td> </td>
<td><?=$row['id']?></td>
<td><?=$final_msg?></td>
<td><?=$row['address']?></td>
<td><?=$row['postcode']?></td>
</tr>
<?php
}
}
else
{
echo "<li>No Results</li>";
}
Changes in the JS
$.ajax({
type: "GET",
url: "searchdata.php",
data: dataString,
cache: false,
beforeSend: function(html) {
document.getElementById("insert_search").innerHTML = '';
$("#flash").show();
$("#searchword").show();
$(".searchword").html(search_word);
$("#flash").html('<img src="ajax-loader.gif" align="absmiddle"> Loading Results...');
},
success: function(html){
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
$("#MainTable").append(html); //<-- append the data from the ajax
}
});

Categories