Using id and value with jquery autocomplete, javascript, json and php - php

I'm looking for a simple example of some code showing how to use jquery autocomplete with ids and values, json and php, but I can't find any. Basically I have a list of employee names in a database, they have an id and a name. I would like to display the name, but use the id in a hidden field in my form submission. I would like to provide the list of names via php and json ajax. I would also like to use the feature where you have to enter say 3 characters before it shows the autocomplete, since it is a very long list of employee names. Not sure whether you have to pass the 3 characters to the php as a parameter for this.
I'm a noob so a simple example would really be appreciated.
Thanks

There are great examples here at jQuery UI:
http://jqueryui.com/demos/autocomplete/#remote
Click the view source button below the example to get a look at the Javascript side of things. Note the parameters for "source" (this is the path to your PHP script delivering results) and "minLength." Setting the minLength property to 3 will take care of the second part of your question.
As far as the remote side the results need to be in JSON format so you can query your data from the database, get it as a PHP associative array and then use the json_encode() method to put it into a format that the autocomplete plugin can read. The autocomplete implementation in their example sends a querystring variable, "term", to the source file containing the search string input by the user.
This example expects JSON results from the server to be in this format:
[ { "id": "Branta hrota", "label": "Pale-bellied Brent Goose", "value": "Pale-bellied Brent Goose" }, ...]
So the PHP source page could deliver results by using code like this:
// source.php (or whatever path you used for the autocomplete "source" setting)
// Sanitize your input!
$term = mysql_real_escape_string( $_GET['term'] );
$results = mysql_query( "SELECT * FROM employees WHERE name LIKE '%{$term}%' "); // Grab your data
$output_array = new array();
while ( $row = mysql_fetch_assoc( $results ) ) {
$output_array[] = array(
'id' => $row['id']
, 'label' => $row['name']
, 'value' => $row['name']
);
}
// Print out JSON response
echo json_encode( $output_array );
So that's all untested pseudocode, but it should point you in the right direction.

Related

How to get all variable with "Required" As her value? On a get cURL PHP

I'm trying to build a page that use API from another site. I'm kind noob on this so my question can be silly.
This site have a bunch of category and on each of this category there are different fields that have to be filled so you can post an item.
So instead of me creating a page for each category, and try to pass a get that is already available on their API get the variable that have Required as it value so I can pass it to my code to fill it the right way.
So if I pass:
curl -X GET -H 'Authorization: Bearer $ACCESS_TOKEN' https://api.mercadolibre.com/categories/MLA1055
It returns me a lot of results, and on some of it are:
"shipping_profile": "optional",
"show_contact_information": false,
"simple_shipping": "optional",
"stock": "required"
So my idea is if there is a way to get the the name of the result that will be stock. So I can put it on my code so the user can fill it and I don't have to do category by category...
Like I said before. I'm noob at PHP and cURL, but I have some experience with coding, is just a new language, hope you guys can help me.
First, you would have to convert the JSON string from API into an object understood by PHP, we have json_decode() for this:
//let's assume JSON data has been downloaded and stored in data.json file
$jsonString = file_get_contents(dirname(__FILE__) . '/data.json');
$jsonObject = json_decode($jsonString, true);
Next, from the URL you gave in the comment, I can see that the "required" data is stored inside settings key. You can use JSON viewer tools to visualize the data.
I'm using online JSON viewer tools
Extract it to another variable, or just loop through the elements:
$arrayRequired = array();
foreach($jsonObject['settings'] as $key => $setting){
if($setting === 'required'){
$arrayRequired[] = $key;
}
}
Your required keys now stored inside $arrayRequired variable:
print_r($arrayRequired);
Array
(
[0] => immediate_payment
[1] => price
[2] => stock
)
That's it.

I fetch data from podio CRM using PHP

