JQuery KeyUp Live Search. How to? - php

I am trying to find out why is it that I can get my live search to work but it returns all results from mysql table no matter what I type. Perhaps you could help?
I am trying to get the previous request and initiate a new one on each keyup.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Help Tool 2.0</title>
<link type="text/css" rel="stylesheet" href="assets/css/index.css" />
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function(){
$('#search-box').keyup(function() {
$("#results").html('');
var xhr;
var keywords = $(this).val();
if(xhr != null) xhr.abort();
xhr = $.get("search.php", {q: keywords}, function() {
//alert("success");
})
.success(function(data) {
xhr = null;
//alert("second success");
$("#results").html(data);
})
});
});
</script>
<input id="search-box" name="q" type="text" />
<div id="results"></div>
</body>
</html>
And the PHP:
<?php
include_once ('database_connection.php');
if(isset($_GET['q'])){
$keyword = trim($_GET['q']) ;
$keyword = mysqli_real_escape_string($dbc, $keyword);
$query = "select topictitle,topicdescription from topics where topictitle like '%$q%' or topicdescription like '%$q%'";
//echo $query;
$result = mysqli_query($dbc,$query);
if($result){
if(mysqli_affected_rows($dbc)!=0){
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo '<p> <b>'.$row['topictitle'].'</b> '.$row['topicdescription'].'</p>';
}
}else {
echo 'No Results for :"'.$_GET['q'].'"';
}
}
}else {
echo 'Parameter Missing';
}
?>

Try this js code in place of what you have. I added the delay function so that the script waits a specified amount of time after the user stops typing before sending the request. This prevents a large amount of requests getting sent to the server.
<script type="text/javascript">
var delay = (function() {
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$("#search-box").keyup(
function () {
delay(function () {
var keyword = $("#search-box").val();
var URL = encodeURI("search.php?q=" + keyword);
$.ajax({
url: URL,
cache: false,
type: "GET",
success: function(response) {
$("#results").html(response);
}
});
}, 500);
}
);
</script>

Related

How to filter a JSON page feeding data to Select2?

I'm trying to populate a Select2 box with data from a t-sql query. The query is run on a PHP page which translates the output to JSON and is called in the javascript of the main page.
The main page looks like this:
<?php
header('Content-type: text/html; charset=UTF-8');
require('db.php'); // Bring in the database connection
include("auth.php"); // Make sure the user is logged in to an account
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" http-equiv="Content Type" charset="utf-8"/>
<!-- JQuery -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- SELECT 2 -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
</head>
<body style="background-color: #F5F5F5;">
<select class="js-data-example-ajax">
</select>
<script>
$('.js-data-example-ajax').select2({
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json'
// Additional AJAX parameters go here
}
});
</script>
</body>
</html>
My JSON page looks like this:
<?php
require('db.php'); // Bring in the database connection
include("auth.php"); // Make sure the user is logged in to an account
$search = $_GET['search'];
//JSON Table Stuff
$sql = "SELECT DISTINCT [IN] AS id, Nom as text
FROM dbo.[TFM_NumérosIN2012]
;";
$stmt = sqlsrv_query($con,$sql);
$result = array();
do {
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($stmt));
sqlsrv_free_stmt($stmt);
$data2 = json_encode($result);
echo '{ "results":' . $data2 . '}';
?>
The data output by the JSON page looks like this:
{ "results":[{"id":2,"text":"SMITH Sean"},{"id":3,"text":"CHARLES charley"},{"id":4,"text":"TFC Madrid"},{"id":5,"text":"VAN DAMME jean claude"}]}
The data is loading into the select list without any problems. However, I've tried to filter the data multiple ways and nothing has worked. I've tried adding a data parameter and passing a search variable to the php/JSON page and referencing in the $sql variable as a where clause, but this doesn't return anything
To try and filter the data I changed the javascript to this:
$('.js-data-example-ajax').select2({
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json',
data: function (params) {
var query = {
search: params.term
}
// Query parameters will be ?search=[term]&type=public
return query;
}
}
});
But this breaks my select and and it displays a message 'The results could not be loaded.'
Does anyone know what I'm doing wrong here?
Cheers,
At the end of your php file just echo the following line :
echo json_encode($result);
In your html/js file :
<link href='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js'></script>
<select name='js-data-example-ajax' class='js-data-example-ajax'></select>
$(document).ready(function()
{
$('.js-data-example-ajax').select2({
placeholder: "Search for product",
minimumInputLength: 1,
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json',
data: function (params) {
var query = {
search: params.term,
type: 'public'
}
console.log("query : "+query.search);
return query;
},
processResults: function (response) {
console.log("response : "+response);
return {
results: $.map(response, function(obj) {
console.log("response obj.id: "+obj.id);
console.log("response obj.text: "+obj.text);
return { id: obj.id, text: obj.text };
})
};
},
cache: false
}
});
});

