foreach JSON array in jquery - php

I have an Array in the following format :
[["tag1","tag2","tag3","tag4","tag5","tag6","tag7","Thy","YUI"],["","",0,"jkghjg","hgjhg","kjhkjhg","kjghjkg)","gjhg","jkjkghj"]]
I need to "foreach" the array and get each values one by one like: Features , notes ...
When I put it into $.each() I am getting this error:
Uncaught TypeError: Cannot use 'in' operator to search for '1103' in ..
How do I get it?

did you mean make the array as associative JSON object?
try this
var a = [["Features", "Notes", "Code", "Value", "Testing", "BAC", "Total", "Thy", "YUI"],
["", "", 0, "jkghjg", "hgjhg", "kjhkjhg", "kjghjkg)", "gjhg", "jkjkghj"]]
var json = {}
for (var i in a[0]) {
var key = a[0][i];
var val = a[1][i];
json[key] = val;
}
console.log(json);
console.log(json.Testing);

var a_data= [["Features","Notes","Code","Value","Testing","BAC","Total","Thy","YUI"],["","",0,"jkghjg","hgjhg","kjhkjhg","kjghjkg)","gjhg","jkjkghj"]]
var output="";
$.each(a_data,function(index,data){
output+=data.join(",")
})
console.log(output)

try this
var a = [["Features", "Notes", "Code", "Value", "Testing", "BAC", "Total", "Thy", "YUI"], ["", "", 0, "jkghjg", "hgjhg", "kjhkjhg", "kjghjkg)", "gjhg", "jkjkghj"]]
$.each(a, function (i, data) {
$.each(data, function (j, val) {
console.log(val);
});
});
you can also try this if you want to use foreach method
Array.prototype.forEach.call(a,function(rm){
rm.map(function(ed){
console.log(ed)
})
})

Related

Json Returning [object object] instead of values

