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);
Related
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!');
}
}
});
});
});
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 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.
I made an ajax form with json response. The json array contains information out of a mysql database. Now I want to show these datas in a table.
I made a placeholder in the html file which is hidden.
Here my Code for the ajax/json part:
$("#select_coffee_talk_year").button().click(function() {
var form = $('#coffee_talk_year');
var data = form.serialize();
$.ajax({
url: "include/scripts/select_event.php",
type: "POST",
data: data,
dataType: 'json',
success: function (select) {
//alert(select.ID[0]);
//alert(select.ID[1]);
//alert(select.ID.length);
$("#coffee_talk").fadeOut();
$("#coffee_talk").fadeIn();
}
});
return false;
});
This is my html:
<p class="bold underline headline">Bereits eingetragen:</p>
<form id="coffee_talk_year" action="include/scripts/select_event.php" method="post" accept-charset="utf-8">
<select name="year_coffee_talk" id="year_coffee_talk">
<option value="none" class="bold italic">Jahr</option>
<?php
for($i=2008; $i<=$year; $i++){
if ($i == $year) {
echo "<option value=\"".$i."\" selected=\"$i\">".$i."</option>\n";
} else echo "<option value=\"".$i."\">".$i."</option>\n";
}
?>
</select>
<button id="select_coffee_talk_year">anzeigen</button>
<input type="hidden" name="coffee_talk_year_submit" value="true" />
</form>
<br />
<div id="coffee_talk"></div>
<br />
<button id="add_coffee_talk">hinzufügen</button>
select_event.php:
if ('POST' == $_SERVER['REQUEST_METHOD']) {
/*******************************/
/** Erzaehlcafe auswählen
/*******************************/
if (isset($_POST['coffee_talk_year_submit'])) {
$getID = array();
$getDate = array();
$getTheme = array();
$getContributer = array();
$getBegin = array();
$getPlace = array();
$getEntrance = array();
$getFlyer = array();
$sql = "SELECT
ID,
Date,
Theme,
Contributer,
Begin,
Place,
Entrance,
Flyer
FROM
Coffee_talk
WHERE
YEAR(Date) = '".mysqli_real_escape_string($db, $_POST['year_coffee_talk'])."'
";
if (!$result = $db->query($sql)) {
return $db->error;
}
while ($row = $result->fetch_assoc()) {
$getID[$i] = $row['ID'];
$getDate[$i] = $row['Date'];
$getTheme[$i] = $row['Theme'];
$getContributer[$i] = $row['Contributer'];
$getBegin[$i] = $row['Begin'];
$getPlace[$i] = $row['Place'];
$getEntrance[$i] = $row['Entrance'];
$getFlyer[$i] = $row['Flyer'];
$i++;
}
$result->close();
$response['ID'] = $getID;
$response['Date'] = $getDate;
$response['Theme'] = $getTheme;
$response['Contributer'] = $getContributer;
$response['Begin'] = $getBegin;
$response['Place'] = $getPlace;
$response['Entrance'] = $getEntrance;
$response['Flyer'] = $getFlyer;
echo json_encode($response);
}
}
Div with id=coffee_talk is my placeholder. Now I wish to fade in the table with its data and if I change the year and submit it with the button I wish to fade the old one out and fade new in.
My only problem is that I need to write this table in php with loops. But I think its not possible in Java Script. What should I do?
PS I used ajax cause I dont want to have a reload all the time.
Your quick solution would be:
$("#select_coffee_talk_year").button().click(function() {
var form = $('#coffee_talk_year');
var data = form.serialize();
$.ajax({
url: "include/scripts/select_event.php",
type: "POST",
data: data,
dataType: 'json',
success: function (select) {
var coffee_talk = $("#coffee_talk");
coffee_talk.fadeOut('fast', function() {
for(i in select) {
row = select[i];
div = coffee_talk.append('<div id="row_'+i+'" />');
for(column in row) {
div.append('<span class="column_'+column+'">'+row[column]+'</span>');
}
}
coffee_talk.fadeIn();
});
}
});
return false;
});
For a nicer approach you should lookup Moustache.js which is a client side JavaScript templating engine (which has equivalents in PHP/Java/Ruby/Python/Go and other languages and is based on Google CTemplates).
It will allow you to create HTML templates and populate them with the data you have in a variable such as the JSON variable an AJAX request might receive.
Hey guys, I'm using jQuery's autosuggest plugin by using php to get the data. But it doesn't seem to work since I always get: No Results Found, even though I'm sure there are results:
Here's the php code:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
$input = mysql_escape_string($_GET["q"]);
$data = array();
$mysql=mysql_connect('localhost','***','***');
mysql_select_db('jmtdy');
$query = mysql_query("SELECT * FROM users WHERE username LIKE '%".$input."%'");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['value'] = $row['id'];
$json['name'] = $row['username'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>
And the script:
<script >
$(document).ready(function () {
$("#suggestedfriend").autoSuggest("suggestedf.php");
});
</script>
<script >
$(document).ready(function () {
$("#suggestedfriend").autoSuggest(
"suggestedf.php",
{
selectedValuesProp: "value",
selectedItemProp: "name",
searchObjProps: "name"
});
});
</script>
Add the above parameters, it will start to work :)
Just look at data, that server sends you back. If you use firefox you can watch it in network tab of firebug, or if you use chrome see it in resources.
The header must be in top of the file, right after the
<?php
header('Content-type: application/json');
include_once 'resources/dbconn.php';
$term = $_REQUEST['term'];
$query = "SELECT * FROM cds WHERE titel LIKE '%$term%'";
$result = $mysqli->query($query);
$arr = array();
while ($obj = $result->fetch_array()) {
$arr[] = $obj;
}
//for jsonp echo '('.json_encode($arr).')';
echo json_encode($arr);
?>
The JS/jQuery string
<script type="text/javascript">
$(function() {
var cache = {},
lastXhr;
$("#exercise").autocomplete({
minLength: 2,
source: function(request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
lastXhr = $.getJSON("json_Search.php", request, function(data,status,xhr) {
cache[term] = data;
if (xhr === lastXhr) {
response(data);
}
});
}
});
});
</script>