Loop through PHP associative array in javascript or jquery - javascript

I have the following PHP associative array output as a response to jquery post request:
Array
(
[0] => Array
(
[user] => 25
)
)
How can iterate through the above PHP associative array in javascript or jquery? Is this possible? or should I print the output of PHP in another way? I have access to the PHP as well

In PHP just echo using json_encode:
$array = array(array('user' => 25));
echo json_encode($array); // [{"user":25}]
In Jquery:
var data = $.parseJSON(jsonString); // '[{"user":25}]'
console.log(data[0].user); // 25

Here's what I use in a similar application:
PHP:
header("Content-Type: application/json");
if ( $_REQUEST["jsoncallback"] ) {
$callback = htmlentities( $_REQUEST["jsoncallback"] );
}
$output = json_encode( $array );
if ( $callback ) {
$output = $callback . "(" . $output . ")"; // I know the variables can be embedded in the strings, I don't care, I like it this way.
}
echo $output;
Javascript:
var getURL = "http://www.example.com/script.php?jsoncallback=?";
jQuery.ajax({
dataType: "json",
url: getURL,
success: function(data){
var obj = jQuery.parseJSON( data );
// now you can loop through the data object
}
});
For the looping part, this question/answer might be helpful: How to Loop through plain JavaScript object with objects as members?

Related

I have nested while loop php mysql. how to encode it to valid JSON

<?php
// header("Access-Control-Allow-Origin: *");
// header("Content-Type: application/json; charset=UTF-8");
require_once ('connection.php');
try {
$selectCatagory = 'select Catagory_id, Catagory_name, Catagory_image from district_shop.catagory';
$prepareCatagory = $conn -> prepare($selectCatagory);
$prepareCatagory ->execute(array());
while ($fetchCatagory = $prepareCatagory ->fetch(PDO::FETCH_ASSOC)) {
$Catagory = $fetchCatagory['Catagory_id'];
$selectSubCatagory = 'select * from district_shop.subcatagory where Catagory_id= :Cat_id';
$prepareSubCatagory = $conn -> prepare($selectSubCatagory);
$prepareSubCatagory -> execute(array(
'Cat_id' => $Catagory
));
while ($fetchSubCatagory = $prepareSubCatagory -> fetch(PDO::FETCH_ASSOC)) {
//print_r($fetchSubCatagory);
echo json_encode($fetchSubCatagory);
// It doesnot encoded to valid JSON
}
}
} catch (PDOException $th) {
$th-> errMessage();
}
?>
// The outpuut invalid JSON file is as :-
[{"Subcatogory_id":"1","Subcatagory_name":"Crasher Material","Subcatagory_description":"Crasher Material","Active_Subcatagory":"Active","Catagory_id":"1"},{"Subcatogory_id":"2","Subcatagory_name":"Plumbing Items","Subcatagory_description":"Plumbing Items","Active_Subcatagory":"Active","Catagory_id":"1"},{"Subcatogory_id":"3","Subcatagory_name":"Iron Material","Subcatagory_description":"Iron Material","Active_Subcatagory":"Active","Catagory_id":"1"},{"Subcatogory_id":"4","Subcatagory_name":"Cementing","Subcatagory_description":"Cement Material","Active_Subcatagory":"Active","Catagory_id":"1"},{"Subcatogory_id":"5","Subcatagory_name":"Marble & Tiles","Subcatagory_description":"Marble & Tiles","Active_Subcatagory":"Active","Catagory_id":"1"},{"Subcatogory_id":"6","Subcatagory_name":"Electric Material","Subcatagory_description":"Electric Material","Active_Subcatagory":"Active","Catagory_id":"1"}][{"Subcatogory_id":"7","Subcatagory_name":"Sweets ","Subcatagory_description":"Sweets ","Active_Subcatagory":"Active","Catagory_id":"2"},{"Subcatogory_id":"8","Subcatagory_name":"Salted(Namkeen)","Subcatagory_description":"Salted(Namkeen)","Active_Subcatagory":"Active","Catagory_id":"2"},{"Subcatogory_id":"9","Subcatagory_name":"Cold and Beverages","Subcatagory_description":"Cold and Beverages","Active_Subcatagory":"Active","Catagory_id":"2"},{"Subcatogory_id":"10","Subcatagory_name":"Food and Snacks","Subcatagory_description":"Food and Snacks","Active_Subcatagory":"Active","Catagory_id":"2"}]
Sir, I am unable to create its valid json as i have two tables in mySQL named catagory and subcatagory.
so nested while loop is used to extract subcatagory by using catagory. The output is encoded in json but it was no a valid JSON.
The problem is you're echoing multiple JSONs without nesting them properly. Instead of this:
[subcat1, subcat2, subcat3][subcat4, subcat5, subcat6] (invalid)
Your output should look like be one of these
[subcat1, subcat2, subcat3, subcat4, subcat5, subcat6] (valid flat array)
[[subcat1, subcat2, subcat3], [subcat4, subcat5, subcat6]] (valid nested arrays)
In your code, you should harvest responses into an array, which you echo json_encode() in the end.
...
$output = [];
while ($fetchCatagory ...) {
...
while ($fetchSubCatagory ...) {
// for nested array
$output[] = $fetchSubCatagory;
// for flat array
$output = array_merge($output, $fetchSubCatagory);
}
}
echo json_encode($output);
That should do the trick :-)

