I try to use the plugin from "devbridge autocomplete" : https://www.devbridge.com/sourcery/components/jquery-autocomplete/
I would like to get 3 values from my search.php page (and not just 1).
It works for "value" but not for "data1" and "data2" (result for each = null)
My jQuery code :
$('#search-adress').autocomplete({
serviceUrl: 'search.php',
dataType: 'json',
onSelect: function (value,data1,data2) {
alert('You selected: ' + value + ', ' + data1 + ', ' + data2);
}
});
My search page :
$term=$_GET['query'];
$query = mysql_query("select distinct adress,id,city from myadresstable where (adress like '%{$term}%') order by adress limit 10 ");
if (mysql_num_rows($query))
{
while($row = mysql_fetch_assoc($query))
{
$reply['suggestions'][] = ''.utf8_encode($row['nom_voie']).'';
$reply['data1'][] = ''.utf8_encode($row['id']).'';
$reply['data2'][] = ''.utf8_encode($row['city']).'';
}
echo json_encode($reply);
}
Thank you for helping me :)
You can just change a bit the php array this way:
$term=$_GET['query'];
$query = mysql_query("select distinct adress,id,city from myadresstable where (adress like '%{$term}%') order by adress limit 10 ");
if (mysql_num_rows($query))
{
$arr = array();
while($row = mysql_fetch_assoc($query))
{
$reply['suggestions'] = utf8_encode($row['nom_voie']);
$reply['data'] = utf8_encode($row['id']);
$reply['value'] = utf8_encode($row['city']);
$arr[] = $reply;
}
echo json_encode($arr);
}
And in your jquery code:
$(function(){
$('#autocomplete').autocomplete({
lookup: datos,
onSelect: function (suggestion) {
console.log(suggestion);
alert('You selected: ' + suggestion.value + ', ' + suggestion.data + ', ' + suggestion.nom_voie);
}
});
});
Sample fiddle: https://jsfiddle.net/robertrozas/n6oLLfmc/
Try selecting "Valdivia" to see the alert
I found the solution :)
The problem was the PHP Array. To get some data values with this autocomplete plugin you have to use array() :
PHP Code
$suggestions = array();
if (mysql_num_rows($query))
{
while($row = mysql_fetch_assoc($query))
{
$mydata1='$row['data1']';
$mydata2='$row['data2']';
$nom_voie=''.utf8_encode($row['nom_voie']).'';
$suggestions[] = array(
"value" => $nom_mydata1,
"data" => $nom_mydata2
);
}
}
echo json_encode(array('suggestions' => $suggestions));
Related
I have 2 tables to be retrieved from database with 2 different queries and needs to be encoded in json and send to ajax.The issue is I am not able to pass 2 json's to ajax .
I have tried with echo json_encode(array($data1,$data2)); but it is not working.
//My php code
$query = $db->query("select * from table1 where valu1='".$value1."'");
while ($row = $query->fetch_assoc()) {
$data1['value1'] = $row['value1'];
$data1['value2'] = $row['value2'];
}
$query = $db->query("select * from table2 where value2='".$value2."' ");
while ($row = $query->fetch_assoc()) {
$data2['value2'] = $row['value2'];
$data2['value3'] = $row['value3'];
}
echo json_encode(array($data1,$data2));
//My AJAX code
$(document).ready(function(){
$('#Form').submit(function(e){
e.preventDefault(); // stops the form submission
$.ajax({
url:$(this).attr('action'), // action attribute of form to send the values
type:$(this).attr('method'), // method used in the form
data:$(this).serialize(), // data to be sent to php
dataType:"json",
success:function(data){
//main
alert(data.value1);
},
error:function(err){
alert(err);
}
});
});
});
Kindly help in solving this issue.Thanks in advance
In PHP:
echo json_encode(array($data1, $data2));
In AJAX:
var data1 = data[0];
var data2 = data[1];
$.each(data1, function() {
console.log(this.value1 + ',' + this.value2);
});
$.each(data2, function() {
console.log(this.value2 + ',' + this.value3);
});
EDIT:
After a whole year, I just noticed that the initial PHP code was wrong, because the loop for the sql result would overwrite each time the values of the array. So, the correct one is this:
$query = $db->query("select * from table1 where valu1='".$value1."'");
while ($row = $query->fetch_assoc()) {
$data1[] = array('value1' => $row['value1'], 'value2' => $row['value2']);
}
$query = $db->query("select * from table2 where value2='".$value2."' ");
while ($row = $query->fetch_assoc()) {
$data2[] = array('value2' => $row['value2'], 'value3' => $row['value3']);
}
echo json_encode(array($data1,$data2));
Your code is fine, you just have to handle the two arrays within your success function:
success: function(data){
var object1 = data[0];
var object2 = data[1];
// Do whatever you like to do with them
}
How can I pass data from a php of then rows back to ajax ?
PHP
$query = 'SELECT * FROM picture order by rand() LIMIT 10';
$result = mysql_query($query);
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$url[]=$rec['pic_location'];
$name[]=$rec['name'];
$age[]=$rec['age'];
$gender[]=$rec['gender'];
}
echo json_encode($url);
echo json_encode($name);
echo json_encode($age);
echo json_encode($gender);
Ajax
$(".goButton").click(function() {
var dir = $(this).attr("id");
var imId = $(".theImage").attr("id");
$.ajax({
url: "viewnew.php",
dataType: "json",
data: {
current_image: imId,
direction : dir
},
success: function(ret){
console.log(ret);
var arr = ret;
alert("first image url: " + arr[0][0] + ", second image url: " + arr[0][1]); // This code isnt working
alert("first image Name: " + arr[1][0] + ", second image name: " + arr[1][1]);
$(".theImage").attr("src", arr[0]);
if ('prev' == dir) {
imId ++;
} else {
imId --;
}
$("#theImage").attr("id", imId);
}
});
});
});
</script>
My question is how can I display the values here ? The Alert message is giving me "Undefined" ?
You can do something along these lines.
PHP
$query = 'SELECT * FROM picture order by rand() LIMIT 10';
$res = mysql_query($query);
$pictures = array();
while ($row = mysql_fetch_array($res)) {
$picture = array(
"pic_location" => $row['pic_location'],
"name" => $row['name'],
"age" => $row['age'],
"gender" => $row['gender']
);
$pictures[] = $picture;
}
echo json_encode($pictures);
JS
...
$.ajax({
...
dataType: "json",
...
success: function(pictures){
$.each(pictures, function(idx, picture){
// picture.pic_location
// picture.name
// picture.age
// picture.gender
});
}
});
...
You can't put multiple echo statements for the AJAX response:
echo json_encode($url);
echo json_encode($name);
echo json_encode($age);
echo json_encode($gender);
Join your arrays and send a single response:
$arr = $url + $name + $age + $gender;
echo json_encode($arr);
You can easily do this using a single Array:
$pics = array();
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$pics[$rec['id']]['url'] = $rec['pic_location'];
$pics[$rec['id']]['name']=$rec['name'];
$pics[$rec['id']]['age']=$rec['age'];
$pics[$rec['id']]['gender']=$rec['gender'];
}
echo json_encode($pics);
i have this code on the server side:
<?php
header('Content-Type: text/html; charset=utf-8');
require "../general.variables.php";
require "../functions_validation.php";
require "../functions_general.php";
require "../../db_con.php";
$keyword = mysql_real_escape_string($_POST["keyword"]);
$query = mysql_query("
SELECT user_id, user_fullname, user_area, user_city, user_quarter, user_tmb
FROM `migo_users`
WHERE (
user_fullname LIKE '%".$keyword."%' AND user_id NOT IN (".$superAdmins2string.")
)
ORDER BY tmb_set DESC, user_fname ASC
LIMIT 7;
");
$i = 0;
while ($userInfo = mysql_fetch_array($query)) {
$area_name = mysql_fetch_array(mysql_query("
SELECT area_name
FROM `migo_areas`
WHERE
area_id='".$userInfo['user_area']."';
"));
$city_name = mysql_fetch_array(mysql_query("
SELECT city_name
FROM `migo_cities`
WHERE
city_id='".$userInfo['user_city']."';
"));
if ($userInfo['user_quarter'] != 0) {
$quarter_name = mysql_fetch_array(mysql_query("
SELECT quarter_name
FROM `migo_quarters`
WHERE
quarter_id='".$userInfo['user_quarter']."';
"));
}
else {
$quarter_name['quarter_name'] = "";
}
$rsl[$i]['user_id'] = $userInfo['user_id'];
$rsl[$i]['user_fullname'] = $userInfo['user_fullname'];
$rsl[$i]['user_area_name'] = $area_name['area_name'];
$rsl[$i]['user_city_name'] = $city_name['city_name'];
$rsl[$i]['user_quarter_name'] = $quarter_name['quarter_name'];
$rsl[$i]['user_tmb'] = $userInfo['user_tmb'];
$i++;
}
echo json_encode($rsl);
mysql_close();
?>
and this code on the client side:
$.ajax({
type : 'POST',
url : 'php/general.ajax/header_search.php',
//async : false,
//cache : false,
dataType : 'json',
data: {
keyword : sb_keyword
},
success : function(data) {
var hs_hits = 0;
var hs_row_nr = 1;
var hs_results = "<div class='sb_spacing'></div><div id='sb_rows_cont'>";
if (data != null) {
$.each(data, function(index, arr) {
hs_hits++;
if (arr['user_quarter_name'] != "") {
var quarter_text = " - " + arr['user_quarter_name'];
}
else {
var quarter_text = "";
}
hs_results = hs_results + "<a class='search_links' href=profile.php?id=" + arr['user_id'] + "><div class='sbr_row' row_nr='" + hs_row_nr + "'><div class='sbr_imgFrame'><img src='images/user_48x48/" + arr['user_tmb'] + "' alt=''></div><div class='sbr_name'>" + arr['user_fullname'].replace(regexp_hs_user_fullname, '<span>$&</span>') + "</div><div class='sbr_area'>" + arr['user_area_name'] + "</div><div class='sbr_area'>" + arr['user_city_name'] + quarter_text + "</div></div></a>";
hs_row_nr++;
});
}
if (hs_hits > 0) {
hs_results = hs_results + "</div><div class='sb_spacing'></div><a class='search_links' href='search.php?name=" + sb_keyword + "'><div id='sbr_botttom'>Se flere resultater for <span class='gay'>" + sb_keyword + "</span></div></a>";
$("#sb_results").html(hs_results).show();
searchSet = 1;
total_rows = hs_hits;
$("#sb_rows_cont > a:first .sbr_row").addClass('sbr_row_act');
on_a = $("#sb_rows_cont > a:first");
first_a = on_a;
last_a = $("#sb_rows_cont > a:last");
sb_url = $(on_a).attr('href');
search_navigator_init();
}
else {
$("#sb_results").hide();
searchSet = 0;
}
},
error : function() {
alert("ajax error");
}
});
one problem tho, if the query gives 0 results, and the each function tries to run on the client side my js code stops working..
so i was wondering what i could do here.
how can i retrieve the amount of hits from the server side, before i run the each loop?
You're instantiating $rsl in the middle of a loop (implicitly), but you aren't entering the loop unless you have at least one entry.
Instantiate $rsl up above your while loop:
...
$i = 0;
$rsl = array();
while ($userInfo = mysql_fetch_array($query)) {
...
And now when you encode it, it is an empty array instead of null. This will also save your HTTP error_log, and generally be happier. : )
I would try json_encode() your PHP array to allow JavaScript to eval it as a native JS object.
echo json_encode($some_array);
Just a note, json_encode() is only available for PHP versions 5.2 and higher.
$.getJSON('ajax.php',{form data}, functon(data){
if(data == '') return;
});
i have this script and it works, but not as i expected. I need to assign an array of values with differents names, now all $arr[] are named "valor"
{"valor":"20"},{"valor":"50"}
i need
{"valor1":"20"},{"valor2":"50"}
the script
$query = mysql_query("SELECT valor FROM grafico") or die(mysql_error());
$arr = array();
while($row = mysql_fetch_assoc($query)) {
$arr[] = $row;
}
echo json_encode($arr);
in ajax
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("button").click(function(){
jQuery.ajax({
url: "chart.php",
dataType: "json",
success: function(json){
var msg = "Nome: " + json.valor1+ "\n";
msg += "Sobrenome: " + json.valor2 + "\n";
alert(msg);
}
});
});
});
</script>
the problem is: I need to create a loop that create uniques names, as value1, value2, value3
like
$arr['valor1'] = "Evandro";
i tried a loop- for, but i get an error of memory
thanks
Try this:
$query = mysql_query("SELECT valor FROM grafico") or die(mysql_error());
$arr = array();
$i = 1;
while($row = mysql_fetch_assoc($query)) {
$arr[] = array("valor{$i}" => $row["valor"]);
++$i;
}
echo json_encode($arr);
Should work. Alternatively if you want to make it so it works with current callback change the $arr[] = line to the following:
$arr["valor{$i}"] = $row["valor"];
$index = 1;
while($row = mysql_fetch_assoc($query)) {
$key = 'valor'.index;
$arr[$key] = $row;
$index++;
}
Does that give you a memory error? It shouldn't.
My Jquery code
function nalozi() {
var id_skupine = $('#skupina option:selected').val();
$('#artikel option').remove();
//$('#artikel').append('<option value="'+id_skupine+'">'+id_skupine+'</option>');
$.getJSON('artikli.php', {id_skupine:$('#skupina').val()}, function(data) {
$.each(data, function(index,item) {
$("#artikel").append("<option value=" + item.id + ">" + item.ime_artikla + "</option>");
});
});
}
$(document).ready(function() {
nalozi();
$('#skupina').change(function() {
nalozi();
});
});
AND PHP CODE
<?php
if(isset($_GET['id_skupine']))
{
$id_skupine = $_GET['id_skupine'];
$poizvedba = mysql_query("SELECT id,ime_artikla FROM artikli WHERE id_skupine = '$id_skupine'");
$velikost = mysql_num_rows($poizvedba);
for ($i=0;$i<$velikost;$i++)
{
$elements[]=mysql_fetch_assoc($poizvedba);
}
}
echo json_encode($elements);
?>
I don't get the values back.
Update:
You should never put variable before sanitalizing/validating/type-converting into your sql queries. If your the value you expect in query string is a number, you need to properly type-cast it like this:
$id_skupine = (int) $_GET['id_skupine'];
And if it is a string, the least you can do is to use mysql_real_escape_string function:
$str = mysql_real_escape_string($_GET['str']);
Shouldn't you be grabbing the records from db like this:
if(isset($_GET['id_skupine']))
{
$id_skupine = $_GET['id_skupine'];
$poizvedba = mysql_query("SELECT id,ime_artikla FROM artikli WHERE id_skupine = '$id_skupine'");
$velikost = mysql_num_rows($poizvedba);
while($row = mysql_fetch_assoc($poizvedba)){
$elements[] = $row['ime_artikla'];
}
}
echo json_encode($elements);
Might be your query is not returning anything
$poizvedba = mysql_query("SELECT id,ime_artikla FROM artikli WHERE id_skupine = '$id_skupine'");
Remove single quote from '$id_skupine'
Try
$poizvedba = mysql_query("SELECT id,ime_artikla FROM artikli WHERE id_skupine = '".$id_skupine."'");