jQuery autocomplete from php-json without database - javascript

I want to make autocomplete on my form with jQuery. The source taken from json data from php, but i don't use database.
Here is my code :
facebookfriends.php
<?php
include('facebookdata.php');
$user_friend = $user_friends['data'];
$json_friends = json_encode($user_friend);
echo $json_friends;
?>
Script
$(function() {
$( "#search" ).autocomplete(
{
source:'facebookfriends.php',
});
});
JSON DATA
[{"name":"Indiarto Priadi","id":"502163984"},
{"name":"Agustin Kertawijaya","id":"511990261"},
{"name":"Jecklyne Christin L","id":"528197912"},
{"name":"Jazi Eko Istiyanto","id":"531149275"},
{"name":"Esritha Situmorang","id":"535864892"},
{"name":"Christy Margaretha Siregar","id":"543468540"},
{"name":"Daniel Oscar Baskoro","id":"549332828"},
........]
I just want to display the name in autocomplete to ensure that the autocomplete works well. But it doesn't. Please help. Thank you!

1.You have to parse json in php
2.make an array for dropdown list
Following steps to be followed:
$data ='[{"name":"Indiarto Priadi","id":"502163984"},
{"name":"Agustin Kertawijaya","id":"511990261"},
{"name":"Jecklyne Christin L","id":"528197912"},
{"name":"Jazi Eko Istiyanto","id":"531149275"},
{"name":"Esritha Situmorang","id":"535864892"},
{"name":"Christy Margaretha Siregar","id":"543468540"},
{"name":"Daniel Oscar Baskoro","id":"549332828"}]';
$user_friend = json_decode($data, true );
$data=array();
foreach($user_friend as $key=>$val)
$data[]=$val['name'];
$json_friends =json_encode($data);
echo $json_friends;

you need to pass label and value into you php file
For example
$data[] = array(
'label' => $row['city_name'].','.$state['state_name'].','.$c_name['country_name'],
'value' => $row['city_name'].','.$state['state_name'].','.$c_name['country_name']
);
echo json_encode($data);
flush();

Related

Giving json to Autocomplete JQuery

I have the following javascript,php (idf is an inputbox in html):
JS:
$(document).ready(function() {
// tell the autocomplete function to get its data from our php script
$('#idf').autocomplete({
source: "../php/testingauto.php"
});});
PHP:
<?php
include('connection.php');
session_start();
try{
$q =$conn->query("SELECT ID_farm FROM farm");
$result=$q->fetchAll(PDO::FETCH_ASSOC);
if(count($result)!=0) {
echo json_encode($result);
}
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
And I want to give my JSON result in the auto-complete list.
But I always get a null result on the output of the auto-complete function.
Am I doing something wrong ?
This is the JSON I get from echo: [{"ID_farm":"CYS1000004"},{"ID_farm":"CYS1021009"}]
Any help is appreciated. Thanks.
you need to render correct format from the resource response like the availabletags example, Hope it helps :)

Passing array values to js