php ajax not returning expected result, possible json decode issue

Paste the following code into PHP.
$json = '[{"id":1,"quantity":1},{"id":2,"quantity":2},{"id":3,"quantity":3}]';
$json2 = json_decode($json);
foreach($json2 as $item){
$item->total = 9;
}
foreach($json2 as $item){
print_r($item);
echo "<br>";
}
echo json_encode($json2);
The above code will display the following result. I will call this the "expected result"
stdClass Object ( [id] => 1 [quantity] => 2 [total] => 9 )
stdClass Object ( [id] => 1 [quantity] => 2 [total] => 9 )
stdClass Object ( [id] => 1 [quantity] => 2 [total] => 9 )
[{"id":1,"quantity":2,"total":9},{"id":1,"quantity":2,"total":9},{"id":1,"quantity":2,"total":9}]
Now, Following the same logic. Paste java script below
function test(){
var json = [{"id":1,"quantity":1},{"id":2,"quantity":2},{"id":3,"quantity":3}];
$.ajax({
url: base_url+"Product/ajax_test",
type: "POST",
dataType: "JSON",
data: {
'json':json,
},
success:function(data){
console.log(data);
}//end success function
});//end of ajax
}
And paste the php below, I am using codeigniter frame work if this helps
public function ajax_test(){
$json = $this->input->post('json');
$json2 = json_decode($json);
foreach($json2 as $item){
$item->total = 2;
}
echo json_encode($json2);
}
I expect the above 2 piece of code to show something similar in the console as my "expected result", but nothing shows in the console. And if I change the above code to the following
public function ajax_test(){
$json = $this->input->post('json');
foreach($json as $item){
$item["total"] = 2;
}
echo json_encode($json);
}
The above code will show result in console. the "total" property is not in the final result as if it simply gave back the original $json variable. And it is also weird I need to use $item["total"] instead of $item->total.
Question 1, What did I do wrong on the above?
Question 2, Since PHP is stateless, is there a way for me to trouble shoot ajax, by echoing out the php page in the console without json encoding it?, if this make sense.
json_decode() can decode a JSON object as either an object or an array.
$json = '[{"id":1,"quantity":1},{"id":2,"quantity":2},{"id":3,"quantity":3}]';
$json_with_objects = json_decode($json);
$json_with_arrays = json_decode($json, true);
echo $json_with_objects[0]->quantity;
echo $json_with_arrays[0]["quantity"];
var_dump($json_with_objects);
var_dump($json_with_arrays);
Presumably, though we can't know since you don't provide it, your code $this->input->post() is decoding with associative arrays instead of objects.

PHP to JSON Array Output is Wrong

What I am trying to do doesn't feel difficult, but for some reason I can't seem to find the correct way to ouput this JSON array, from php.
PHP code:
$a = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
$i++;
$a = array();
$epoch = $row['time'];
$dt = new DateTime("#$epoch"); // convert UNIX timestamp to PHP DateTime
$a = array(
"time" => $dt->format('Y-m-d H:i:s'),
"signal" => $row['signal'],
"symbol" => $row['symbol'],
"price" => $row['price'],
"timeframe" => $row['timeframe'],
"epoch" => $row['time']);
echo json_encode($a, JSON_UNESCAPED_SLASHES);
}
Output:
{
"time":"2016-11-14 17:23:00",
"signal":"Sell",
"symbol":"XAUUSDecn",
"price":"1221.64000",
"timeframe":"M1",
"epoch":"1479144180"
}
{
"time":"2016-11-14 17:07:59",
"signal":"Sell",
"symbol":"GBPJPYecn",
"price":"135.13200",
"timeframe":"M1",
"epoch":"1479143279"
}
The correct output should have },{ NOT }{ between each object.
What I am ultimately trying to do:
function getTrades(a) {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "core/engine.php",
data: "q=data&account="+a,
dataType: "html", //expect html to be returned
success: function(response){
if(response=="nologin") {
alert("Sorry, but either your account is not activated or your login is incorrect!");
} else {
var j = $.parseJSON(response);
$.each(j, function (k, v) {
$("#trades").html('<span class="tradesignal"><!-- span class="signalarrowup"></span-->'+v.time+'<span style="color:#2DC14E;"> '+v.signal+'</span>   <button class="tsym" id="sym_'+v.epoch+'">'+v.symbol+'</button>  '+v.price+'  '+v.timeframe+'</span>');
});
}
//alert(response);
console.log(response);
}
});
}
Each {json},{json} object will have its data printed into a span on an html page.
Appreciate the guidance!
Try creating a results array and push each one of the objects there, then after the loop finishes, convert the array to json and print it.
example:
$results = array();
$i = 0;
while($row = mysqli_fetch_array($result)){
//your code here
$a = array("time" => ....);
$results[] = $a; //this will add $a to $results
}
echo json_encode($results, JSON_UNESCAPED_SLASHES);
Just to add a little more explanation in addition to the code the other answers are suggesting. The problem is, you aren't outputting a JSON array. Each time you do
echo json_encode($a, JSON_UNESCAPED_SLASHES);
inside your loop, you output a valid JSON object like:
{
"time":"2016-11-14 17:23:00",
"signal":"Sell",
"symbol":"XAUUSDecn",
"price":"1221.64000",
"timeframe":"M1",
"epoch":"1479144180"
}
However, when you output the subsequent objects, getting a result like
{
"time": ...
}
{
"time": ...
}
You no longer have valid JSON. Even though each of the individual objects is valid, concatenating them together isn't. Simply adding a comma between the objects will still not make it valid. In order to produce an actual JSON array, the comma separated objects will need to be enclosed in square brackets like this:
[
{
"time": ...
},
{
"time": ...
}
]
That's why you need to add each of the arrays you're creating in the loop to an outer array and then json_encode the whole thing after the loop. The outer PHP array will become the outer JSON array you need.
As Xorifelse said, you want to put the data in an array, and then call json_encode on the array. Here is a code that should work:
$a = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
$i++;
$epoch = $row['time'];
$dt = new DateTime("#$epoch"); // convert UNIX timestamp to PHP Date
$a[] = array("time" => $dt->format('Y-m-d H:i:s'), "signal" => $row['signal'], "symbol" => $row['symbol'], "price" => $row['price'], "timeframe" => $row['timeframe'],"epoch" => $row['time']);
}
echo json_encode($a, JSON_UNESCAPED_SLASHES);