I am trying to extract the values ​​of a json but when I return it I get an object object.
Something I did wrong in decoding? this is the decoding code in php
<?php $contenido=file_get_contents("https://www.deperu.com/api/rest/cotizaciondolar.json");
$info = json_decode($contenido,true);
$cadena=array(
0=>$info['cotizacion'],
);
echo json_encode($cadena);
?>
this is the function code
<script>
$(function() {
$("#btnbuscar").on('click',function(){
var direccion='servicio.php';
$.ajax({
type:'get',
url:direccion,
success:function(datos){
var campo=eval(datos);
alert(datos[0]);
}
});
return false;
});
});
</script>
Uwhen you write this:
$cadena=array(
0=>$info['cotizacion'],
);
echo json_encode($cadena);
Your $info is an array, and cadena is an array, too. So you can direct point $cadenra to the array like this:
$cadena= $info['cotizacion'];
echo json_encode($cadena);
Or fix your js like this:
alert(datos[0][0]);
Here is a simple way to read your JSON without Ajax but with using $.getJSON
On your PHP file since you want to get only "cotization" data change: $cadena=array(0=>$info['cotizacion'] to $cadena=array(0=>$info['cotizacion'][0] and you can remove [0] if you are planning to have and to loop on multiple "cotizacion"
On your javascript use:
$.getJSON("servicio.php", function(data) {
var items = [];
$.each(data[0], function(key, val) {
(key + '=' + val);
});
});
There are several solutions, but don't get wrong in a javascript/jquery while calling a json chain.
For example:
<?php
// Page : service.php
$json = '{
"service": "Reference dollar exchange rate",
"website": "website.com",
"link": "https://www.website.com/gearbox_type/",
"quotation": [{
"buy": 3.419,
"sale": 3.424
}]
}';
// $json = file_get_contents("https://www.website.com/api/example.json");
$info = json_decode($json,true); // convert array
$cadena=array(
0=>$info['quotation'][0],
);
echo json_encode($cadena); // convert json
// get-> [{"buy":3.419,"sale":3.424}]
echo json_encode($cadena[0]); // convert json
// get-> {"buy":3.419,"sale":3.424}
?>
// Javascript
// To better use your function I would have to do a cleanup of the code with JSON.parse
<script>
$(function() {
/*
* Check yes and Json and convert json string
* Analyze the data with JSON.parse () and the data becomes a JavaScript object.
* Ex. var obj = '{hello:'mitico'}' -> convert object
* $.clean_string_json(obj) return-> {hello:'mitico'}
* $.clean_string_json('text' + obj) return-> {}
* $.clean_string_json('text' + obj,false) return-> false
* $.clean_string_json('text' + obj,true) return-> true
*/
$.clean_string_json = function (str,xreturn) {
try {
return JSON.parse(str);
} catch (e) {
return xreturn === false ? false : xreturn || {};
}
};
$("#btnbuscar").on('click',function(){
$.ajax({
type:'get',
url: 'service.php',
success:function(datos){
var campo= $.clean_string_json(datos);
alert(datos[0]); // return -> {"buy":3.419,"sale":3.424}
}
});
return false;
});
});
</script>
Welcome to stackoverflow! We hope you like it here.
As already pointed out by #Anurag Srivastava, call the url directly and you'll get json back, you do not need a proxy.
const jUrl = "https://www.deperu.com/api/rest/cotizaciondolar.json";
$.get(jUrl)
.then(({cotizacion}) => console.log(cotizacion));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Display JSON Data in HTML using Laravel 4

Please help me with my problem in displaying JSON data into my view..
my script is:
$('#supplierId').change(function(){
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data) {
var firstnameID = $('#firstnameID');
$.each(data, function(index, element) {
firstnameID.val(element.first_name);
});
});
});
and my JSON reply is:
{"id":7,"first_name":"John","last_name":"Doe"}
the thing is when i tried to:
alert(element.first_name);
it says UNDEFINED, but when I:
alert(element);
it gives me the value of the last name which is Doe.. my question is how can I then access the other values like the ID and the first name..
EDITED:
this is my route:
Route::get('api/dropdown', function(){
$input = Input::get('option');
$supllier = Supplier::find($input);
returnResponse::json($supllier->select(array('id','first_name','last_name'))
->find($input));
});
Please help me with this one, This is my first time using JSON so im a bit confuse on how this works.
Best Regards
-Melvn
Why are you using each? This should work:
$('#supplierId').change(function(){
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data) {
var firstnameID = $('#firstnameID');
firstnameID.val(data.first_name);
});
});
Ok, give this a try..
Explicitly state that what you're expecting back from the server is JSON using the dataType option in get().
$('#supplierId').change(function()
{
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data)
{
var firstnameID = $('#firstnameID');
$.each(data, function(index, element)
{
firstnameID.val(element.first_name);
});
},
'json' // <<< this is the dataType
);
});
Now you should be able to access the data using the dot syntax:
console.log("last_name: " + element.last_name);
console.log("first_name: " + element.first_name);
console.log("id: " + element.id);
I would add another few lines, just to check that you're getting back what you expect to see:
console.log("NEW ELEMENT"); // << indicator in the console for your reference
console.log(element); // << the whole "element"

Getting key => value from json array passed from php

