problem with jquery autocomplete and mySql - php

search.php
$text = $mysqli->$_POST['term'];
$query = "SELECT name FROM males WHERE name LIKE '%" . $text . "%' ORDER BY name ASC";
$result = $mysqli->query($query);
$json = '[';
$first = true;
while($row = $result->fetch_assoc())
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$row['name'].'"}';
}
$json .= ']';
echo $json;
index.php
1) HTML
<body>
Text: <input type="text" id="autocomplete" />
</body>
2) jQuery
$( "#autocomplete" ).autocomplete({
source: function(request, response) {
$.ajax({ url: "http://localhost/testing/auto/search.php",
data: { term: $("#autocomplete").val()},
dataType: "json",
type: "POST",
success: function(data){
response(data);
}
});
},
minLength: 2
});
When I type 2 letters, it gives me all the names in my database even if these two letters do not match any of the names.
How does that happen and how do I fix it?

Looks like my comment worked as an answer, hence this answer.
What does $mysqli->$_POST['term'] do? I think you should have $text = $_POST['term'];. This should work.

Change the PHP to
$text = $_POST['term'];
$query = "SELECT name FROM males WHERE name LIKE '%" . $mysqli->real_escape_string($text) . "%' ORDER BY name ASC";
$result = $mysqli->query($query);
echo json_encode($result->fetch_all(MYSQLI_ASSOC));
You forgot to escape the input to prevent SQL injections. Additionally, use #mu's answer to fix your front-end code.

Your source callback isn't doing what you think it is. The current contents of the autocompleter are in request.term, not in $("#autocomplete").val(). You're sending an empty value for term back to your PHP and then your SQL looks like:
SELECT name FROM males WHERE name LIKE '%%' ORDER BY name ASC
which of courses matches everything in your males table. Your source callback should look like this:
source: function(request, response) {
$.ajax({
url: "http://localhost/testing/auto/search.php",
data: { term: request.term },
dataType: "json",
type: "POST",
success: function(data) {
response(data);
}
});
}
The jQuery-UI widget probably manipulates the DOM a fair bit so the #autocomplete input element may not have anything useful in it until the autocompleter has a final value for it.
For reference, here's what the fine manual has to say:
The third variation, the callback, provides the most flexibility, and can be used to connect any data source to Autocomplete. The callback gets two arguments:
A request object, with a single property called term, which refers to the value currently in the text input. For example, when the user entered "new yo" in a city field, the Autocomplete term will equal "new yo".

First make sure that your search.php is working. Switch to $_GET['term'] and run the page directly until you get the data you wanted.
I would personally change the query from from LIKE '%text%' to LIKE 'text%'.
After that use Firebug to examine the parameters that are transferred to the search.php with an AJAX call. BTW, are you sure that your jquery code is correct?

I think is your sql query. U were using
$query = "SELECT name FROM males WHERE name LIKE '%$text%' ORDER BY name ASC"
if your name list like
Aaron
Alexander
Maartha
...
If you type 'AA', the above query will result : Aaron, Maartha. Because the query will search matching given string between the whole strings.
% text % means the query result will ignore the left and right result.
if you're looking for names field data you supposed to use query
$query = "SELECT name FROM males WHERE name LIKE '$text%' ORDER BY name ASC"
If you type 'AA, it will result : Aaron.
Note that jQuery only returns what you're asking to the database.

Use $_REQUEST['term'] instead $_POST['term'].

Related

jQueryUI autocomplete JSON not returning expected data