Echoing a series of JSON data from php to JavaScript,

I am having a difficulty retrieving a series of json data from php to my JavaScript, file..
Firstly, I have a series of json data stored in an array in php, and echoing each by wrapping it in the for loop to my JavaScript file,
<?php
$result = array('{"one": "test","two": "test"}','{"three": "test","four": "test"}');
for ($i = 0; $i < count($result); ++$i) {
echo $result[$i];
}
?>
in my JavaScript,
$.ajax({
url: "visualiser/visualiser_RouteList.php",
dataType: "JSON",
async: false,
success: function(data){
console.log(data);
}
});
My console does not display anything at all, not recognizing each array element as a json..
but if I send just one array element specifically, for example,
echo $result[0];
then it successfully displays,
Object {one: "test", two: "test"}
why can't I pass a series of json data in an array from php in my ajax call?
It doesn't work because you are generated malformed JSON. The output of your script is
{"one": "test","two": "test"}{"three": "test","four": "test"}
When you access the first element of the array only you get
{"one": "test","two": "test"}
Which is valid.
PHP has json_encode which will do this work for you, so your code would become
$result = array(
array('one' => 'test', 'two' => 'test'),
array('three' => 'test', 'four' =>'test')
);
echo json_encode($result);
giving the output
[{"one":"test","two":"test"},{"three":"test","four":"test"}]
Your code will output this:
{"one": "test","two": "test"}{"three": "test","four": "test"}
This is invalid JSON, so obviously will not work. (Try parsing it with JSON.parse and you'll see.)
You actually need to send the data as an array, so replace your for loop with a simple json_encode call:
echo json_encode($result);
This will output
[{"one": "test","two": "test"},{"three": "test","four": "test"}]
This is valid JSON, and can be parsed into a Javascript array.
Also can you this script
function doj($json){
$result = json_encode($json);
return json_decode($result, true);
}
$json = array(
'{"one": "test","two": "test"}',
'{"three": "test","four": "test"}'
);
$j = doj($json);
foreach($j as $k=>$v){
$extractagain = json_decode($v);
print_r($extractagain);
}
and the output is:
stdClass Object ( [one] => test [two] => test ) stdClass Object ( [three] => test [four] => test )

Passing a JSON object from PHP to Javascript

I generate a json object inside my php file using json_encode but when I parse it in Javascript I get error unknow token which is because when I print the returned string it is actually html code not a json string.
let's consider the simplest case:
php:
$testjson = '{"result":true,"count":1}';
echo $testjson;
js:
$.get("serverside.php", function(data, status) {
JSON.parse(data); // I get error here
});
how should I use that JSON object from php in javascript?
It probably best you create your json array a bit more dynamically in php :
$testjson = array();
$testjson['result'] = true;
$testjson['count'] = 1;
echo json_encode($testjson);
What Tanantos said is you best bet. I personally would've write it like:
$testjson = array(
"result" => true,
"count" => 1
);
echo json_encode($testjson);
PHP :
$testjson = array(
"result" => true,
"count" => 1
);
echo json_encode($testjson);
js :
$.get('serverside.php', function(json){
console.log(json);
}, 'json');
jquery-1.10.2.min

Categories