json_encode in php - php

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.

Related

json_encode for more than 2 arrays

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
}

Recover php mysql query with ajax/json?

How to recover data from research by json? I would like to recover the separate items as the result show in php page to create new elements, for example recover item.f, item.m to create new elements like item.f < / div> < span > item.m. .. thank you
(error presented at)
Error Can not read property of items " of null
Php page ( does the query )
if ($_GET['action'] == "chatheartbeat") { chatHeartbeat(); }
function chatHeartbeat() {
$sql = "select * from mensagens ";
$query = mysql_query($sql);
$items = '';
$chatBoxes = array();
while ($chat = mysql_fetch_array($query)) {
$items. = << < EOD
{
"s": "0",
"f": "{$chat['de']}",
"m": "{$chat['mensagem']}",
"i": "{$chat['img']}"
},
EOD;
}
}
Index ( calls the pair query present the results - error here - need help here)
$.ajax({
url: "asd.php?action=chatheartbeat",
cache: false,
dataType: "json",
success: function(data) {
$.each(data.items, function(i, item) {
alert(item.f)
});
}
});
As #jeroen says dont manually generate JSON Strings use json_encode() to create a JSONString from a PHP array or an object.
if ($_GET['action'] == "chatheartbeat") {
$sql = "select * from mensagens ";
$query = mysql_query($sql);
$chatBoxes = array();
while ($chat = mysql_fetch_array($query)) {
$t - new stdClass();
$t->s = "0";
$t->f = $chat['de'];
$t->m = $chat['mensagem'];
$t->i = $chat['img'];
$chatBoxes[] = $t;
}
$items = json_encode($chatBoxes);
// now just echo $items to return it to the javascript in the browser
// here or later in the code if there is more to your code than you showed us
echo $items;
}
References:
json_encode()
json_decode()
Thank you all for the help, I managed to solve the problem as follows
Php page ( does the query )
$result = mysql_query("SELECT * FROM mensagens");
while( $array = mysql_fetch_assoc($result)){
$table[]= array("de"=>$array['de'],"mensagem"=>$array['mensagem']); }
echo json_encode($table);
Index
$.ajax({
url: 'asd.php',
dataType: 'json',
success: function(data)
{
for($i=0; $i < data.length; $i++){
$("#chatbox_"+chatboxtitle+" .chatboxcontent").append(
'<div class="message"><span class="from">'+data[$i].de+':
</span><span class=content">'+data[$i].mensagem+'</span></div>');
}}
});

Get data value from php array with autocomplete jquery/ajax

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));

$.each() loop through json not looping

i have an ajax call that gets back json i am trying to send the items returned to specific input text id's.
This is the ajax:
$.ajax({
url: "php/myfirstfile.php",
type: "POST",
data: $("#frameroof").serialize(),
cache: false,
dataType: "json",
success: function (json) {
$.each(json, function () {
$.each(json, function (key, value) {
/// do stuff
$('#' + key ).val(value);
});
});
}
});
This is what is returned: [{"a-frame":"100"}][{"vertical":"350"}]
it looks im getting 2 arrays when i need one to loop over. Im not sure.
Here is the php
if(isset($_POST["cart"])){
$frameArray = ($_POST["cart"]);
if(is_array($frameArray)){
foreach($frameArray as $row){
$catalogue = $row['catalogue'];
$certification = $row['certification'];
$catagory = $row['catagory'];
$subcatagory = $row['subcatagory'];
$length = $row['length'] ;
$sql = "SELECT `price` AS '$subcatagory' FROM `products` WHERE `catalogue_id` = '$catalogue' AND `certification` = '$certification' AND `catagory` = '$catagory' AND `sub_catagory` = '$subcatagory' AND `length` = '$length' ";
$result = $short_connect->query($sql);
if (($result) && ($result->num_rows > 0)) {
$results = array();
//convert query result into an associative array
while ($row = $result->fetch_assoc()) {
$results[] = $row;
}
//dump all data from associative array converted from query result
echo (json_encode($results,true));
$result->free();
}
}
}
}
$short_connect->close();
I believe your problem is pretty simple. Inside of your loop you're initializing the results array and you're outputting it. This causes a new results array to be created, serialized to JSON, and outputted for every iteration of the loop. Thus what you're sending the browser is not JSON, but several chunks of JSON all run together.
This is the basic idea of what you need to be doing:
<?php
// Initialize the output data
$results = array();
foreach($something as $a_something) {
$results[] = do_something_to($a_something);
}
//Serialize and send the output data
echo (json_encode($results,true));
Rearranging your code with that pattern in mind produces this (which ought to work for you, and will return an empty array to the browser if your if conditions aren't met or the query doesn't return anything):
<?php
// Initialize the output data
$results = array();
if(isset($_POST["cart"])){
$frameArray = ($_POST["cart"]);
if(is_array($frameArray)){
foreach($frameArray as $row){
$catalogue = $row['catalogue'];
$certification = $row['certification'];
$catagory = $row['catagory'];
$subcatagory = $row['subcatagory'];
$length = $row['length'] ;
$sql = "SELECT `price` AS '$subcatagory' FROM `products` WHERE `catalogue_id` = '$catalogue' AND `certification` = '$certification' AND `catagory` = '$catagory' AND `sub_catagory` = '$subcatagory' AND `length` = '$length' ";
$result = $short_connect->query($sql);
if (($result) && ($result->num_rows > 0)) {
//convert query result into an associative array
while ($row = $result->fetch_assoc()) {
//Add to the output data
$results[] = $row;
}
$result->free();
}
}
}
}
$short_connect->close();
//Serialize and send the output data
//dump all data from associative array converted from query result
echo (json_encode($results,true));

Passing data back from php to ajax

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);

Categories