jquery $.getScript().. How to get data from external js file into array

I try to put data into js file, through "jquery $.post" and "fwrite php", and get back that data into array. How to do that?
here's the html:
<!doctype html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function() {
if ($("#nameput").val() != "") {
$.post("processing.php", {
putname: $("#nameput").val()
});
var arr = [$.getScript("talk.js")];
alert(arr[0]);
}
})
})
</script>
</head>
<body>
<input type="text" id="nameput" />
<button id="button">send AJAX req</button>
</body>
</html>
Here's the php, I name it "processing.php" :
<?php
$file = fopen("talk.js","a");
$text = $_POST["putname"];
fwrite($file,'"'.$text.'",');
fclose($file);
?>
And "talk.js" will look like this :
"a","b","c",
Why I can't put that data from "talk.js" into array at " var arr = [$.getScript("talk.js")]; " as in html file above?
Here's what I try after I read comments. I change the scirpt into this:
<script>
$(document).ready(function() {
$("#button").click(function() {
if ($("#nameput").val() != "") {
$.post("processing.php", {
putname: $("#nameput").val()
}, function() {
$.getScript("talk.js", function(data) {
var arr = data.split(",");
alert(arr[0]);
})
})
}
})
})
</script>
And php into this:
<?php
$file = fopen("talk.js","a");
$text = $_POST["putname"];
fwrite($file,$text);
fclose($file);
?>
But it still not work?
here's a simplified version of your button click to help you out:
$("#button").click(function() {
$.getScript("talk.js", function(data){
var arr = data.split(',');
alert(arr[0]);
});
});
If you log the output of $.getScript you will easily see why what you're trying doesn't work.
Using this method you will get the data returned from the script ("a","b","c"), but you'll need to split it on a comma into an array. Then you can reference whichever part of the array you want.
Note that the each element of the array will have quotations around them.

JSON data to $scope

I'm writing a little, simple script which load JSON file and print into HTML by AngularJS. This is my JS code:
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
var $_GET = getQueryParams(document.location.search);
var APP = angular.module('APP', []);
var restaruantId;
APP.ApplicationCtrl = function ($scope) {
if ($_GET['id'] !== undefined && $_GET['id'] !== null) {
restaruantId = $_GET['id'];
jQuery.get( "inc/getData.php", { id: restaruantId} )
.done(function( data ) {
// $scope.restaurant = data;
$scope.restaurant = angular.fromJson(data);
console.log($scope);
});
} else {
alert("ERROR");
}
$scope.name = 'World';
};
getData.php load JSON file from Graph API and it works. $scope.restaurant is an object and it contains all data. This is my HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AngularJS Test</title>
<script src="js/jquery-1.10.2.min.js"></script>
<script src="angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-app="APP" ng-controller="APP.ApplicationCtrl">
<h1>{{ restaurant.name }}</h1>
</div>
</body>
</html>
Unfortunatelly restaurant.name doesn't work and it's empty. Can you tell me why?

click counter in php using jquery

