get data from two array with jquery from php json encode - php

I am newbie in this thing, i have searched on internet but not work for me, maybe someone can give me solution to get data from two array from json encode
<?php
session_start();
include "config.php";
$viewEO;
$viewAcara;
$ideve=mysql_real_escape_string($_GET["id"]);
$mysql = ("SELECT id_eo,nama as namaEO,logo,deskripsi as DeskEO,email,telp from eventorg WHERE id_eo='$ideve'");
$result=mysql_query($mysql);
if (!empty($result))
{
while ($row=mysql_fetch_array($result))
{
$viewEO[] = array(
'idEO' => $row['id_eo'],
'namaeo' => $row['namaEO'],
'deskripsieo' => $row['DeskEO'],
'email' => $row['email'],
'telpon' => $row['telp'],
'logoeo' => $row['Logo']
);
}
}
$mysql2 = ("SELECT id_acara,nama,tanggal,endtanggal,lokasi,imagePath,deskripsi,id_eo from acara WHERE id_eo='$ideve'");
$result2=mysql_query($mysql2);
if (!empty($result2))
{
while ($row2=mysql_fetch_array($result2))
{
$viewAcara[] = array(
'idacara' => $row2['id_acara'],
'namaacara' => $row2['nama'],
'deskripsi' => $row2['deskripsi'],
'tanggal' => $row2['tanggal']
);
}
}
mysql_close($con);
$final = array('array1'=>$viewEO, 'array2'=>$viewAcara);
header('Content-Type: application/json');
echo json_encode($final);
?>
and this is my html code
var arrEOS=new Array();
$.ajax({
url: 'phpmobile/viewdetaileo.php',
data: { "id": tempideo},
dataType: 'json',
success: function(data){
$.each(data, function(i,item){
if (arrEOS.indexOf(item.ideo)<0)
{
$('#daftaracara').append('<li data-role="list-divider" >'+item.tanggal+'</li><li><a onclick="detailAcara('+item.idacara+')"><h2>'+item.nama+'</h2><p><strong>'+item.deskripsi+'</strong></p><p>'+item.lokasi+'</p></a></li>');
arrEOS.push(item.idacara);
}
$('ul').listview('refresh');
$("#img1").html('<img id="img1" src="web/'+item.logoeo+'">');
$("#namaeo").html(item.namaeo);
$("#deskEO").html(item.deskripsieo);
$("#telpon").html(item.telpeo);
$("#email").html(item.emaileo);
});
},
error: function(){
//output.text('There was an error loading the data.');
}
});
Thank you before, Have a nice day :)

