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
Related
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)
})
})
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"
i return this json from my php page but jquery cannot decode it,result is always null.
{
"City": [
{
"CityID": "1",
"CityName": "istanbul"
},
{
"CityID": "2",
"CityName": "Ankara"
}
]
}
Jquery Code:
$.getJSON("handlers/cityhandler.php", function(json){
var result = jQuery.parseJSON(json);
console.log(result[0].City.CityID);
Jquery alternate code:
$.getJSON("handlers/cityhandler.php", function(json){
$.each(json, function(i,City){
$("#selectcity").append('<option value="' + City.CityID + '">' + City.CityName + '</option>');
});
console.log(json.City[0].CityID);
The data is already parsed when you receive it, you don't need to call $.parseJSON. Furthermore, the reason why you are getting a null pointer exception is because result[0] doesn't exist: result is an associative array, not a regular array.
$.getJSON("handlers/cityhandler.php", function(json){
console.log(json.City[0].CityID);
});
Your second attempt isn't right either; if you're trying to loop over the cities you must loop over the inner array:
$.getJSON("handlers/cityhandler.php", function(json){
$.each(json.City, function(i, val){
$("#selectcity").append('<option value="' + val.CityID + '">'
+ val.CityName + '</option>');
});
});
Your JSON output is valid JSON, so the issue is not coming from there. Are you sure that this is exactly what the jQuery handler receives?
Side note, result[0] doesn't exist! Your top element is an object and not an array!
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);
My jquery looks like this
var formContent ="action=view&msgid="+id;
$.getJSON("myserv.php",formContent, function(json){
$.each( json, function(k, v){`
alert( "Key: " + k + ", Value: " + v );`
});
});
in my php file i have an array that i json encode
while($message->fetch()) {
$arr[$i]["read"]=$message->test;
$arr[$i]["messageid"]=$message2->test2;
$arr[$i]["subject"]=$message2->test3;
$arr[$i]["text"]=$message2->test4;
}
$str=json_encode($arr);
return $str;
the alert returns Key:0 Value: [Object Object]
Any idea how I can get it to return the correct result? How can I display the results nicely in a div or span?
You are putting it all in a single cell array. And then in your callback, in jQuery, you are trying to loop through the array cell. I'm assuming you want to keep $arr an array (guessing you could have multiple 'read', 'subject', etc) so you should change your js to:
var formContent ="action=view&msgid="+id;
$.getJSON("myserv.php",formContent, function(json){
$.each(json, function(i){
$.each(json[i], function(k, v) {
alert( "Key: " + k + ", Value: " + v ); });
});
});
});
Or, if you don't want a single cell array, and will only return one 'read', 'subject etc, then change your PHP to:
if($message->fetch()) {
$arr["read"]=$message->test;
$arr["messageid"]=$message2->test2;
$arr["subject"]=$message2->test3;
$arr["text"]=$message2->test4;
$str=json_encode($arr);
}
else {
$str=json_encode(Array('error' => 'No message'));
}
return $str;