I am new to JQuery and trying to create a counter which counts the number of clicks and updates the counter in the database by one.
I have created a button, on click of that i am sending the counter's value to the database. and trying to get the updated count at my first page.
my code is -
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Implementing counter</title>
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<? session_start()?>
<? ob_start()?>
<?
if($_SERVER['HTTP_HOST']=='localhost'){
$host="localhost";
$user="root";
$pass="";
$dbas="db_name";
mysql_connect($host,$user,$pass,$dbas);
mysql_select_db($dbas);
}
?>
<script>
$(document).ready(function(){
$("#count").click(function(){
saveData();
$("#counter").load();
});
function saveData(){
$.ajax({
type: "POST",
url: "counter.php",
data: { count: "1"}
})
.done(function( count ) {
alert( "Counter Plus: " + count );
})
.fail(function() {
alert( "error" );
});
}
});
</script>
<br />
<button id="count">Add Counter</button><br>
<div id="counter">
<?
$fetch1=mysql_query("select `count` from user");
$fetch2=mysql_fetch_array($fetch1);
$counter=$fetch2['count'];
echo "You have ".$counter." Clicks";
?>
</div><br><br>
</body>
</html>
My counter.php looks like -
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Counter</title>
</head>
<body>
<? session_start()?>
<? ob_start()?>
<?
if($_SERVER['HTTP_HOST']=='localhost'){
$host="localhost";
$user="root";
$pass="";
$dbas="db_name";
mysql_connect($host,$user,$pass,$dbas);
mysql_select_db($dbas);
}
?>
<?
if (isset($_POST['count'])) { // Form has been submitted.
$count = $_POST['count'];
$n=0;
$fetch1=mysql_query("select `count` from user");
$fetch2=mysql_fetch_array($fetch1);
$n1=$fetch2['count'];
$n=$n1+$count;
// INSERT THE DATA
$query = "UPDATE user SET `count`='{$n}'";
// Confirm if the query is successful.
$result = mysql_query($query);
echo "Counter Updated by 1";
}
?>
</body>
</html>
when i click the button, the counter.php is called, counter is updated, but my < div > is not updated. the counter.php page is shown as a dialog over my screen.
My first page & when i click the button, it looks like this -
Tell me what is going wrong??
Remove HTML Tag's FROM counter.php
<? session_start()?>
<? ob_start()?>
<?
if($_SERVER['HTTP_HOST']=='localhost'){
$host="localhost";
$user="root";
$pass="";
$dbas="db_name";
mysql_connect($host,$user,$pass,$dbas);
mysql_select_db($dbas);
}
?>
<?
if (isset($_POST['count'])) { // Form has been submitted.
$count = $_POST['count'];
$n=0;
$fetch1=mysql_query("select `count` from user");
$fetch2=mysql_fetch_array($fetch1);
$n1=$fetch2['count'];
$n=$n1+$count;
// INSERT THE DATA
$query = "UPDATE user SET `count`='{$n}'";
// Confirm if the query is successful.
$result = mysql_query($query);
echo $n;
}
?>
AND replace ajax code with below
function saveData(){
$.ajax({
type: "POST",
url: "counter.php",
data: { count: "1"}
})
.done(function( count ) {
$("#counter").html( "Counter Plus: " + count );
})
.fail(function() {
// alert( "error" );
});
}
});
you are using alert !! use .html()
find and try this!!
//alert( "Counter Plus: " + count );
$("#counter").html( "Counter Plus: " + count );
You can change div content at success
function saveData(){
$.ajax({
type: "POST",
url: "counter.php",
data: { count: "1"},
success: function(data) {
$('#div').html(data);
},
error: function(error) {
alert(error);
}
});
}
You need to return total count from your counter.php not the whole html markup
Your counter.php should output
Total count = 25
then in your jquery .done callback put this instead of alert
$("#counter").html(count);
from your counter.php you are returning some string... do like this..
counter.php
$query = "UPDATE user SET `count`='{$n}'";
$result = mysql_query($query);
echo $n; //here $n has updated count value
in jquery
success : function (count)
{
$("#counter").html("you have "+count+" clicks");
}
hope will help you
What you're doing is you are using javascript function 'alert', hence the dialog box appears whenever you press the Add Counter button. Change your code to following:
function saveData(){
$.ajax({
type: "POST",
url: "counter.php",
data: "count=1",
success: function(data)
{
$('#counter').html(data);
},
error: function()
{
//alert("error");
}
});
});
Also, exclude all the HTML tags from the counter.php page and viola!