I am trying to get an array from PHP and to manipulate it further using jQuery. In my PHP file i do echo json_encode($data) and when i put an alert in my response in jQuery i get:
[
{
"CustomerID": "C43242421",
"UserID": "432421421",
"Customer": "rqewrqwreeqwr",
"Add1": "rqwerqwreqwrqwrqwr",
"Add2": " ",
"Add3": " ",
"Phone": "4131231",
"Fax": "532442141",
"Contact": "reqwrqwrw",
"Email": "gfdgdsg",
"PaymentTerm": null,
"Country": "3231",
"City": "111",
"Zip": " "
}
]
, wich is a valid json array. Now what i try to do further is get the pairs as key => value as i would in an associative array in php.
$.post("templates/test.php",
{data: query,
cond: $(this).text(),
action: 'select'
},
function(res) {
alert(res) //outputs what i pasted above
$.each($.parseJSON(res), function(key, value) {
alert(key + value);
//this outputs: 0[object Object]
});
Removing the $.parseJSON in the above function gives me a invalid 'in' operand e on jquery.min.js(line 3) in Firebug error log.Can you assist me with my troubles?
Try:
var r = $.parseJSON(res);
$.each(r[0], function(key, value) {
alert(key + value);
});
The result of $.parseJSON(res) is an array, containing a single element (an object). When you iterate over that array (using $.each), value represents the entire object that's stored at the current index of the array. You'll need to iterate over that object to output its properties:
$.each($.parseJSON(res)[0], function(key, value) {
alert(key + ' = ' + value);
});
If you have an array with multiple objects inside it, this more general code should output the key-value pairs for all of them:
$.each($.parseJSON(res), function(index, arrayObject) {
$.each(arrayObject, function(key, value) {
alert(key + ' = ' + value);
});
});
res = $.parseJSON(res);
for (var i = 0; l = res.length; i < l; i++) {
data = res[i];
customer = data.Customer;
}
You have there an Array of Objects. You can iterate through the array of objects just like the code above.
You can get some kind of object from json:
function parse_json(res)
{
try{
return eval('(' + response + ')');
}
catch(e){
// invalid json
}
}
Try this:
$.getJSON('your-json-string-file.php', function (data) {
$.each(data, function(key, val) {
alert(key +'=>'+ val)
});
});
Hope this will help you

how to convert a JSon object to an array in Javascript

I am returning array as
$array = array {
'id' => 1,
'name'=>krishna,
}
echo json_encode($array);
exit;
from an ajax call
How can I convert this json value to java script array?
This is my actual data
var data = [{
"candidate_notes_id":"1",
"candidate_id":"38",
"subject":"test",
"description":"t‌estestsete\netestes\n\n\nsteetet",
"private":"0",
"created_date":"2012-09-14 11:55:13",
"updated_date":"2012-09-14 11:55:13",
"updated_by":"admin"
}]
var newArray = jQuery.parseJSON(data);
alert(newArray);
return false;
result :
var newArray = JSON.stringify(data);
var date_split = newArray.substr(1,newArray.length-2);
var newData = date_split.replace('\n','<br>');
var newArray = $.parseJSON(newData);
alert(newArray.candidate_notes_id);
alert(newArray.candidate_id);
alert(newArray.subject);
alert(newArray.description);
If you are using jQuery then you can use jQuery.parseJSON(YOUR_AJAX_RESPONSE_DATA); which will convert json to JS object
Link: http://api.jquery.com/jQuery.parseJSON/
Please look at an answered question ...
You will find how to convert a json to an array.
JSON to javaScript array
var array = [];
$.each(JSONObject, function(i, obj) {
array.push([obj.id.value, obj.name.value]);
});
You can parse it using
obj = JSON.parse(responseData); // replace `responseData` with your XHR response variable name
in your success callback function. Then convert it an array as follows
var myArray=[];
myArray[0]=obj.id;
myArray[1]=obj.name;
but first of all your
$array = array {
'id' => 1,
'name'=>krishna,
};
should be
$array = array (
'id' => 1,
'name'=>'krishna'
);
DEMO.

PHP JSON Highcharts load database result

I'm stuck!
I need to create highchart with json result. I found some sources here but can't put this to work.
The closest I can get was doing this:
Chart options:
var options = {
chart: {
renderTo: 'tudo',
defaultSeriesType: 'column',
rightMargin: 80
},
title: {
text: 'Weekdays'
},
subtitle: {
text: 'Source: somewhere in a calendar'
},
xAxis: {
labels: {
enabled: false
}
},
yAxis: [
{
min: 0,
title: {
text: 'Amount'
}
},
{
linkedTo: 0,
opposite: true
}
],
series: []
};
ajax call:
$.getJSON('ajax/calc.ajax.php', function(data) {
var series = [];
$.each(data, function(key, value) {
series.name = key;
series.data = value;
options.series.push(name);
});
var chart = new Highcharts.Chart(options);
});
highchart loads ok, and fills the series with Series 1, Series 2 ....
but no graphic is made, he keeps blank. ( something like this: Demo).
wanna know if I'm missing something or everything.
Thanks
update: i change the sql, now i'm working with 2 fields, and with this, the grafic work perfect, now i just want to know if doing like this its ok.
header('Content-Type: application/json');
while(!$res->EOF){
//$json = array("group" => "Web", "action" => "list");
$json[$res->fields["DESMAR"]] = array(intval($res->fields["QTD"]));
//$json["users"] = array(array("name" => "JulioGreff", "status" => "online"));
$res->MoveNext();
}
echo json_encode($json);
In your ajax call -
$.getJSON('ajax/calc.ajax.php', function(data) {
var series = []; // <---------------------- must be object not array
$.each(data, function(key, value) {
series.name = key;
series.data = value;
options.series.push(name); // <-------- it should be series not name
});
var chart = new Highcharts.Chart(options);
});
So, it would be as follows -
$.getJSON('ajax/calc.ajax.php', function(data) {
$.each(data, function(key, value) {
var series = {}; // <-------------------- moved and changed to object
series.name = key;
series.data = value;
options.series.push(series); // <-------- pushing series object
});
var chart = new Highcharts.Chart(options);
});
Also, considering the JSON you are receiving -
{"nome":"TRANSFORMADOR 250VA 0-230-380V / 0,24V-0-48V","modelo":"TRANSFORMADOR","marca":"SEIT","valor":"318.87|542.08","qtdade":"0"??}
what you are doing in the $.each -
series.data = value;
does not make sense.
series.data is an array. So, it could look like either as follows -
[y1, y2, y3, ....] // array of numbers (which are y values)
or as follows -
[[x1, y1], [x2, y2], [x3, y3], ....] // array of arrays of pair of numbers (x and y values)
or as follows -
// array of objects which can have x and y values as properties
[{
name: 'Point 1',
color: '#00FF00',
y: 0
}, {
name: 'Point 2',
color: '#FF00FF',
y: 5
}]
So, make sure that your PHP code produces a JSON that matches an array of one of the above, then series.data = value inside your $.each will work.
Update:
Sorry, I do Java and have never done PHP so can't help you much with PHP. But, can you try with the following as your PHP, just to see if the chart shows up?
header('Content-Type: application/json');
$return_data = array(
array(array(10, 20), array(20, 30), array(56, 30), array(50, 20)),
array(array(10, 0), array(20, 10), array(56, 100), array(50, 40))
);
echo json_encode($return_data);
Update: To render pie while keeping the same PHP.
$.getJSON('ajax/calc.ajax.php', function(data) {
var series = { // <-------------------- create just one series object
type: 'pie',
data: [] //data array for new series
};
$.each(data, function(key, value) {
series.data.push([key, value[0]]);
});
options.series.push(series); // <-------- pushing series object
var chart = new Highcharts.Chart(options);
});
This should draw pie chart.
It looks like the problem lies in your PHP code. Highcharts expects a series to follow a particular format. In your case, things work out (partly) because name is one of the field it is looking for. The data, however, needs to be in one of three formats:
An array of y values (e.g. [0, 1, 2])
An array of arrays (x, y values; e.g. [[0,0], [1,1], [2,2]])
An array of objects meeting using point properties
You would want the last format, I think. For example:
var series = [];
series.name = "series1";
series.data = {y: 10}; //very minimalistic example of the object format
options.series.push(name);
To get your code to work, you might need to change the inside of your $.each function to something like this:
$.each(data, function(key, value) {
series.name = key;
series.data = {
y: value.property_you_are_interested_in
};
options.series.push(name);
});
...of course, if you wanted to use one of the other forms, it would be pretty easy as well:
//First form (array of y values)
var series = {};
series.data = [];
$.each(data, function(key, value) {
series.name = key;
series.data.push(value.property_you_are_interested_in);
});
options.series.push(series);
//Second form (array of x, y values)
var series = {};
series.data = [];
$.each(data, function(key, value) {
series.name = key;
series.data.push([value.X_property_you_are_interested_in, value.Y_property_you_are_interested_in]);
});
options.series.push(series);

Categories