ajax/php autocomplete issue - php

i'm new to pdo and json. I want to make an autocomplete searching by username and also displaying pic next to name. The issue i have is that my script is not displaying pic next to name but it makes it part of autocomplete, i mean it displays if it matches the letters from the search box. Sorry if my english is bad.Here is my sql script:
include("configPDO.php");
// Query to get the usable suggestions
$likeString = '%' . $_GET['term'] . '%';
// We Will prepare SQL Query
$STM = $dbh->prepare("SELECT username,avatar,id FROM `users` WHERE username LIKE :likeString");
// bind parameters, Named parameters always start with colon(:)
$STM->bindParam(':likeString', $likeString);
// For Executing prepared statement we will use below function
$STM->execute();
// we will fetch records like this and use foreach loop to show multiple Results
$STMrecords = $STM->fetchAll();
$Category_array = array();
foreach($STMrecords as $row)
{
$result = $row[0].$row[1];
array_push($Category_array, $result);
}
$json = json_encode($Category_array);
echo $json;
this is my ajax code using jquery.ui.autocomplete.js
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
url: 'Get_Auto1.php',
dataType: 'json',
success: function(data){
$('#searchg').autocomplete(
{
source: data,
minLength: 1
});
}
});
});
</script>
Thnx in advance.
I managed to make it displaying the avatar next to each result but id doesnt show the image itself just the url ex:"http://twingoo.ro/images/twingoo_logo.png", i also tryed with img src. I modified this line of code: $result = $row[0].$row[1];
here is the link of the demo: demo link

Related

Ajax request dataType json