The json data you send from the php is $final = array('array1'=>$viewEO, 'array2'=>$viewAcara); your looping is wrong.
This can be done in many idea what I am suggesting is, try to use two new loops with in ajax success
$.each(data.array1, function(i,item){
//do the operations you want to perform with these vaules
console.log(item.idacara);
console.log(item.namaacara);
console.log(item.deskripsi);
console.log(item.tanggal);
}
and
$.each(data.array2, function(i,item){
//do the operations you want to perform with these vaules
console.log(item.logoeo);
console.log(item.idEO);
console.log(item.namaeo);
console.log(item.deskripsieo);
console.log(item.email);
}

Try this if you only have two array exactly,
$.each(data, function(i,item){
if(i == "array1"){
//for array1
console.log(item[0].idEo);
}
else{
//for array2
console.log(item[0].idacara)
}

Related

Parse JSON in JQuery and set in inputs

I'm implementing a web and I need to use AJAX+JQuery to complete some fields without recharging the page. I test it and it works correctly but when I tried to use a real JSON (created by MySQL) I'm not be able to parse it.
The format of JSON is this:
[
{
"ID":"5847"
},
{
"Usuari":"admin"
},
{
"Nom":"admin"
},
{
"Cognom1":null
},
{
"Cognom2":null
},
{
"Tipus":"admin"
},
{
"Progres":"0"
}
]
And the AJAX code is this:
$(document).ready(function(){
$("#botoBuscar").click(function(){
$.ajax({url: "http://192.168.1.39/web/api/buscarUser.php?user="+ $("#userInput").val(), success: function(data){
var obj = $.parseJSON(data);
$("#id").val(obj[0]['ID']);
$("#user").val(obj[0]['Usuari']);
$("#nom").val(obj[0]['Nom']);
$("#cognom1").val(obj[0]['Cognom1']);
$("#cognom2").val(obj[0]['Cognom2']);
$("#tipus").val(obj[0]['Tipus']);
$("#progres").val(obj[0]['Progres']);
}});
});
});
If I print only the var "data", it prints correctly the full JSON, but if I try to use data['ID'] or data[0]['ID'], etc.. it doesn't print anything. What I'm doing wrong? Thanks!
If you need, the code to generate JSON is this (PHP):
$sql = "SELECT id, user, nom, cognom1, cognom2, tipus, progres FROM users WHERE user='".$_GET['user']."'";
$result = $db->query($sql);
$row = $result->fetch_array(MYSQLI_ASSOC);
$id = $row['id'];
$user = $row['user'];
$nom = $row['nom'];
$c1 = $row['cognom1'];
$c2 = $row['cognom2'];
$tipus = $row['tipus'];
$progres = $row['progres'];
//build the JSON array for return
$json = array(array('ID' => $id),
array('Usuari' => $user),
array('Nom' => $nom),
array('Cognom1' => $c1),
array('Cognom2' => $c2),
array('Tipus' => $tipus),
array('Progres' => $progres));
echo json_encode($json);
mysqli_close($db);
Thanks!
I found the solution to get the values correctly. The code is the following one:
$(document).ready(function(){
$("#botoBuscar").click(function(){
$.ajax({url: "http://XX.com/api/buscarUser.php?user="+ $("#userInput").val(), success: function(data){
var obj = $.parseJSON(data);
$("#id").val(obj[0]['ID']);
$("#user").val(obj[1]['Usuari']);
$("#nom").val(obj[2]['Nom']);
$("#cognom1").val(obj[3]['Cognom1']);
$("#cognom2").val(obj[4]['Cognom2']);
$("#tipus").val(obj[5]['Tipus']);
$("#progres").val(obj[6]['Progres']);
}});
});
});

Undefined Variable in Ajax from PHP

I have tried different ways to make this work but it is still not working. data[0].urgency is undefined. I tried to stringify data but a bunch of \n in between the result (see below).
Thank you in advance.
My ajax code:
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
console.log(data.length);
console.log(data[0].urgency);
}
});
}
My PHP code:
<?php
session_start();
ob_start();
require_once('../../mysqlConnector/mysql_connect.php');
$results = array();
$query="SELECT COUNT(initID) AS count, urgency, crime, initID, TIMESTAMPDIFF( minute,dateanalyzed,NOW()) AS minuteDiff FROM initialanalysis WHERE commanderR='0' AND stationID='{$_SESSION['stationID']}';";
$result=mysqli_query($dbc,$query);
while ($row = $result->fetch_assoc()){
$count = $row['count'];
$urgency = $row['urgency'];
$crime = $row['crime'];
$initID = $row['initID'];
$minuteDiff = $row['minuteDiff'];
$results[] = array("count" => $count, "urgency" => $urgency, "crime" => $crime, "initID" => $initID, "minuteDiff" => $minuteDiff);
}
echo json_encode($results);
?>
Result of PHP:
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4743"}]
I think the result is in wrong format? I'm not sure.
This is the result of console.log(data), there is a comment tag of html and I don't know why:
<!-- -->
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4761"}]
Use a JSON parser for validate the json response like JSON.parse
function ValidateJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
Update your ajax call like this
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
data= jQuery.parseJSON(data);
console.log(data.length);
console.log(data[0].urgency);
}
});
}

AJAX it's not receiving the data back from the php file

