autocomplete dos not show result passing custom values - php

i'm trying to pass custom values to autocomplete, so:
my custom work value's its based in this question
using a default source like doc's:
$("#inpPesqCli").autocomplete({
source: "ajax/search.php",
minLength: 2,
autoFocus: true
});
firebug returns this (example):
[...
{ "id": "29083", "label": "SOME ONE 2", "value": "SOMEONE WITH LELE" },
{ "id": "19905", "label": "SOME ONE", "value": "SOMEONE WITH LALA"},
...]
work's perfect, results shows up.
when i try to set some custom values:
$("#inpPesqCli").autocomplete({
source: function( request, response ) {
$.ajax({
url: "ajax/search.php",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 2,
autoFocus: true
});
firebug return's me the exactly same array result:
[...
{ "id": "29083", "label": "SOME ONE 2", "value": "SOMEONE WITH LELE" },
{ "id": "19905", "label": "SOME ONE", "value": "SOMEONE WITH LALA"},
...]
but, the problem is, when i pass custom calues, the result's dosent shows up.
php:
$type = "C";
$q = strtolower($_GET["name_startsWith"]); // this i change: custom = name_startsWith / default = term
if (!$q) return;
$res = $p->SomeClass($codemp,$q,$type);
$items = array();
while(!$res->EOF){
$items[$res->fields["NOMCLI"]] = $res->fields["CODCLI"];
$res->MoveNext();
}
// below this, i have the php autocomplete default function, if u need, ask then i post.
dont know what i'm missing.

set ajax type = GET , maybe work, by default data send type is POST
$("#inpPesqCli").autocomplete({
source: function( request, response ) {
$.ajax({
url: "ajax/search.php",
dataType: "jsonp",
type : "GET",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 2,
autoFocus: true
});

Related

Datatable default ordering not applying

I have this code for jQuery Datatables, it works fine, everything is working as it should aside from the order function is not sorting the column on page load (or at all).
What am I doing wrong here? I've read Datatables documentation and this appears to be correct.
$(document).ready(function() {
$('#data').DataTable( {
"ajax": {
"dataType": 'json',
"url": "package.json",
"dataSrc": "search_result",
"order": [ 0, "desc" ]
},
"columns": [
{ "data": "num" },
{ "data": "domain_name",
"render": function(data, type, row, meta)
{
if(type === 'display')
{
data = '<a class="intel_link" href="http://www.' + data + '" target="_blank">' + data + '</a>';
}
return data;}
},
{ "data": "query_time"},
{ "data": "create_date" },
{ "data": "update_date" },
{ "data": "expiry_date" }
]
} );
} );
Problem is with sort attr, its written inside ajax block.
$(document).ready(function() {
$('#data').DataTable( {
"ajax": {
"dataType": 'json',
"url": "package.json",
"dataSrc": "search_result"
},
"order": [ 0, "desc" ]
"columns": [
{ "data": "num" },
{ "data": "domain_name",
"render": function(data, type, row, meta)
{
if(type === 'display')
{
data = '<a class="intel_link" href="http://www.' + data + '" target="_blank">' + data + '</a>';
}
return data;}
},
{ "data": "query_time"},
{ "data": "create_date" },
{ "data": "update_date" },
{ "data": "expiry_date" }
]
} );
} );
For more detail ref Datable Order

Ajax with HighCharts setData on Symfony 2

I have a problem on my HighCharts graph with JSON data. To explain a litle bit : I have a form, when I submit this form I send my data to my controller with Ajax, I treat them and I return the new array of data for my highcharts graph, but when I use setData function with my new array the graph disappear and the new data aren't displayed.
Here is my ajax function and my test to set the new data into my graph :
$('#gestion .l-gestion-content-form #form-add-informations .btn-validation').click(function(e) {
e.preventDefault();
var chart = $('#hightchart-graf').highcharts();
var dataActionForm = $('#form-add-informations').attr('action').split("/");
var url_ajax = Routing.generate('gestion_view', { dossier: dataActionForm[4], fille: dataActionForm[5] });
var formData = $('#form-add-informations').serializeArray();
$.ajax({
type: "POST",
dataType: 'json',
url: url_ajax,
data: formData,
success: function(msg)
{
console.log(msg['infosArray']);
var test = [ msg['infosArray'].join(',') ];
console.log(test);
console.log('---------------------------------------------');
console.log(msg.infosArray);
var test2 = msg.infosArray.join(',');
var test3 = test2.replace('"', '');
console.log(test2);
chart.series[0].setData( [ msg.infosArray.join(',') ] );
//[ {{ msg.infosArray | join(',') }} ]
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('ERROR');
}
});
});
All my data are stored in the array named msg.infosArray or msg['infosArray'] and the first console.log return an array like this :
["[Date.UTC(2015,11,23),80.00]", "[Date.UTC(2015,11,23),89.00]", "[Date.UTC(2015,11,25),150.00]", "[Date.UTC(2015,11,28),45.00]", "[Date.UTC(2015,11,29),169.00]", "[Date.UTC(2015,11,29),189.00]", "[Date.UTC(2015,11,29),196.00]", "[Date.UTC(2015,11,29),200.00]", "[Date.UTC(2015,11,29),205.00]", "[Date.UTC(2015,11,30),210.00]", "[Date.UTC(2015,11,31),225.00]", "[Date.UTC(2016,0,1),250.00]", "[Date.UTC(2016,0,2),25.00]", "[Date.UTC(2016,0,3),259.00]", "[Date.UTC(2016,0,5),25.00]", "[Date.UTC(2016,0,6),250.00]", "[Date.UTC(2016,0,7),25.00]", "[Date.UTC(2016,0,8),250.00]", "[Date.UTC(2016,0,9),25.00]", "[Date.UTC(2016,0,10),250.00]", "[Date.UTC(2016,0,11),25.00]", "[Date.UTC(2016,0,12),250.00]", "[Date.UTC(2016,0,25),25.00]", "[Date.UTC(2016,0,26),250.00]"]
So I tried to escape " and ' or to join the array but nothing work. Somebody know how can I set the new data, or where I commited a fault ?
Maybe i got a bad response from my Controller ?
Thanks
You need to convert string of javascript code to array of javascript.
I wrote a demo version which converts string to javascript code. and draws chart as expected. Do not focus on the labels it's a dummy data.
JSFiddle Demo
$(function () {
var data = ["[Date.UTC(2015,11,23),80.00]", "[Date.UTC(2015,11,23),89.00]", "[Date.UTC(2015,11,25),150.00]", "[Date.UTC(2015,11,28),45.00]", "[Date.UTC(2015,11,29),169.00]", "[Date.UTC(2015,11,29),189.00]", "[Date.UTC(2015,11,29),196.00]", "[Date.UTC(2015,11,29),200.00]", "[Date.UTC(2015,11,29),205.00]", "[Date.UTC(2015,11,30),210.00]", "[Date.UTC(2015,11,31),225.00]", "[Date.UTC(2016,0,1),250.00]", "[Date.UTC(2016,0,2),25.00]", "[Date.UTC(2016,0,3),259.00]", "[Date.UTC(2016,0,5),25.00]", "[Date.UTC(2016,0,6),250.00]", "[Date.UTC(2016,0,7),25.00]", "[Date.UTC(2016,0,8),250.00]", "[Date.UTC(2016,0,9),25.00]", "[Date.UTC(2016,0,10),250.00]", "[Date.UTC(2016,0,11),25.00]", "[Date.UTC(2016,0,12),250.00]", "[Date.UTC(2016,0,25),25.00]", "[Date.UTC(2016,0,26),250.00]"];
//t = t.map(function(element){return eval(element);});
data = data.map(function (e) {
return eval(e);
});
data = data.map(function (e) {
return [(new Date(e[0])).toLocaleString(), e[1]]
});
var categories = data.map(function (e) {
return (new Date(e[0])).toLocaleString()
});
// t[0] = [date = new Date(t[0])];
$('#container').highcharts({
title: {
text: 'Monthly Average Temperature',
x: -20 //center
},
subtitle: {
text: 'Source: WorldClimate.com',
x: -20
},
xAxis: {
categories: categories
},
yAxis: {
title: {
text: 'Temperature (°C)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: '°C'
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: 'Tokyo',
data: data
}]
});
});

JQuery Autocomplete with Geonames and MYSQL

I trying to create a multifunctional search bar, where one can not only look for cities (using Geonames) but also using the same input field for finding signed up users (using my MYSQL table.
I managed to achieve both seperately, however I couldn't manage to merge the code together.
The JQuery code for the geoname autocomplete:
$(function() {
$( "#top_search_field" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://api.geonames.org/searchJSON?username=dummie",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
country: "AT",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function (event, ui) {
var selectedObj = ui.item;
jQuery("#top_search_field").val(selectedObj.value);
return false;
},
open: function () {
jQuery(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
jQuery(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
});
The code for grabbing the users from the table:
$(function() {
$( "#top_search_field" ).autocomplete({
source:'php_includes/search.php',
minLength: 2,
open: function () {
jQuery(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
jQuery(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
})
});
search.php
include_once("db_connect.php");
$stmt = $db_connect->query("SELECT user_auth, first_name, last_name, avatar FROM users WHERE (first_name LIKE '%".$_REQUEST['term']."%' OR last_name LIKE '%".$_REQUEST['term']."%') ");
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$results[] = array('label' => utf8_encode($row['first_name'].' '. $row['last_name'] ) );
}
echo json_encode($results);
What is the best way to merge the codes together and make it possible to look for both cities and users?
You need to do a service for getting information from multiple service, combine them and respond to your autocomplete result. Let say you have a service called advanced_search.php. In this file;
<?php
$keyword = $_GET["keyword"];
$result = array();
$usersReturnedFromService = getUsersFromService($keyword); // Get users from service by using curl
foreach ($usersReturnedFrom as $user) {
array_push(array("type" => "user", "value" => $user));
}
$geoNamesReturnedFromService = getGeoNamesFromService($keyword); // Get geonames from service by using curl
foreach ($geoNamesReturnedFromService as $geoname) {
array_push(array("type" => "geoname", "value" => $geoname));
}
// When you sort, result will mixed
function compareArr($a, $b){
$ad = strtotime($a['value']);
$bd = strtotime($b['value']);
return ($ad-$bd);
}
usort($result, 'compareArr');
echo json_encode($result);
And in js side;
$(function() {
$( "#top_search_field" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "advanced_search.php?keyword=" + request.term, // put other variables here. I have only put term
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.value, // john
value: item.type + "|" + item.value // user|john
}
}));
}
});
},
minLength: 2,
select: function (event, ui) {
var selectedObj = ui.item;
jQuery("#top_search_field").val(selectedObj.value);
return false;
},
open: function () {
jQuery(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
jQuery(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
});

jQuery UI autocomplete wont display returned json (PHP)

The jQuery:
$("[type=text]").autocomplete({
source: "json.php",
minLength: 0
}).addClass("ui-widget ui-widget-content ui-corner-left");
Works fine if I change the source: to a JS array. I know that the php is working because I can see it in the console, but here is the sample php anyways:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
So the dropdown just isn't displaying. Feeling pretty stupid right about now.
In your json.php file, be sure to set the content encoding to be json via the header() function before your echo. This way jQuery should see the array as proper json.
header("Content-Type: application/json");
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
A few days ago I was also having problems with a JSON-populated Autocomplete.
My problem was that I wasn't setting the content-type, as Wally said above:
header("Content-Type: application/json");
I also wrapped my jQuery autocomplete call inside a getJSON, then used the data from that function to populate the autocomplete field. My gut tells me that the extra getJSON shouldn't be necessary, but like you, I was having problems referencing my PHP file as the source.
$.getJSON("json.php", function(data) {
$("[type=text]").autocomplete({
dataType: "json",
source: data,
minLength: 1,
});
});
Since I'm using an old PHP version, I hand-made my JSON. I included "label" and "value" fields because I'm fairly certain they're necessary for the autocomplete to work.
$jsonList = "[{"label" : "Item 1", "value" : "1"}, {"label" : "Item 2", "value" : "2"}]";
return $jsonList;
http://jqueryui.com/demos/autocomplete/remote-jsonp.html
Check this get from demos site.
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});

How to set id after creating new jstree node?

I'm using jsTree 1.0. And have this code :
$(document).ready(function () {
$("#folders_tree").jstree({
"core": {
"initially_open": ["root"]
}, "html_data": {
"data": '<?= $folders; ?>'
}, "themes": {
"theme": "default",
"dots": true,
"icons": true,
"url": "<?= Yii::app()->request->baseUrl ?>/css/jstree/themes/default/style.css"
}, "contextmenu": {
"items": {
"create": {
"label": "Create",
"action": function (obj) {
this.create(obj);
}, "_disabled": false,
"_class": "add",
"separator_before": false,
"separator_after": false,
"icon": false
}, "rename": {
"label": "Rename",
"action": function (obj) {
this.rename(obj);
}, "_disabled": false,
"_class": "rename",
"separator_before": false,
"separator_after": false,
"icon": false
}, "remove": {
"label": "Delete",
"action": function (obj) {
this.remove(obj);
}, "_disabled": false,
"_class": "delete",
"separator_before": true,
"separator_after": false,
"icon": false
}, "ccp": false
}
},
"plugins": ["themes", "html_data", "ui", "crrm", "contextmenu"]
});
/* Callbacks */
var folders = $("#folders_tree");
folders.bind("create.jstree", function (e, data) {
var parent_id = data.rslt.parent[0].id;
var name = data.rslt.name;
var node = data.args[0];
var dataArray = {
"ref_folder": parent_id,
"name": name
};
var dataString = JSON.stringify(dataArray);
$.ajax({
type: 'POST',
url: '<?= Yii::app()->createUrl('
ajax / createfolder ') ?>',
data: {
data: dataString
}, success: function (jdata) {
var json_data = JSON.parse(jdata);
// Here's! This code is not working. Id is not set.
$(node).attr("id", json_data.new_id);
}, dataType: 'text'
});
});
});
$(node).attr("id", json_data.new_id) // this code is not working.
I'm stuck on this :( How can I set this id?
The node variable must be declared as :
var node = data.rslt.obj;
And called as :
node.attr("id", json_data.new_id);
I would do alert(jdata) in the success callback.
Be sure the server is returning safe JSON and that the actual new_id attribute exists.

Categories