Comet - PHP error showing

I am new to comet and doing a simple application.
My html file looks like
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>testing comet</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery-1.9.0.js"></script>
</head>
<body>
<div id="content">
</div>
<p>
<form action="" method="get" onsubmit="comet.doRequest($('#word').val());$('#word').val('');return false;">
<input type="text" name="word" id="word" value="" />
<input type="submit" name="submit" value="Send" />
</form>
</p>
<script type="text/javascript">
// comet implementation
var Comet = function (data_url) {
this.timestamp = 0;
this.url = data_url;
this.noerror = true;
//alert(data_url);
this.connect = function() {
var self = this;
$.ajax({
type : 'get',
url : this.url,
dataType : 'json',
data : {'timestamp' : self.timestamp},
success : function(response) {
self.timestamp = response.timestamp;
self.handleResponse(response);
self.noerror = true;
},
complete : function(response) {
// send a new ajax request when this request is finished
if (!self.noerror) {
alert("error");
// if a connection problem occurs, try to reconnect each 5 seconds
setTimeout(function(){ comet.connect(); }, 5000);
}else {
// persistent connection
self.connect();
}
self.noerror = false;
}
});
}
this.disconnect = function() {}
this.handleResponse = function(response) {
$('#content').append('<div>' + response.msg + '</div>');
}
this.doRequest = function(request) {
$.ajax({
type : 'get',
url : this.url,
data : {'msg' : request}
});
}
}
var comet = new Comet('./backend.php');
comet.connect();
</script>
</body>
</html>
backend.php looks like
<?php
$dr=DIRECTORY_SEPARATOR;
$filename = dirname(__FILE__).$dr.'data.txt';
// store new message in the file
$msg = isset($_GET['msg']) ? $_GET['msg'] : '';
if ($msg != '')
{
file_put_contents($filename,$msg);
die();
}
// infinite loop until the data file is not modified
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif) // check if the data file has been modified
{
usleep(10000); // sleep 10ms to unload the CPU
clearstatcache();
$currentmodif = filemtime($filename);
}
// return a json array
$response = array();
$response['msg'] = file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo json_encode($response);
flush();
data.txt contains a blank file.
Now my question is
if (!self.noerror) {
alert("error");
This will execute and showing alert "error" always. But it is working perfectly if I comment that alert part. Is anything wrong ?
When I track the process with firebug, on those requests, getting an fatal error like this.
Any one please help me
Thanks in advance
The time-out issue will be caused by your while loop failing to exit before PHP exits because the value of the max_execution_time directive has been reached. You could extend this, but do you really want scripts to be running for that long? I'd be more inclined to do more work in the JavaScript - make it request an update every second or so (10ms is far, far too often).
Regarding the alert("error"), be careful where you're setting the value of noerror - do you really want to set it to false at the end of the complete() function? I think you want to change your call to $.ajax() to something more like this (abbreviated):
$.ajax({
error : function() {
// the request failed
setTimeout(function() { comet.connect(); }, 5000);
},
success : function(response) {
// the request succeeded
self.connect();
}
});
If you can, remove the noerror variable entirely and use the error() and success() callbacks to house your logic for each scenario, like above.
You must edit the backend.php lines;
<?php
$dr=DIRECTORY_SEPARATOR;
ini_set('max_execution_time', 300);
$filename = dirname(__FILE__).$dr.'data.txt';

Categories