I'm trying to send some values ​​through ajax and after being treated in the test.php, send the data back to be used.
The database part is correct. My problem is in the re-sending of the data:
The Json coding part does not give error, but when I try to check the data, many of them do not appear.
I think this can be caused by:
The way I am resending the data;
The way I encode Json.
My code.
ajax main.php:
$('#filtro_limit1').val(num_Limite_rows);
$.ajax({
url: teste.php,
type:'post',
data:
{
limite: num_Limite_rows,
tipologia: tipologia_val,
ordenar_por: ordenar_por_val
},
success: function(data, num_rows, num_actual_rows, mensagem_erro)
{
}
});
PHP teste.php:
if(pg_num_rows($result1) > 0)
{
$data = array[];
$data = $result1;
$out = array_values($data);
echo json_encode($out);
echo pg_num_rows($result1);
echo $filtro_limit;
echo "Não existem erros";
}
else
{
$data = array[];
echo json_encode($data);
$numero_rows = 0;
echo $total_rows;
echo $filtro_limit;
echo "Não existem valores a serem mostrados";
}
Please some help needed. Thank you for the future help.
Your success function is wrong. The parameter data will contain all the output of your php script. You can't automatically split the output by using different parameters in the function definition.
function success(data, textStatus, jgXHR) {
console.log(data);
}
Check your console and you'll see your data.
You'll probably want to change your php code:
$result = [
'out' => json_encode($out),
'result1' => pg_num_rows($result1),
'filtro_limit' => $filtro_limit,
'message' => "Não existem erros",
]
echo json_encode($result);
exit;
and
$result = [
'total_rows' => $total_rows,
'filtro_limit' => $filtro_limit,
'message' => "Não existem valores a serem mostrados",
];
echo json_encode($result);
exit;
That way, you'll have a much easier time to parse the data in JavaScript. For example:
function success(data, textStatus, jgXHR) {
var message = data.message;
}
you have to return all data in one statement in php like this :
echo json_encode(array(
'out'=>$out,
'num_rows'=>pg_num_rows($result1),
'filtro_limit'=>$filtro_limit,
'msg'=>"Não existem valores a serem mostrados"
));
and ajax code like this:
$('#filtro_limit1').val(num_Limite_rows);
$.ajax({
url: 'teste.php',
type:'post',
dataType: 'json',
data:
{
limite: num_Limite_rows,
tipologia: tipologia_val,
ordenar_por: ordenar_por_val
},
success: function(data)
{
$num_rows=data['num_rows'];
}
});

jquery ajax not parsing json data from php

I'm facing a strange problem for the last 10 hours and its really very annoying. The problem is with jquery printing json data from php. The php script is running fine, but when the ajax call returns in complete: event i'm not getting any valid otput.
here is the jquery code::
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST',
dataType: 'json',
complete: function(data) {
console.log(data['message']['Album_Name']);
}
});
return false;
});
});
i had to use complete: event as success: didn't worked at all. Atleast i'm getting some sort of output from the complete: event, although its giving undefined or [object][Object] which is totally ridiculous.
here is the retrieveFileFront.php:
<?php
require './retrieveFiles.php';
$type = $_POST['type'];
$nav_text = $_POST['navtext'];
$ret_files = new retrieveFiles($type, $nav_text);
$data = $ret_files->retFiles();
if ($data['success'] == FALSE) {
$data = array('success' => FALSE, 'message' => 'Sorry an Error has occured');
echo json_encode($data);
} else {
echo json_encode($data);
}
?>
and here is the /retrieveFiles.php
<?php
class retrieveFiles {
public $content_type;
public $list_nav;
public $connection;
public $result;
public $result_obj;
public $tags_array;
public $query;
public $row;
public function __construct($type, $nav_text) {
$this->content_type = $type;
$this->list_nav = $nav_text;
}
public function retFiles() {
#$this->connection = new mysqli('localhost', 'usr', 'pass', 'data');
if(!$this->connection) {
die("Sorry Database connection could not be made please try again later. Sorry for the inconvenience..");
}
if ($this->content_type == "Artists") {
$this->query = "SELECT album_name, album_art FROM album_dummy NATURAL JOIN album_images_dummy WHERE artist_name LIKE '$this->list_nav%'";
try {
$this->result = $this->connection->query($this->query);
$this->row = $this->result->fetch_row();
if (isset($this->row[0]) && isset($this->row[1])) {
$this->tags_array = array("success" => true, "message" => array("Album_Name" => $this->row[0], "Album_Art" => $this->row[1]));
return $this->tags_array;
}
} catch (Exception $e) {
echo 'Sorry an Error has occurred'.$e;
return false;
}
}
}
}
?>
I'm getting a 200 response in console in firebug, which indicates that its running okay.
<!DOCTYPE HTML>
{"success":true,"message":{"Album_Name":"Streetcleaner","Album_Art":"\/var\/www\/html\/MusicLibrary\/Musics\/1989 - Streetcleaner\/folder.jpg"}}
Now this is making me even more confused as i can see that the json is formatted properly. Please provide any sort of suggestion on how to solve this problem.
Thanks in advance..
JSON encoded data is usually not sent like
data['message']['Album_Name']);
But rather like:
data.message.Album_Name;
You're calling your results the wrong way. These are not associative arrays anymore but are now objects, as the name JSON (JavaScript Object Notation) suggests.
You need to parse the json response using
data = $.parseJSON(data)
Use success event instead of complete in ajax and we can able to parse JSON encoded data in javascript/jQuery by using JSON.parse
well after a long period of trauma, i finally found a solution, turns out that i needed to parse the response text and then access the objects, individually.
Here is the working code
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$('#loading').css('visibility', 'visible');
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST'
dataType: 'json',
complete: function(data) {
var res = data.responseText;
res = res.replace(/<!DOCTYPE HTML>/g, "");
res = res.trim();
console.log(res);
var arr = JSON.parse("[" + res +"]"); //needed to parse JSON object into arrays
console.log(arr[0].message.Album_Name);
console.log(arr[0].message.Album_Art);
$('#loading').css('visibility','hidden');
}
});
return false;
});
This works fine and gives the desired response. Anyways thanks for the help, guys.

