jQueryUI autocomplete JSON not returning expected data - php

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);

Related

Error with my dojo ajax php request

Im trying to use a dojo ajax function to call a PHP file that then returns the contents of a DB table in JSON format.
My function:
var _getWeatherInfo = function(){
dojo.xhrget({
url: "PHP/weather.php?ntown=" + _ntown,
handleAs: "json",
timeout: 5000,
load: function(responce, details) {
_updateWeathertData
},
error: function(error_msg, details) {
_handleError(error_msg);
}
});
}
My PHP:
<?php include('configHome.php'); ?>
<?php
$ntown = $_GET['ntown'];
$weather = array();
$query="SELECT * FROM `weather` WHERE `town` = '$ntown'";
$result=mysql_query($query);
while($row = mysql_fetch_row($result)) {
$weather[] = $row[0];
}
echo json_encode($weather);
mysql_close();
?>
When using this code I am getting an error message saying that "$ntown = $_GET['ntown'];" is an undefined index. I have tried removing the index all together and using an actual value in the select statement (i.e. SELECT * FROM weather WHERE town = 'Auckland') but all I get back is the value i enter ["Auckland"], and not the 3 other values that are meant to be returned, ["Auckland", "Sunny", "8", "14"].
Any ideas? I can try add more info if needed. Thanks!
There are some other issues with your code, but to get to the one you are asking the question about. You have this:
while($row = mysql_fetch_row($result)) {
$weather[] = $row[0];
}
What you are doing is just taking the first value of the row (of which there is probably only one, and just sending that back. This is what you need:
$weather = mysql_fetch_row($result);

jquery autocomplete sql query list based on another input value

I have two autocomplete fields in my form. I populate the first field's list by using the following code...
$result = mysql_query("SELECT * FROM exercise_strength");
$arr_autoCompleteExerciseStr=array();
$s=0;
while($row = mysql_fetch_array($result)){
$autoCompleteExerciseStr = "\"".ucfirst($row['exercise'])."\", ";
$arr_autoCompleteExerciseStr[$s] = $autoCompleteExerciseStr;
$s++;
}
and...
$(function() {
var availableTags = [
<?php for($k=0; $k<sizeof($arr_autoCompleteExerciseStr); $k++) {echo $arr_autoCompleteExerciseStr[$k]; } ?>
];
$( "#inputExercise" ).autocomplete({
source: availableTags,
minLength: 0
});
$( "#inputExercise" ).focus(function(){
$(this).autocomplete("search");
});
});
The same code with a different mysql_query is used for the other field. What I want to do is change the list of the second field based on what's typed in the first. For instance, if the user types Chest in the first field, a list of relevant Exercises is shown in the second field, selected from my sql database.
What is the best way to do this?
I would prefer if I wouldn't have to leave the page, cause then the user have to refill the rest of the form..
Please help! :)
-- UPDATE --
Based on your advice about JSON my code now looks like this.
Script:
$(document).ready(function(){
$.post('json_exercise.php', { /**/ }, showExercise, "text");
});
function showExercise(res){
var list = JSON.parse(res);
$("#inputExercise").autocomplete({
source: list,
minLength: 0
});
$( "#inputExercise" ).focus(function(){
$(this).autocomplete("search");
});
}
PHP file:
$con = mysql_connect(***);
if (!$con) {die('Could not connect: ' . mysql_error());}
mysql_select_db("test", $con);
$result = mysql_query("SELECT * FROM exercise_strength");
$i = 0;
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
//add the row to the $chat array at specific index of $i
$exercise[$i] = $row['exercise'];
$i += 1;
}
echo json_encode($exercise);
Now I just need to change the php filed based on whats selected in the first autocomplete field.
If you want to autocomplete based on results from a SQL query without having to leave the page, you might want to look into AJAX and JSON.
Also, please use PDO instead of the mysql_* functions for interfacing with DBMS's with PHP.

parsing multidimensional array from php to jquery