I'm having troubles displaying a value in an input field. I did this in the past, and I haven't got a clue where my code goes wrong.
I have an input field with id="input" and a button with id="button". This is my jquery code:
$("#button").click(function() {
var uid = <?php echo $user['uid']; ?>;
$.ajax({
url: "php/fetchUserData.php",
method: "POST",
data: {
uid: uid
},
dataType: "json",
success: function(text) {
$("#input).val(text.bedrijfsnaam);
}
});
});
And here is the code on of the php/fetchUserData.php file:
<?php
include_once 'dbc.php';
if($_POST){
$uid = $_POST['uid'];
$sql = "SELECT * FROM users WHERE uid = '$uid'";
$query = mysqli_query($dbc, $sql);
$result = mysqli_fetch_assoc($query);
echo json_encode($result);
}
?>
UPDATE:
var_dump($result) does displays the associative array.
console.log(text) gives no result.
if I change dataType to text and echo out $result['bedrijfsnaam'] instead of json_encode($result) all goed well. The problem is that I want to load more than just the bedrijfsnaam (= company name).
UPDATE 2:
If I use the very same code but with another table in the database it does works. I really don't have a clue what can be the problem here...
I've been searching what could be the matter with the users table, and I notice cardinality is 0, although there are 4 rows in the table. In the other tables of the database, the cardinality value represents the number of rows. Could that have anything to do with this problem?
UPDATE 3:
Instead of the query:
$sql = "SELECT * FROM users WHERE uid = '$uid'";
I tried:
$sql = "SELECT bedrijfsnaam FROM users WHERE uid = '$uid'";
And it worked! Then I started adding column names, and all went well until a certain column: land (meaning country) a varchar column just like many others in the table.
What could be the reason this particular column causes the error to happen?
I know this became a phpmyadmin question instead of a php or jquery question. Should the question be moved to the sql part of the forum?
Assuming this is your actual code, your issue is likely stemming from not actually referencing and updating a field.
Something like this should be what you need:
$("#input").val(text.bedrijfsnaam)
I don't know anything about PHP and I don't think it matters. I think you got most part right. In success of your ajax request, set the text value of the input field.
$.ajax({
url:"php/fetchUserData.php",
method: "POST",
data:{uid:uid},
dataType:"json",
success:function(text){
$("id='button'").text(text.bedrijfsnaam);
}
});
$.ajax({
url:"php/fetchUserData.php",
method: "POST",
data:{uid:uid},
dataType:"json",
success:function(text){
$('#input').val(text[0]);
}
});
hmtl maybe better works than .val
You're wrong with your jquery selection of your div: you're missing an " in your code.
hope it will work

Jquery - parsererror - Unexpected end of JSON input

I'm trying to retrieve info from my database and display the information in a table generated by JQuery. I had done this before, and with using the exact same code it doesn't work anymore. I've looked up several other questions about this, but none of them has given me an answer.
This is the situation: An user select a value from the select menu, by selecting a value, that value gets sent and used to retrieve the right key for the right data. Then, by pressing a button the data should appear in a table. In order to accomplish this, I am using 3 ajax calls, one for populating the select box, one to send the right value, and another one to retrieve the needed data. The first two work perfectly, but not the last one.
My browser receives the data (see below) but the table does not appear and I'm getting a 'Unexpected end of JSON input' error. Can anyone help me out with this?
HTML/Jquery of the Ajax with the error:
function BekijkGegevens() {
$.ajax({
type: 'GET'
, data: {}
, dataType: 'json'
, url: "https://projectmi3.000webhostapp.com/webservices/bekijk.php"
, success: function (rows) {
$('#output').append("<table><tr><th> datum</th><th>stand</th></tr>")
for (var i in rows) {
var row = rows[i];
var datum = row[1];
var stand = row[0];
$('#output').append("<tr><td>" + datum + "</td><td>" + stand + "</td></tr>");
}
$('#output').append("</table>");
}
, error: function (JQXHR, TextStatus, ErrorThrow) {
console.log(JQXHR);
console.log(TextStatus);
console.log(ErrorThrow);
}
})
}
PHP:
<?php
include_once('confi.php');
error_reporting(E_ALL);
if (isset($_POST['teller']))
{
$teller = mysqli_real_escape_string($conn,$_POST['teller']);
$sql2="SELECT sta_stand,sta_datum FROM stand WHERE teller_id = '$teller'";
$result = $conn -> query($sql2);
//$query2 = mysql_query($sql2) or trigger_error(mysql_error()." ".$sql2);
$data2=array();
while ($row = mysqli_fetch_row($result))
{
$data2[]=$row;
}
echo "{data:" .json_encode($data2). "}" ;
}
?>
Thanks for any help that you can provide.
EDIT: Forgot to put my browser network, here it is.
http://puu.sh/uzI4f/a9ed1e0be5.png
EDIT2: I've split the PHP script into two seperate files, and tries to use a session variable to pass the needed key as suggested in the comments. Yet I am still getting the same error. Hereby the two new PHP files:
This one is used to send the key from Jquery to PHP:
<?php
include_once('confi.php');
error_reporting(E_ALL);
session_start();
if (isset($_POST['teller']))
{
$teller = mysqli_real_escape_string($conn,$_POST['teller']);
$_SESSION['teller'] = $teller;
}
?>
This one is used to get the needed information:
<?php
include_once('confi.php');
error_reporting(E_ALL);
session_start();
if (isset($_SESSION['teller']))
{
$sql2='SELECT sta_stand,sta_datum FROM stand WHERE teller_id ="' .$_SESSION['teller'].'"' ;
$result = $conn -> query($sql2);
//$query2 = mysql_query($sql2) or trigger_error(mysql_error()." ".$sql2);
$data2=array();
while ($row = $result-> fetch_row())
{
$data2[]=$row;
}
echo json_encode($data2);
}
?>
First, some warnings (in accordance with this link):
Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe! Don't believe it?
You should test against the session variable in your second script, which should look like this:
<?php
include_once('confi.php');
error_reporting(E_ALL);
session_start();
if (isset($_SESSION['teller']))
{
$teller = $_SESSION['teller'];
$sql2="SELECT sta_stand,sta_datum FROM stand WHERE teller_id = '$teller'";
$result = $conn -> query($sql2);
$data2=array();
while ($row = mysqli_fetch_row($result))
{
$data2[]=$row;
}
echo json_encode(['data'=> $data2]);
}
?>
Please note that I am also appending the 'data' properly to the JSON instead of just trying to "glue" (as said by Denis Matafonov) the JSON string together.
Dont try to glue data to string, like this:
echo "{data:" .json_encode($data2). "}" ;
Use simple
echo json_encode(['data'=> $data2]);
It should produce the same result if everything goes right, but wouldnt break up json if your $data2 is null
Declare your $data2 in the begginng, before if statement:
$data2 = [];
if (isset($_POST['teller'])) {
//do stuff and redefine $data2 or fill it;
}
//always echo valid json, event if no $POST["teller"] has arrived
echo json_encode(['data' => $data2]);

jQuery display object value

I am trying to access some info in my database and displaying the result of my query in some textboxes.. my code works but it says object object..
here's my jQuery code:
jQuery('body').on('click', '.update_button', function() {
var manufacturer_part = jQuery(this).val();
jQuery.ajax({
url: '/codes/clearhouse_processor.php',
type: 'POST',
data: {update_key: manufacturer_part},
dataType: 'json',
success: function(result) {
jQuery('#update-manufacturer-part').val(result.part_number);
jQuery('#update-manufacturer').val(result.manufacturer);
jQuery('.update-form').stop();
jQuery('.update-form').slideToggle('slow');
jQuery('html,body').animate({
scrollTop: jQuery('.update-form').offset().top-60
}, 750);
}
});
});
and here's my php code...
if(isset($_POST['update_key'])){
$manufacturer_part = $_POST['update_key'];
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query = $db->getQuery(true);
// Select all records from the user profile table where key begins with "custom.".
// Order it by the ordering field.
$query->select($db->quoteName(array('part_number')));
$query->from($db->quoteName('clearing_house'));
$query->where($db->quoteName('part_number') . '='.preg_replace("/[^0-9,.]/", "", #$manufacturer_part) );
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();
echo json_encode($results);
}
and btw, I am using joomla here...
thanks in advance,
jQuery('#update-manufacturer-part').val(result[0].part_number);
it is receiving an array from the server
by the result you gave
and if you want to see all the results that you receive
jQuery('#update-manufacturer-part').val(result[0].part_number);
_.map(result,function(){return part_number; }).join(",")
on the query itself update the fields that you need to get
$query->select($db->quoteName(array('part_number', 'manufacturer', 'field3', 'fieild4')));

How to get jquery autocomplete to display only terms that begin with the typed query

Context
I am adding autocomplete function to the search engine at motherpipe.co.uk.
I want it to only suggest terms that begin with the letters typed in by the user. For example, if the user types "lon" the function should return ten suggestions that begin with "lon".
I have about 50,000 terms in a local database
I have managed to get the autocomplete up and running, working with a separate php script that calls the database (sql).
Problem
My problem is that to begin with the top ten listings in the database (based on id) are shown regardless of what the user is typing in. It is only after the user types a further letter that suggestions appear correctly.
Question
How can I modify either jquery or the php code to make sure that ONLY terms that begin with what is typed in are returned (and then only the top ten terms in that subset based on the id.)?
HTML
<script type="text/javascript" src="/scripts/autocomplete/autocomplete/jquery.js"></script>
<script type="text/javascript" src="/scripts/autocomplete/autocomplete/jquery.autocomplete.js"></script>
<script>
$(document).ready(function(){
$("#tag").autocomplete("/scripts/autocomplete/autocomplete/autocomplete.php", {
selectFirst: false,
minChars: 2
});
});
</script>
PHP
<?php
$q=$_GET['q'];
$mydata=mysql_real_escape_string($q);
$mysqli=mysqli_connect('localhost','username','password','languages') or die("Database Error");
$sql="SELECT searchterms FROM topterms WHERE searchterms LIKE '$mydata%' ORDER by id";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error());
if($result)
{
while($row=mysqli_fetch_array($result))
{
echo $row['searchterms']."\n";
}
}
?>
With the new version of jQuery autocomplete when you use a URL as a source (like you do):
You must return JSON data:
String: When a string is used, the Autocomplete plugin expects that
string to point to a URL resource that will return JSON data. It can
be on the same host or on a different one (must provide JSONP).
The GET argument you receive is 'term', not 'q'
The Autocomplete plugin does not filter the results, instead a query
string is added with a term field, which the server-side script should
use for filtering the results.
The proper way to use real escape with mySQL in PHP is to use it after the connection has been established, in your case:
$q = $_GET['term'];
$mysqli = mysqli_connect('localhost','username','password','languages');
if (!$mysqli or $mysqli->connect_error) die("Database Error");
$mydata = $mysqli->real_escape_string($q);
$sql = "SELECT searchterms FROM topterms WHERE searchterms LIKE '$mydata%' ORDER by id";
$result = mysqli_query($mysqli,$sql);
$json = array();
if ($result and $result->num_rows > 0) {
while($row=mysqli_fetch_array($result)) {
$json[] = $row['searchterms'];
}
}
header('Content-Type: application/json'); // You can skip that because IE doesn't really like it
echo json_encode($json);

Speed up live search js, php, mysql

I have made a "live search bar" with php and javascript. if you enter a word in the search bar it searches the database (mysql).
index.php:
<input type="text" onkeyup="getMovie(this.value)"/>
<div id="movie"></div>
javascript.js:
function getMovie(value) {
$.post("getmovie.php",{partialMovie:value},function(data) {
$("#movie").html(data);
});
}
getmovie.php:
include_once "connection.php";
if($_POST['partialMovie']){
$partialMovie = $_POST['partialMovie'];
$sql = "SELECT title FROM movie WHERE title LIKE '%$partialMovie%'";
$stm = $db->prepare($sql);
$result = $stm->execute(array());
while($row = $stm->fetch(PDO::FETCH_ASSOC)) {
echo "<li>".$row['title']."</li>";
}
}
This works, but it is way to slow. I have only 3 "movies" in my database, but it takes like a second or two to show the results.
the titles of the 3 movies are: een twee drie.
but if i type "een" fast, after a second you see een, twee, drie. a second later you see: een twee. and another second later you see: een.
So my question is: is there a way to speed the search up or is there a way to stop searching if you type another letter?
Either lower your expectation, because 1 second for a request's round trip is not very improvable, or get the data as json at page load time and search against locally available json data. But if there are many records this might not be an option.
As you use PDO, bind your parameters to avoid sql injection.
Then use full text search in MySQL (select match against), it will be a lot faster than the like %% approach.
Doc : http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
HTML:
<input type="text" id="movie-autocomplete"/>
<div id="movie"></div>
JS:
$(document).ready(function(){
$('#movie-autocomplete').keyup(function(){
setTimeout(function(){
$.post(
"getmovie.php",
{
partialMovie: $(this).val()
},
function(data) {
$("#movie").html(data);
}
);
}, 500);
});
});
This will create a small delay and post an atual value within the field.
PHP:
include_once "connection.php";
if(!empty($_POST['partialMovie'])){
$partialMovie = $_POST['partialMovie'];
$sql = "SELECT title FROM movie WHERE title LIKE :movie ORDER BY title LIMIT 0, 10";
$stm = $db->prepare($sql);
$result = $stm->execute(array(':movie' => "%{$partialMovie}%"));
while($row = $stm->fetch(PDO::FETCH_ASSOC)) {
echo "<li>".$row['title']."</li>";
}
}
We have to bind the parameter to secure the SQL query and prevent SQL injection. Also You should ensure You have set the PDO to use real prepared statements.
To further speed all the process You should return only JSON data from the PHP and fill in the <ul> within Your JS code...

Categories