So current setup is as following:
PHP:data.php
<?php
$method = $_SERVER['REQUEST_METHOD'];
$data = array(
"16508",
"16498",
"16506"
);
if ($method === "GET") {
echo json_encode($data);
}
?>
JS:
$.get("./page_asset/data.php").then(function(returned) {
data = JSON.parse(returned);
};
Now, how do I parse the data without getting the specific php page (as I don't want to rely on the specific php address such as "/page-asset/data.php").
For example:
PHP:
<?php
$data = array(
"16508",
"16498",
"16506"
);
?>
I simply want to pass these values to js without relying on the page url.
You can use PHP to create the Javascript in the original page. json_encode() can be used to convert a PHP value to the analogous JS literal.
<?php
$data = array(
"16508",
"16498",
"16506"
);
?>
<script>
var data = <?php echo json_encode($data); ?>;
</script>
You can use a hidden field:
<input id="my-data" type="hidden" value='<?php echo json_encode($data)?>' />
And then you can parse the input value from javascript:
var data = $.parseJSON($('#my-data').val());

How to pass extra data content on yii activeform's ajax parameters?

I am trying to set up a ajax request when radio button is clicked. Here is my code that I am trying for.
<?php echo $form->dropDownListRow($model, 'page', $pages, array('class' => 'span5', 'prompt' => '-- page --')); ?>
<?php echo $form->radioButtonListInlineRow($model, 'for', array('desktop'=>'Desktop', 'mobile'=>'Mobile'), array('ajax' => array(
'type'=>'POST',
'url'=>Yii::app()->createUrl('/admin/adv/loadpositions'), //or $this->createUrl('loadcities') if '$this' extends CController
'update'=>'#Adv_position', //or 'success' => 'function(data){...handle the data in the way you want...}',
'data'=>array('for'=>'js:this.value', 'page' => 'XXXXXXXX'),
)));
?>
I just want to pass its's value as well as it's upper field's value to the ajax action. How can I make it come true. 'data'=>array('for'=>'js:this.value', 'page' => 'XXXXXXXX'),.
Thanks in advance.
$(this.form).serialize()
Will give you the form data. Try something like:
<?php
echo $form->radioButtonList($model, 'for', array('desktop'=>'Desktop', 'mobile'=>'Mobile'), array('ajax' => array(
'type'=>'POST',
'url'=>Yii::app()->createUrl('/admin/adv/loadpositions'),
'data'=>array('data'=>'js:$(this.form).serialize()'),
)));
?>
Update:
You can easily parse this serialized string using PHP function parse_str
<?php
$data = 'str1=value1&str2=value2';
parse_str($data);
echo $str1; //value1
echo $str2; //value2
Just change your data attribute to something like this:
'data'=>array('for'=>'js:this.value', 'page' => 'js:$("#someId").val()'),

how to get the value of array sent from AJAX POST in php?

i am having a probelem with ajax multiple delete. I've sucessfully set the values of the checkbox slected in a variable.
the problem i have to solve is how to get the value of the sent array in php.
here is the ajax post code
<script>
$("#delete-btn").click(function(e){
e.preventDefault();
var id = new Array();
$(".check:checked").each(function() {
id.push($(this).attr('value'));
});
$.post("../ajax/multiDelete.php",{id:id},function(data){
alert(data);
});
});
</script>
now, the php page
<?php
if(isset($_POST['id'])){
$id = array($_POST['id']);
foreach($id as $value){
echo $value;
}
}
?>
when the data is alerted, i only get "array";
i do not know about JSON, so if there is anything i can do without it then your help is most appreciated! thanks : D
Since id is an array and in your code you are wrapping it inside an array again. Instead of that,do this :
<?php
if(isset($_POST['id'])){
// Don't use array($_POST['id']) as id is already an array
$id = $_POST['id'];
foreach($id as $value){
echo $value;
// Here you'll get the array values
}
}
?>
If you want retun array from php - user json_encode()
echo json_encode(array($_POST['id']));
P.S. JS function alert() can`t print arrays or object. Use console.log(data) and you will see result in developer console of your browser.
This is not related to your question, but I just wanted to show you a better way of getting the id values, without creating a new array variable and then pushing items into the array, by using the jQuery .map() method:-
$("#delete-btn").click(function (e) {
e.preventDefault();
// Get all the values in the array 'id' variable
var id = $(".check:checked").map(function () {
return this.value || 0;
}).get();
$.post("../ajax/multiDelete.php", { id: id }, function (data) {
alert(data);
});
});
Hope this helps!
Don't pass array variable in AJAX. Convert id array to JSON using JSON.stringify(id).
In PHP backend,use
<?php $val = json_decode($_REQUEST['id']);
foreach($val as $ids){
echo $ids;
}
use $val array to proceed further in php.
You have to access your checked value by-
<?php
if(isset($_POST['id'])){
$id = array($_POST['id']);
foreach($id as $value){
foreach($value as $value1){
echo $value1;
}
}
}
?>
Because this is an array inside array.

jQuery autocomplete returns some null values

I'm using jQuery autocomplete with PHP source file that connects to MySQL and get the info to show as autocomplete on input field. Here's my code:
Index/Input
<script>
$(function() {
$("#search").autocomplete({
source: 'http://localhost/testes/autocomplete.php',
minLength: 3
});
});
</script>
<input type="text" id="search"/>
autocomplete PHP
$req = "SELECT DISTINCT name FROM faculty WHERE name LIKE '%".$_REQUEST['term']."%'";
$query = mysql_query($req);
while($row = mysql_fetch_array($query)){
$results[] = array('label' => $row['name']);
}
echo json_encode($results);
The problem is, it returns good values and other null values. But, in the last case, the values should not be null because they are in the database.
For example, in the database I have the entries:
ISCTE - Instituto Universitário
INDEG-ISCTE Business School
Searching by 'iscte' the autocomplete gives second one but the first one appear as null.
Thank you for you time,
Regards,
Hugo
That is because the encoding. Use this:
...
while($row = mysql_fetch_array($query)){
$results[] = array('label' => utf8_encode($row['name']));
}
...
Your database should set to UTF8, but by the way, this fix it.

Categories

Resources