I am using php and jquery to read data out of a database, put it into a 2-dimensional array, return it with jquery, and display it on a webpage. I get tripped up when I try to display it.
Here's my jquery code:
$('.sf1930').click(function(){
$year = "1930";
$.post('get_year.php', {year:$year},
function(data){
console.log(data);
$('#occupant_rect').show();
var obj = jQuery.parseJSON(data);
//$('#occupantList').append( data[0][1] );
console.log(obj[0].address);
$('#occupantList').append( obj[0].address );
})
})
The first console.log displays my data beautifully:
"[{\"address\":\"1202 Arch St.\",\"occupant\":\"Morris Wolfe tailor\"},{\"address\":\"1400 Arch St.\",\"occupant\":\"The Great A&P Tea Co. Grocery\"},{\"address\":\"1500 Arch St.\",\"occupant\":\"Hoge's Drug Store\"}]"
but the second console log shows that obj[0].address is undefined.
Here's my php code:
$year = $_POST['year'];
//echo json_encode($year);
if ($year == '1930') {
$q1930 = "SELECT address, occupant1930 FROM mytable WHERE occupant1930 <> ''";
$result = $mysqli_getstores->query($q1930);
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
//echo json_encode($row['address'] . ',' . $row['occupant1930']);
$response = array(address=>$row['address'],occupant=>$row['occupant1930']);//end array
array_push($responses, $response);//push this array of one record into a larger
//array to hold all records
} //end while
echo json_encode(json_encode($responses)); //return the array of arrays
}//end year == 1930
?>
Note that I've double json_encoded the results.
I've looked at a number of stackoverflow questions on this topic, but the answers don't appear to be working for me.
Does anyone see what I'm doing wrong, please?

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.

How to use data in rows returned from a database in javascript

Using Javascript I need to get some rows from a DB table, and then loop through each row and use different fields from each row.
For example, if I get the rows like this:
var coordinatesArray = '<?php
global $wpdb;
echo $wpdb->get_var("SELECT * FROM users_coordinates WHERE lat>20 and lat<40 and long>-10 and long<40);
?>';
How should I write the following code:
// for each row do: {
// alert the id field
// alert the lat field
// alert the long field
// }
JSON is the way to put the output in, that ensures that the result will be valid JavaScript and protects you from arbitrary code execution in JS.
var coordinatesArray = <?php
global $wpdb;
// replace * by id, lat and long since you don't need other fields
$sql = "SELECT id, lat, long FROM users_coordinates WHERE lat>20 and lat<40 and long>-10 and long<40";
$rows = $wpdb->get_results($sql);
// if the function fails (?), make valid JS syntax
if (is_array($rows)) {
echo json_encode($rows);
} else {
echo '[]';
}
?>;
for (var i=0; i<coordinatesArray; i++) {
alert(coordinatesArray[i].id);
alert(coordinatesArray[i].lat);
alert(coordinatesArray[i]["long"]);
}
The other way would be creating a JS object with the id field as key of the JS object:
var coordinatesMap = <?php
global $wpdb;
// replace * by id, lat and long since you don't need other fields
$sql = "SELECT id, lat, long FROM users_coordinates WHERE lat>20 and lat<40 and long>-10 and long<40";
// note: OBJECT_K, the result will be an associative array with the first field of a
// row as key
$rows = $wpdb->get_results($sql, OBJECT_K);
// if the function fails (?), make valid JS syntax
if (is_array($rows)) {
echo json_encode($rows);
} else {
echo '{}';
}
?>;
for (var id in coordinatesMap) {
if (coordinatesMap.hasOwnProperty(id)) {
alert(id);
alert(coordinatesMap[id].lat);
alert(coordinatesMap[id]["long"]);
}
}
Please replace alert by something else, it's not really user-friendly. Remember that PHP != JavaScript and you cannot use PHP functions in JavaScript and vice versa. If you're not sure how the output would look like, use the View source option of a page.
References:
http://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Results
You may have a better time writing your own custom PHP script to fetch these values (rather than depending on WP), loop through them, and build a json object that you return to the javascript.
First, $wpdb->get_var can only get one value. http://codex.wordpress.org/Class_Reference/wpdb#SELECT_a_Variable
Use $wpdb->get_results instead
http://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Results
var coordinatesArray = '<?php
global $wpdb;
echo $wpdb->get_results("SELECT * FROM users_coordinates WHERE lat>20 and lat<40 and long>-10 and long<40);
?>';
for(coord in coordinatesArray) {
alert(coordinatesArray[coord].id);
alert(coordinatesArray[coord].lat);
alert(coordinatesArray[coord].long);
}
I haven't tested, but it should be something like that.

Categories