Using jQueryUI autocomplete to search a MySQL database. When user presses enter in the search field, I want to populate a div with the result(s) returned from DB.
The code works and does return an autocomplete list of suggestions.
However, the JSON data returned in the select: function is not what I expected.
In the PHP code sample below, the query requests all fields from the database related to each title matched by the query. There should have been other fields, like author, bid, isbn, genre, etc. -- however, only the title field was returned.
Google Chrome's console looks like this:
Object {item: Object}
item: Object
label: "Much Obliged Jeeves"
value: "Much Obliged Jeeves"
__proto__: Object
Object {label: "Much Obliged Jeeves", value: "Much Obliged Jeeves"}
Where are the other fields?
My jQuery:
$('#srxbks').autocomplete({
source: "autocomplete_test.php",
minLength: 1,
select: function( event, ui ) {
console.log(ui);
console.log(ui.item);
console.log(ui.item.label);
//Not working:
var out = 'Title: ' + ui.item.title + '<br>';
out += 'Author: ' + ui.item.author + '<br>';
$('.booksTableDIV').val(out);
}
});
My PHP:
<?php
include 'connect.php';
$term = strip_tags($_GET['term']);//retrieve search term sent by autocomplete
$qstring = "SELECT * FROM `books` WHERE `title` LIKE '%" .$term. "%'";
$query = mysql_query($qstring) or die(mysql_error());
while ($row = mysql_fetch_array($query)) {
$row['title']=htmlentities(stripslashes($row['title']));
$row['bid']=(int)$row['bid'];
$row_set[] = $row['title'];
}
echo json_encode($row_set);
You just need to be sure all your variables are included in the returning array. Your PHP is the part having an issue, your are not transferring the variables to JSON correctly. Your jQuery is fine. The following is what you need to do for each extra variable you wish to send back to your jQuery.
// Initialize your variables here
$returns = array();
$i = 0;
while ($row = mysql_fetch_array($query)) {
// Format your variables here
$row['title']=htmlentities(stripslashes($row['title']));
$row['bid']=(int)$row['bid'];
// Enter results into JSON array here
$returns[$i]['title'] = $row['title'];
$returns[$i]['bid'] = $row['bid'];
$i++;
}
echo json_encode($returns);

How to update mysql database fields in groups (using GROUP BY)

I have a table named youi in my database. All fields in the table already contain values except for the aff and desc fields. See image below.
Now, I have a form in my HTML page (See image below) where I want to update the desc and aff fields according to their camp. I have not yet dealt with this kind of setup before. I've been thinking how to do this for almost a day now but still can't seem to find a perfect solution. Could you give me ideas or solutions on how to achieve this? I'm using PHP and mySQL.
Thanks in advance!
The easiest way i see is using a different UPDATE for each of those lines.
You could do that in a loop in php where you construct your update with the values of aff, desc and campaign for each line.
The sql would be:
UPDATE tableName
SET aff = varAffiliate,
desc = varDescription
WHERE campaign = varCampaign;
The php part i'm not of much help, sorry.
You can use CASE, WHEN and THEN in a loop to make the one query.
This is a statement I created using a simple for loop to update a bunch of captions on a group of photos.
UPDATE Images SET caption = CASE imgID WHEN 389 THEN 'a' WHEN 390 THEN 'sdf' WHEN 391 THEN 'safasasadf' WHEN 392 THEN 'fs' WHEN 393 THEN 'dfdsf' WHEN 394 THEN 'sfdf' END WHERE imgID IN (389,390,391,392,393,394);
Hope that helps
aff = (case when somefield='slkd' then yyy end),
desc = (case when somefield='slkdfdsd' then xxx end)
I finally found a solution to this problem. I used combination of jQuery, AJAX, PHP and mySQL for it to work.
All <select> have the same id. The same for <input> and <label>. Here's a sample of my HTML code:
<select id="youiaff">
<option>1001</option>
<option>1007</option>
<option>1009</option>
<option>1013</option>
<option>1017</option>
<option>1018</option>
<option>1022</option>
</select>
<input id="youidesc" type="text" />
<label id="youicamp"></label>
<button type='button' class='btn btn-success saveyouiid'>Save</button>
What I did next was to create a jQuery code that will get all the values of <select>, <input> & <label> and put each of them in an array. I used their ids as identifiers. Here's the code:
var desc = $("input[id='youidesc']")
.map(function(){return $(this).val();}).get();
var aff = $("select[id='youiaff']")
.map(function(){return $(this).val();}).get();
var camp = $("label[id='youicamp']")
.map(function(){return $(this).text();}).get();
Then, I passed the variables to the PHP script using AJAX:
$.ajax({
type: 'post',
url: 'saveyouiid.php',
data: {
desc:desc,
aff:aff,
camp:camp,
},
success:function(data){
}
});
This codes will be executed upon clicking the save button. So the full jQuery/AJAX for this would be:
$('.saveyouiid').click(function(){
var desc = $("input[id='youidesc']")
.map(function(){return $(this).val();}).get();
var aff = $("select[id='youiaff']")
.map(function(){return $(this).val();}).get();
var camp = $("label[id='youicamp']")
.map(function(){return $(this).text();}).get();
$.ajax({
type: 'post',
url: 'saveyouiid.php',
data: {
desc:desc,
aff:aff,
camp:camp,
},
success:function(data){
}
});
});
The PHP script (saveyouiid.php) will then accept the values sent via AJAX. These values are arrays. What I did next was I combined the arrays to form a multidimensional array. Then, I get the individual values and perform the mySQL query. Here's what the script looks like:
<?php
$con = mysqli_connect("localhost","imu_fryu","frankyouiIMU2013","imu_frankyoui");
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$aff = $_POST['aff'];
$desc = $_POST['desc'];
$camp = $_POST['camp'];
$arr = array_map(null, $aff, $desc, $camp);
foreach($arr as $array)
{
$aff = $array[0];
if ($aff == ">> Select Affiliate ID <<"){
$affID = "0";
}else{
$affID = $aff;
}
$desc = $array[1];
$camp = $array[2];
$sql1 = "UPDATE youi SET aff = '$affID', descr = '$desc' WHERE camp = '$camp'";
if (!mysqli_query($con,$sql1)) {
die('Error: ' . mysqli_error($con));
}
}
mysqli_close($con);
?>
I hope this could help someone in the future. :)