I fetch data from podio CRM using PHP language and I fetch data for each element via its id as it is found in this function:
public function getContacts($item_id) {
$this->contactAuth();
$item = \PodioItem::get_by_app_item_id($podio_contact_app_id,$item_id);
return $item;
}
For example we have the 'Status' we show it like this:
$status = $item->fields[6]->values;
Not all elements get it right though it is the same function.
Sometimes :
$status = $item->fields[6]->values;
and sometimes :
$status = $item->fields[8]->values;
Can we know what caused the problem?
If some fields are empty they will not be presented in the PodioItem object, that is why the position of a particular field in the array may vary (like a Status field in your example).
So instead of using a field index (which may vary), you should get the value from a field by field's External ID (a human readable name like 'title', 'status' etc) or Field ID (a numeric code):
$item->fields['title']->values // 'title' is an External ID
$item->fields->get(123456789)->values // 123456789 is a Field ID
To know what External ID and Field ID are for a particular field you can list all fields like this:
// Iterate over the field collection
foreach ($item->fields as $field) {
// You can now work on each individual field object:
print "This field has the id: ".$field->field_id;
print "This field has the external_id: ".$field->external_id;
}
Or you can see developer's info on all fields right in Podio in App menu → Developer
And anyways, check the Podio PHP wrapper documentation at https://podio-community.github.io/podio-php/items/ it is pretty useful:)

Twitter typeahead not matching correctly when using "remote", but working with "local" JSON