undefined error with ajaxcall to receive json data

my problem is that I
can not solve this problem
If I call the php script, all I get is an undefined error
this is the code I use for testing AND
this is the original code from the creator that is giving me a headache
function startJsonSession(){
$.ajax({ url: "jsontest.php?action=startjson",
cache: false,
dataType: "json",
complete: function(data) {
username = data.username;
alert(username);
}
});
}
//phpscript
if ($_GET['action'] == "startjson") { startJson(); }
function startJson() {
header('Content-type: application/json');
$items = '';
echo json_encode(array(
"username" => "bob",
"items" => array( "item1" => "sandwich",
"item2" => "applejuice"
)
));
}
thanks, Richard
edited my question because:
this function returns the json data in a different way
and therefore the solution presented below, does not have the same outcome.
function startChatSession() {
$items = '';
if (!empty($_SESSION['openChatBoxes'])) {
foreach ($_SESSION['openChatBoxes'] as $chatbox => $void) {
$items .= chatBoxSession($chatbox);
}
}
if ($items != '') {
$items = substr($items, 0, -1);
}
header('Content-type: application/json');
?>
{
"username": "<?php echo $_SESSION['username'];?>",
"items": [
<?php echo $items;?>
]
}
<?php
exit(0);
}
I recreated with your code and figured it out. The object being returned is of type XMLHttpRequest. Its got a property called responseText holding a json string with the data.
so this works..
var decodedData = eval("(" + data.responseText + ")");
username = decodedData.username;
alert(username);
A bit messy but it does the trick :-)
p.s If it helps, I figured it out using firebug in firefox and sticking a breakpoint in the js code
Edited below:
Without wanting to do the eval, you could use this and it works:
$.getJSON("json.php?action=startjson",
function(data) {
username = data.username;
alert(username);
}
);
Edited to show what I did with the success function:
$.ajax({
url: "json.php?action=startjson",
cache: false,
dataType: "json",
success: function(data) {
username = data.username;
alert(username);
}
});
Is username a global variable?
If not you should prepend the "var" keyword.
username = data.username -> var username = data.username;
At the end I got it working.
I installed firebug and saw that the php script was returning html headers instead off json.
All off the sudden it started working, I really would like to know what the problem was, but I can't tell you.
Anyway, thanks for sticking so long, David
also what I don't understand is that it breaks out off php mode, instead of echoing it back like it's done with xml
?>
{
"username": "<?php echo $_SESSION['username'];?>",
"items": [
<?php echo $items;?>
]
}
<?php
is this the same as above (object array containing literal array)?
echo json_encode(array(
"username" => "bob",
"items" => $items
)
));
}

Categories