Make A Next Button For More More Data?

Hi dear friends,
I hope u are all fine.
I want to make a next button for getting more data from mysql database.
For example:
$sql = mysql_query("SELECT * FROM table LIMIT 0,7");
It get 7 rows.For next data code is that.
$sql = mysql_query("SELECT * FROM table LIMIT 7,7");
I can i do that using ajax.
As you can see in many website like facebook,When you click on comment it give a limited
comment and when you click on more comment it give more and so on.In this proccess you can see
that the other content of page does not change.It means it can use ajax and how can I do that in ajax.
Please help me.Thanks.
your ajax would be something like this
var numberOfdata = 0;
$('#button').click(function () {
$.ajax({
url: 'load.php',
data: {
'limit' : numberOfdata,
// other data ...
},
type : 'post',
// other parameters...
}).success(function (data) {
// adding data to your website
numberOfdata += 7;
});
});
and in your server side, you could do something like this
... other operations
mysql_query("SELECT * FROM table LIMIT " . $_POST['limit'] . ",7");
... continuting the work
Note: You should be able to handle SQL injections on your own.
Edit: please note that mysql_query is not recommended.
You have to send the current comments count via Ajax, get the new ones from the response and display them.
Javascript:
$(document).ready(function() {
$('a.pagination-more').click(function() {
var current_comments_count = $(this).data("current_comments_count");
$.ajax({
type: "POST",
url: "pagination/pagination_ajax_more.php",
data: { "limit_start":current_comments_count },
beforeSend: function() {
$('a.pagination-more').html('<img class="loading-gif" src="pagination/loading.gif" />');
},
success: function(html){
$("#more").remove(); // This is the "More" button. It is appended to the end again in the 'html' variable
$("ul#updates").append(html);
if($("a#end")[0]) {
$("div#more").remove();
}
}
});
return false;
});
});
On the PHP side you just get $limit_start, get results from the database and echo the html like:
$limit_start = $_POST['limit_start'];
$query = mysql_query("SELECT COUNT(*) FROM `table` LIMIT 0, $limit_start");
$current_comments_count = mysql_num_rows($query);
$query = mysql_query("SELECT * FROM `table` LIMIT $limit_start, 7");
while($row = mysql_fetch_assoc($query)) {
echo '<li>
blah blah...
</li>';
}
if(mysql_num_rows($query) == 7)
echo '<div id="more"><a data-current_comments_count="$current_comments_count" class="button pagination-more" href="#">More</a></div>';
else
echo '<div id="more"><a id="end" class="button pagination-more" href="#">The button will be removed from jQuery...</a></div>';
Of course it is strongly recommended to secure your application and not to use only mysql_query(). This code is working but I removed some other stuff and didn't test it now. So, some errors may occur.

