i need your help to choose the fastest method to implement autocomplete on a search box in a web form.
i have to inputs to implement that, #city input and #street input.
the autocomplete of the street input must be filtered by the city input, we have 116K rows of street of the whole country.
how do i get it done right and smart?
thanks a lot!
The search.php file is called by the autocomplete() method of Autocomplete plugin. This file retrieves the skills data based on the search term and returns data as a JSON encoded array using PHP and MySQL.
The autocomplete() method make a GET request to source URL and added a query string with a term field. So, you can get the search term using PHP GET method. The following PHP code, fetch the records from the MySQL database (skills table) and filter the records by $_GET['term']. The filtered skill data returned to autocomplete() method as a JSON encoded array.
connect_error) {
die("Connection failed: " . $db->connect_error);
}
// Get search term
$searchTerm = $_GET['term'];
// Fetch matched data from the database
$query = $db->query("SELECT * FROM skills WHERE skill LIKE '%".$searchTerm."%' AND status = 1 ORDER BY skill ASC");
// Generate array with skills data
$skillData = array();
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$data['id'] = $row['id'];
$data['value'] = $row['skill'];
array_push($skillData, $data);
}
}
// Return results as json encoded array
echo json_encode($skillData);
?>
Related
i am trying in pull my data from mySQL and convert it to a format I can then pass to google.maps API. I am thinking mySQL -> php -> javascript -> google.maps makes the most sense but am deffinitly open to other suggestions.
So far I have connected to and successfully queried my data into an array
<?php
//library of mysql functions including linkDB()
include('../sqlFunctions/sqlFunctions.php');
//Establish connection to database
if($link = linkDB()){
echo "connected to DB";
}
//set up a MySQL query. I am simply pulling geocoordinate ints, strings and boolean.
$sql = "SELECT title
,lat
,lng
,titleYou
,descriptionAre
,privacyRockstar
FROM shelters;";
if($results = $link->query($sql)){
echo "<p>Query succsessful.</p>";
}else{
echo "Query Failed";
}
//initialize an array to store data
$rows = array();
while ($data = $results->fetch_assoc()) {
$rows[] = $data;
echo "<br><br>Loop rotation: ";
var_dump($data);
}
echo "<br><p>The End of The Loop<p><br>";
var_dump($rows);
?>
Now I just need to convert this data into something usable I can pass to google.maps.
Before I was pulling JSON from a text file, which worked, but I want to flexibility and stability of a database. It was easy to parse into and array of Javascript Objects. Then I could just call the index and the property that I needed as you can see from this function I was using.
function setMarkers(){
for(i=0; i < jsonParsed.arrayOfObjs.length; i++){
//setting parameters to hand to google
var markerOptions = {
position : jsonParsed.arrayOfObjs[i].position,
map : mapCanvas,
description : jsonParsed.arrayOfObjs[i].title,
icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
};
//create marker
this ['marker' + i] = new google.maps.Marker(markerOptions);
}
}
Thank you for any light you can help shed on my issue.
It sounds like you already found your answer but I'll post for completeness.
Simply change your the var_dump($rows) line to json_encode($rows).
Read more about json_encode in the php docs.
You probably want to have two php files:
api.php file that emits Content-type: application/json
index.php file that emits Content-type: text/html and calls api.php
On the index page, you can make an AJAX call to your API endpoint and then use JSON.parse(response).
I want to display a drop-down list which pull out database values. My actual code working fine, but here I have to provide the list in the array itself. What i required is, without editing the code, i needed to pull out values from database to this array("state1","state2"....); which is equal to something like this array("$states");
$sql = "SELECT * FROM `States`";
$result = $conn->query($sql);
$i=0;
while($row = $result->fetch_assoc()) {
$t=$row['statename'];
$t[$i]=$row['statenname'];
$i++;
}
$countryArr = array( "INDIA" => array("$t"));
I tried the above code but its listing only one value from database.
Remove this line
$t=$row['statename'];
just keep it to be
$t[$i]=$row['statenname'];
I'm trying to create a Google Places URL that can be reused and concatenated with a response from my database.. Not getting this to work and have been trying for a couple of days with no luck! If I echo out the both strings, from PHP on to my web page and copy&paste it, both addresses generate the same Google Places result, but when I print the JSON decoded response I get UNKNOW_ERROR from Google..
This is what I have been trying to use. The first and the second $googlePlacesAPI contains the exact same URL, just that one is concatenated and the other is "hard coded".
$googlePlacesAPI = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" .
$BarName. "+" . $BarCity . "&sensor=false&types=bar|night_club&key=" . $mySuperSecretKey;
$googlePlacesAPI = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" .
$BarName. "+" ."Göteborg". "&sensor=false&types=bar|night_club&key=" . $mySuperSecretKey;
To get the value of $BarCity I use this piece of code (before creating the $googlePlacesAPI variable):
$row = mysqli_fetch_array(mysqli_query($con, "SELECT * FROM City WHERE ID = $CityID"));
mysqli_close($con);
$BarCity = $row['CityName'];
EDIT:
This is how I decode the answer:
$placesSearch = json_decode(file_get_contents($googlePlacesAPI));
You probably want to close the connection after you're done with $row:
$row = mysqli_fetch_array(mysqli_query($con, "SELECT * FROM City WHERE ID = $CityID"));
$BarCity = $row['CityName'];
mysqli_close($con);
See a sample of mysqli_fetch_array usage at http://nl3.php.net/mysqli_fetch_array#example-1728
I have a mysql table with image data in.
I want to retrieve the image data and push into a javascript array.
There are two fields that I want to put into the array and they are image_ref, and image_name
I know I need a 2D array for this and I need to retrive the data from the db using ajax and JSON.
I am not sure how to complete this.
I know I need to call the php page with a JSON ajax call
js:
var imagesArray[];
$.getJSON("get_image_data.php")
.done(function(data) {
/*THIS IS WHERE I NEED HELP---*/
});
get_image_data.php page
include("connect.php");
$query = mysql_query("SELECT * FROM images WHERE live='1' ORDER BY insertDate DESC");
while($row=mysql_fetch_array($query){
echo json_encode(array("a" => $row['image_ref'], "b" => $row['image_name']));
}
I have highlighted where I need help in getting the returned data into the stockImages array.
Can anyone show me the light?
thanks in advance
By calling json_encode() multiple times in your loop, you are creating lots of singular bits of JSON. You should aim at creating and transmitting one transfer object, like this:
include("connect.php");
$query = mysql_query("SELECT * FROM images WHERE live='1' ORDER BY insertDate DESC");
$images = array();
while($row=mysql_fetch_array($query){
$images[] = array("a" => $row['image_ref'], "b" => $row['image_name']);
}
echo json_encode($images);
This will give you one JSON array, through which you can loop in your client side Javascript.
Actually, it is PHP that is wrong, 'cause on JS you will have the array you need directly in "data".
You PHP code should look like:
$query = mysql_query("SELECT * FROM images WHERE live='1' ORDER BY insertDate DESC");
$result = array();
while($row=mysql_fetch_array($query){
$result[] = array("a" => $row['image_ref'], "b" => $row['image_name']);
}
echo(json_encode($result));
There seem to be many questions in around this topic but none seem to answer my question. I have a simple website with a signup form, and when users enter their email I want to push this as a new row in a Google Spreadsheet I have already setup. I don't want the user to authenticate or even know about this spreadsheet. How do I authenticate so I can start using the Google API? Code/pseudocode would be greatly appreciated! Here are some examples that do not answer my question:
Using Google Spreadsheet as DB for apps
Google spreadsheet as db for web applications
Here's a link to a library for accessing Google Spreadsheets:
https://github.com/EastCloud/node-spreadsheets
Note: Ive not actually used this lib
You will need to use PHP and the Zend GData Library.
When you post your form to your PHP script, you'll need to collect all of the variables into an associative array that you then pass to the insertRow method of Zend_Gdata_Spreadsheets.
It's important to note that your spreadsheet must contain column headers for my example to work. E.g. First Name / Last Name and it's important to note that when you target these column headers in a script, they will need to be all lowercase and stripped of spaces because this is how the spreadsheet expects them.
Here is a basic example of the PHP script:
<?php
$errors = array(); // use this to create an associative array to json encode and send back any errors
$rowData = array(); // this will be the associative array that gets passed to the insertRow method
$firstName = $_POST['firstName'];
if(isset($firstName)){
$rowData['firstname'] = $firstName; // note the key 'firstname' must equal the column header in your spreadsheet which you are inserting the value into. the column header name key should be all lowercase and not contain spaces regardless of if you have it in the spreadsheet
}else{
$errors['firstname'] = '1';
}
$lastName = $_POST['lastName'];
if(isset($lastName)){
$rowData['lastname'] = $lastName; // note the key 'lastname' must equal the column header in your spreadsheet which you are inserting the value into. the column header name key should be all lowercase and not contain spaces regardless of if you have it in the spreadsheet
}else{
$errors['lastname'] = '1';
}
set_include_path($_SERVER['DOCUMENT_ROOT'] . '/library/');
$spreadsheetKey = 'your-spreadsheet-key';
$worksheetId = 'your-worksheet-id'; // if you only have one worksheet this will be 'od6'
require_once 'Zend/Loader/Autoloader.php';
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->setFallbackAutoloader(true);
$user = "your-user-name-at-gmail-dot-com";
$pass = "your-password";
$service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
$spreadsheetService = new Zend_Gdata_Spreadsheets($client);
$query = new Zend_Gdata_Spreadsheets_DocumentQuery();
$query->setSpreadsheetKey($spreadsheetKey);
$feed = $spreadsheetService->getWorksheetFeed($query);
global $spreadsheetService,$spreadsheetKey,$worksheetId,$rowData;
$insertedListEntry=$spreadsheetService->insertRow($rowData,$spreadsheetKey,$worksheetId);
$returnObject['success'] = 'true';
echo(json_encode($returnObject));
?>
Let me know if this works for you.