I'm creating an autocomplete in Laravel 4 using twitter typeahead, but I'm having problems in the matching process.
The JS code:
$('#autocomplete').typeahead({
limit: 20,
name: 'destinatari',
prefetch: '{{URL::to("alumni/posta/utenti")}}',
remote: '{{URL::to("alumni/posta/utenti")}}'
});
The model populates the array like this:
public static function jsonList($idLogged)
{
$users = DB::table('users_data')
->where('userid', '!=', $idLogged)
->select('nome', 'nome_2', 'cognome', 'cognome_2', 'userid')
->orderBy('cognome', 'asc')
->orderBy('nome','asc')
->get();
$i = 0;
$ordered = array();
foreach($users as $u) {
$ordered[$i]['value'] = $u->nome.' '.$u->nome_2.' '.$u->cognome.' '.$u->cognome_2;
$ordered[$i]['tokens'] = array($u->nome, $u->cognome);
$ordered[$i]['userid'] = $u->userid;
$i++;
}
return $ordered;
}
And my controller simply:
return Response::json( Users::jsonList($this->userdata->id) );
The returned json (I see it in Firebug) looks like:
[{"value":"Silvia Miriam Abeyta Carretero","tokens":["Silvia","Abeyta"],"userid":"246"},
{"value":"Malak Julia Abreu Garrido","tokens":["Malak","Abreu"],"userid":"198"},{"value":"Aina Aguado ","tokens":["Aina","Aguado"],"userid":"243"},
{"value":"Jordi Alarc\u00f3n ","tokens":["Jordi","Alarc\u00f3n"],"userid":"308"},
{"value":"Aaron Nerea Alejandro ","tokens":["Aaron","Alejandro"],"userid":"49"},
{"value":"Alexia Alem\u00e1n ","tokens":["Alexia","Alem\u00e1n"],"userid":"306"},
{"value":"Salma Almaraz ","tokens":["Salma","Almaraz"],"userid":"54"},
{"value":"Alma Almonte Nev\u00e1rez","tokens":["Alma","Almonte"],"userid":"101"},
{"value":"Daniela Almonte ","tokens":["Daniela","Almonte"],"userid":"184"}
,....other similar results....]
The problem is that any letter I type only the first name in the list gets autocompleted ("Silvia Miriam Abeyta Carretero") in the input field, but when I type out in full any other name (say, "Daniela Almonte") the field isn't completed and the dropdown keeps showing the whole 20 results, without processing of any kind.
I must say, though, that if I click on a name it gets selected correctly (I'm logging the userid property of the datum ), but still the autocompletion isn't working.
What puzzles me is that If I copy/paste the whole list directly in the JS (taken as is from Firebug), as local property of typeahead() (instead of remote), everything works fine as it should.
What could be causing this? Is it a Laravel response problem? Or is it the typeahead processor (I believe it's in "transport.js" source file, uses jQuery $.ajax()) of the remote url?
It seems like the returned JSON is considered as a single entry, i don't know why since it looks correct to me...
From the typeahead documentation:
$('input.twitter-search').typeahead({
name: 'accounts',
prefetch: 'https://twitter.com/network.json',
remote: 'https://twitter.com/accounts?q=%QUERY'
});
As you can see, the remote parameter must contains the URL with the query parameter.
PHP side, you have to test if the parameter "q" is set and then adapt your request (with a LIKE statement by example) to correctly filter the list.
Otherwise, you can try to remove this remote parameter, maybe it would work with only the prefetch attribute.

How do I get FullCalendar to display information from my JSON feed?

I'm setting up an app using FullCalendar (http://arshaw.com/fullcalendar/) that will allow the user to see client scheduling information as well as schedule clients through a management interface.
I want to use a MySQL database to populate an array, and then pass that array in the form of a JSON feed to FullCalendar on an HTML page. Ideally, then, the client information would show up on the HTML page. However, even though my JSON feed is being passed, there are no events on my FullCalendar.
Example JSON feed being passed:
[{"title":"Watson","start":"1333976400","end":"1333980000","allDay":false}]
I'm fairly new to these languages and I would not be surprised if this mistake turn out to be simple.
I would deeply appreciate any help or insight on having these events show up. When I manually feed an array into FullCalendar, it does show the events, but so far my JSON feed has resulted in no information being displayed.
Thank you
For reference:
HTML:
$(document).ready(function() {
$('#calendar').fullCalendar({
events: '/json-events.php'
});
});
PHP:
while ($record = mysql_fetch_array($result)) {
$event_array[] = array(
'id' => $record['id'],
'title' => $record['title'],
'start' => $record['start_date'],
'end' => $record['end_date'],
'allDay' => false
);
}
echo json_encode($event_array);
So the problem, for those searchers that come after me, was that my PHP file had HTML head and body tags. I'm a PHP noob and so I didn't know that would cause it not to work. In order for FullCalendar to display the JSON feed, it must ONLY have PHP code, no HTML. JSONLint.com was invaluable in figuring that out.
I set up a quick example and didn't have any trouble getting this to work:
PHP:
<?php
$record[0]["title"]="Test 1";
$record[1]["title"]="Test 2";
$record[2]["title"]="Test 3";
$record[0]["start_date"]="1333976400";
$record[1]["start_date"]="1333976401";
$record[2]["start_date"]="1333976402";
$record[0]["end_date"]="1333980000";
$record[1]["end_date"]="1333980001";
$record[2]["end_date"]="1333980002";
$record[0]["id"]="1";
$record[1]["id"]="2";
$record[2]["id"]="3";
for ($i=0; $i<3; $i++) {
$event_array[] = array(
'id' => $record[$i]['id'],
'title' => $record[$i]['title'],
'start' => $record[$i]['start_date'],
'end' => $record[$i]['end_date'],
'allDay' => false
);
}
echo json_encode($event_array);
exit;
?>
HTML:
events: '/events.php'
Sample output from the PHP script:
[{"id":"1","title":"Test 1","start":"1333976400","end":"1333980000","allDay":false},{"id":"2","title":"Test 2","start":"1333976401","end":"1333980001","allDay":false},{"id":"3","title":"Test 3","start":"1333976402","end":"1333980002","allDay":false}]
So given that the above works for me and it's really no different to what you have above, you might need to check that the PHP script is actually getting called correctly. Check the Javascript console in Mozilla Firefox or Google Chrome to see if there are any errors thrown when Fullcalendar tries to load the events. Check your web server access/error logs for any mention of the PHP script.
events: '/json-events.php'
should be either
events: './json-events.php'
or
events: 'json-events.php'
Let me know if this helps...
EDIT
I also noticed that in the Json that your are receiving there is no id in the line. There may be something going on between the nameing of you id within the DB comparitively to the name your using in the array. Check it out and see if that is what is going on, because that is one of the properties that are required to pass the event.
EDIT
Try removing the [] from $event_array[] and see what happens... If that doesn't work than I am stumpped... sorry

How do you get a text box that becomes a pull down menu like in Yahoo Finance "Get Quotes"?

The first letter you enter creates a pull-down menu of all items in a database that start with that letter...
Are you looking for autocomplete plugin?
Using Plugins/Autocomplete/autocomplete, it seems you can use "local" data, directly into the JS code, ie without having to do an Ajax request to the server :
autocomplete( url or data, [options] )
url or data : String, Array
An URL pointing at a remote resource
or local data as an array.
options (Optional) : Options
A set of key/value pairs that
configure the autocomplete. All
options are optional.
So, you need a way to convert the data you have on the PHP side to some Javascript array.
If you are using PHP >= 5.2, you can use the json_encode function to do that.
For instance, you can have this kind of PHP code :
$data = array(
'first',
'second',
'third',
);
$js_array = json_encode($data);
echo "var my_list = {$js_array};";
And the output you'll get looks like this :
var my_list = ["first","second","third"];
Which declares an initializes some Javascript array containing the results ;; up to you to put that kind of code where it belongs ;-)
Have fun !

Categories