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>
Related
I'm trying to fetch data from DB for a line graph using the below code.
<?php
$dataPoints = array(
$sql1 = "SELECT * FROM chart_data_column WHERE value = 'now'";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
while($row1 = $result1->fetch_assoc()) {
array("y" => 25, "label" => "Sunday"), ?>
} } else { }
);
?>
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: ""
},
axisY: {
title: ""
},
data: [{
type: "line",
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
Using the above code it gives as error as Un-expected Syntax error, expecting ) instead of ; at $dataPoints line
However if i m to remove the sql query, graph plots with static data perfectly.
Any Help is greatly appreciated..
I have to commend you for keeping PHP code and JavaScript separate. This is a very good idea. However, if you want to fetch all records from MySQL using PHP and mysqli library you do not need to have any loop. You can just fetch everything into an array and then display with json_encode() in JavaScript.
<?php
// import your mysqli connection before
$result1 = $conn->query("SELECT * FROM chart_data_column WHERE value = 'now'");
$dataPoints = $result1->fetch_all(MYSQLI_ASSOC);
?>
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: ""
},
axisY: {
title: ""
},
data: [{
type: "line",
dataPoints: <?= json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
<?= is short for <?php echo
You put the entire query inside the array. You need to separate them. Also, you have "chart_data_column" where the table name should be.
$dataPoints = array();
$sql1 = "SELECT * FROM chart_data_column WHERE value = 'now'";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
while ($row = $result1->fetch_assoc()) {
$dataPoints[] = $row;
}
}
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);
I have a notification system that out puts the right value of 1 and updates the div accordingly when a user posts one on my wall.
{
"num":1,
"notification_id":"640",
"notification_content":"Lucy Botham posted a status on your wall",
"notification_throughurl":"singlepoststreamitem.php?streamitem_id=515",
"notification_triggeredby":"85",
"notification_status":"1"
}
But if a user posts twice it does nothing and doesn't update at all.
{
"num":1,
"notification_id":"641",
"notification_content":"Lucy Botham posted a status on your wall",
"notification_throughurl":"singlepoststreamitem.php?streamitem_id=516",
"notification_triggeredby":"85",
"notification_status":"1"
}
{
"num":1,
"notification_id":"642",
"notification_content":"Lucy Botham posted a status on your wall",
"notification_throughurl":"singlepoststreamitem.php?streamitem_id=517",
"notification_triggeredby":"85",
"notification_status":"1"
}
CLIENT SIDE
$user1_id=mysqli_real_escape_string($mysqli,$_SESSION['id']);
$call="select MAX(notification_id) AS notification_id ,notification_status,notification_targetuser,notification_triggeredby,notification_throughurl from notifications WHERE notification_targetuser='$user1_id' AND notification_status='1'";
$chant=mysqli_query($mysqli,$call) or die(mysqli_error($mysqli));
while($notification=mysqli_fetch_array($chant)){
?>
<script type="text/javascript">
var notification_id="<?php echo $notification['notification_id']?>";
var notification_targetuser="<?php echo $notification['notification_targetuser']?>";
var notification_triggeredby="<?php echo $notification['notification_triggeredby']?>";
function loadIt() {
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id+"¬ification_targetuser="+notification_targetuser+"¬ification_triggeredby="+notification_triggeredby,
dataType:"json",
success: function(data){
if(data.notification_stream=1){
$("#notif_ui"+notification_id).prepend('<div class="notif_text"><div id="notif_actual_text-" class="notif_actual_text"><img border="1" src="userimages/cropped'+data['notification_triggeredby']+'.jpg" onerror=this.src="userimages/no_profile_img.jpeg" width="40" height="40" ><br />'+data['notification_content']+' <br />'+data['notification_time']+'<br/></div></div></div><hr/>');
i = parseInt($("#mes").text()); $("#mes").text((i+data.num));
if(!data.notification_id.length) {
//no results...
return;
}
notification_id = data.notification_id;
}
}
});
}
setInterval(loadIt, 10000);
</script>
<? } ?>
SERVER SIDE
$json = array();
$com=mysqli_query($mysqli,"SELECT * from notifications WHERE notification_targetuser='$idw' AND notification_triggeredby='$ide' AND notification_status='1' ORDER BY notification_id")or die($mysqli);
while($row = mysqli_fetch_assoc($com)){
$num = mysqli_num_rows($com);
if($num){
$json['num'] = 1;
}else{
$json['num'] = 0;
}
$json['notification_id'] = $row['notification_id'];
$json['notification_content'] = $row['notification_content'];
$json['notification_throughurl'] = $row['notification_throughurl'];
$json['notification_triggeredby'] = $row['notification_triggeredby'];
$json['notification_status'] = $row['notification_status'];
echo json_encode($json);
}}
$sql = "UPDATE notifications SET notification_status = '2' WHERE notification_targetuser='$idw'";
$go = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
You're echoing the JSON results inside a loop, so if the loop executes more than once, the final result is not valid JSON data. It's just multiple chunks of JSON.
while($row = mysqli_fetch_assoc($com)){
$id = $row['notification_id'];
$num = mysqli_num_rows($com);
if($num){
$json['num'] = 1;
}else{
$json['num'] = 0;
}
$json[$id]['notification_id'] = $row['notification_id'];
$json[$id]['notification_content'] = $row['notification_content'];
$json[$id]['notification_throughurl'] = $row['notification_throughurl'];
$json[$id]['notification_triggeredby'] = $row['notification_triggeredby'];
$json[$id]['notification_status'] = $row['notification_status'];
}
echo json_encode($json);
Then you'll need to adjust your Javascript to expect an array instead of a flat object.
So I have a PHP script where I ask a simple query and then I put it in an array.
<?php
$query = mysql_query('SELECT ATX12V FROM results');
$resultSet = array();
while($row = mysql_fetch_array($query)){
$resultSet['ATX12V'] = $row['ATX12V'];
$data[] = $resultSet;
}
print json_encode($data);
?>
The outcome of print json_encode($data) is:
[{"ATX12V":"10"},{"ATX12V":"65"},{"ATX12V":"64"},{"ATX12V":"96"}]
Below I have a javascript code and my question is how do I add $data to the data[]??
<script>
var buyerData = {
labels : ["January","February","March","April","May","June", "July", "August"],
datasets : [
{
fillColor : "#9DB86D",
strokeColor : "#ACC26D",
pointColor : "#9DB86D",
pointStrokeColor : "#9DB86D",
data : []
}
]
}
</script>
What about simple:
data : <?php echo json_encode($data); ?>
you can use ajax like :
(home.html):
<script type="text/javascript">
window.onload = function() {
$.ajax({
type: "POST",
url: "request.php",
dataType: "json",
success: function (data) {
alert(data[0].ATX12V);
}
});
}
</script>
<script type="text/javascript" src="js/jquery.js"></script>
and server side (request.php) :
<?php
$query = mysql_query('SELECT ATX12V FROM results');
$resultSet = array();
while($row = mysql_fetch_array($query)){
$resultSet['ATX12V'] = $row['ATX12V'];
$data[] = $resultSet;
}
print json_encode($data);
?>
note: Add jquery.js in your project
<?php require_once('Connections/root.php'); ?>
<?php $q = mysql_query("SELECT * FROM performer"); ?>
<script> $(document).ready(function () {
$(function() {
var availableTags = ["<?php while($r = mysql_fetch_assoc($q)) { echo $r['username']; } ?>"];
$("#search_box").autocomplete({
source: availableTags
});
});
});
</script>
the script works but it displayes : User1User2User3
and i want it to display:
User1
User2
User3
How do i add a new line after every user and where do i add the line feed
if i make it like this
var availableTags = ["<?php while($r = mysql_fetch_assoc($q)) { echo $r['username'] . " <br />"; } ?>"];
i get User1User2User3 and the br as a string
Separate your PHP logic from your Javascript code. Up top, build a PHP array first:
$tags = array();
while($r = mysql_fetch_assoc($q)) {
$tags[] = $r['username'];
}
Then in your javascript, echo the array JSON encoded:
var availableTags = <?php echo json_encode($tags); ?>;
Note: You are using deprecated mysql_* functions and should switch to mysqli_* or PDO.
As mentioned, your availableTags array has only 1 string variable.
You need to push the string to the Array.
You can try this:
var availableTags = [];
<?php while($r = mysql_fetch_assoc($q)) { ?>
availableTags.push('<?php echo $r['username']; ?>');
<?php } ?>
The generated js array is not what you expect it to be. With your code, you obtain
var availableTags = ["User1User2User3"];
whereas what you need is
var availableTags = ["User1", "User2", "User3"];
Yous should adapt your PHP code to generate the right JS.