Ajax Printing Database Records to Multiple Fields

I currently have code which will pull the first element from a database record and print it in an output box.
What is the easiest way to print the rest of the elements of that record to the other relevant output boxes?
My PHP file takes an 'id' specified by the user.
$id = $_POST['id'];
$query = "SELECT * FROM Customers WHERE ID = $id";
$result= mysql_query($query);
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_row($result)) {
echo $row[1];
}
}
And this is the code in the HTML file
jQuery(document).ready(function(){
jQuery("input.myid").keyup(function(e){
e.preventDefault();
ajax_search();
});
});
function ajax_search(){
var search_val=jQuery("input.myid").val();
jQuery.post("find.php", {id : search_val}, function(data){
if (data.length>0){
jQuery("input.fname").val(data);
}
});
}
The code takes the id ('myid') and prints to a text box named 'fname'.
I find it easier to json_encode the whole thing (record I mean) and use something like jquery.populate which basically takes an object and fills a form with it (all fields it can find which names' match properties from the object).
I hope this makes sense.

Load json data to autocomplete jquery

I am trying to use the jqueryui autocomplete to load services from mysql database on my form but nothing happens?? please help me or tell me where am wrong
my html
<input type="text" id="actual_service" />
my javascript script
$("#actual_service").autocomplete({
source: "http://dev_svr/medportal/search.php?callback=?",
dataType: "jsonp",
minLength: 1
});
this is search.php
$con = mysql_connect('localhost', 'dev', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("medrep", $con);
$term = trim(strip_tags($_GET['term']));
$qstring = "select prod_id id,prod_name value FROM product where prod_type='SERVICE' and prod_name LIKE '%".$term."%' ORDER BY prod_name;";
$result = mysql_query($qstring);
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
$row['value']=htmlentities(stripslashes($row['value']));
$row['id']=(int)$row['id'];
$row_set[] = $row;
}
header("Content-type: application/json");
echo json_encode($row_set);
when i load that page nothing happens on that inputbox when i type anything.
this is a sample output of http://dev_svr/medportal/search.php?term=ct when i limit the sql to 3 rows
[{"id":50,"value":"ABDOMEN SUPINE&ERECT(2VIEWS)"},{"id":142,"value":"CT BRAIN"},{"id":115,"value":"CT CERVICAL SPINE"}]
1. Your jQuery code is not correct
You are not getting data from a remote domain, therefore you don't need a JSONP request.
It should be:
$("#actual_service").autocomplete({
source: "http://dev_svr/medportal/search.php",
minLength: 1
});
2. Your JSON object is not correct.
Each json object for the autocomplete should have two values: label and value (no ID). If you want the product id to be the value of the selected item, and the product name to be the text that is shown to the user, then the json object should be like:
[{"value":50,"label":"ABDOMEN SUPINE&ERECT(2VIEWS)"},{"value":142,"label":"CT BRAIN"},{"value":115,"label":"CT CERVICAL SPINE"}]
Edit
From what you mentioned in the comments, try this jQuery code:
$('#actual_service').autocomplete({
source: function( request, response ) {
$.ajax({
url: 'http://dev_svr/medportal/search.php',
dataType: 'jsonp',
data: { term: request.term },
success: function( data ) {
response( data );
}
});
},
minLength: 1
});

Categories