How do you access base object Array in a JavaScript Array? - javascript

I'm only posting relevant code here. I'm trying to access an array in a json array. How do I access an array inside an array?
So this is the code serverside :
$scriptfull = array();
while($r = mysqli_fetch_assoc($resultstmt_scriptfull)) {
$scriptfull[] = $r;
}
$resulterr = array('message' => 'Success',
'fullscript'=>$scriptfull);
header('Content-Type: application/json');
echo json_encode($resulterr);
I know how to access JSON array in Javascript. The problem I do not know how to access a base object that is itself an array within a JSON array.
When I do :
success: function(output)
{
console.log(output.fullscript);
}
I see result in console
(1)[...]
0:{...}
scriptAA1: "a1"
scriptAA10: "a10"
​​ scriptAA2: "a2"
​ scriptAA3: "a3"
But nothing prints in the HTML if I try
success: function(output)
{
$('.scriptview').html(output.fullscript);
}
I tried accessing it using below code but nothing prints:
success: function(output)
{
$('.scriptview').html(output.fullscript[1]);
}

What you are doing is trying to print a javascript array of objects at html which of course does not make sense and that why nothing is printed. You can either print the javascript array as a string (which probably is not what you want) like this:
$('.scriptview').html(JSON.stringify(output.fullscript));
I think you should explain better what exactly you are trying to print to html.
Edit:
As I understood you want something like what you are getting in your console. For something like this, the code below will do:
var outputString = '';
output.fullscript.forEach(function(object, index){
outputString += '<br> Object with index: ' + index + '<br>';
for (var prop in object){
outputString += 'Property ' + prop + ': ' + object[prop] + '<br>';
}
});
$('.scriptview').html(outputString);

Since you are trying to output the result as a string, you can use
success: function(output)
{
$('.scriptview').html(JSON.stringify(output.fullscript));
}
Update1
If you want the result formatted with whitespaces, the 3rd argument of the stringify method does that:
success: function(output)
{
$('.scriptview').html(JSON.stringify(output.fullscript, null, '\t'));
}
Update2
A more shorter, readable and efficient way is to just display using the jQuery text method instead of html:
success: function(output)
{
$('.scriptview').text(JSON.stringify(output.fullscript, null, '\t'));
}
This looks more tidy...

Related

".replace() is not a function" when trying to use inside ajax success

This is what I'm doing:
function AddSupervisor()
{
var employeeID = $('#ID').val();
var supervisorId = $('#SupervisorId').val();
var supervisors = '';
if (supervisorId > 0)
{
$.ajax({
url: '#Url.Action("AddSupervisor", "Contact")',
type: 'GET',
dataType: 'json',
data: { EmployeeID: employeeID, SupervisorID: supervisorId },
success: function(data) {
supervisors = data;
$('#divSupervisorList').text(supervisors.replace(",", "<br />"));
},
error: function(data) {
}
});
}
}
This is the error:
Uncaught TypeError: supervisors.replace is not a function
If I do this:
$('#divSupervisorList').text(data);
The the result on screen is this:
John Foo, Jane Bar
What I want is:
John Foo
Jane Bar
But I'm having trouble replacing the , with a <br />. At first I tried:
$('#divSupervisorList').text(data.replace(",", "<br />"));
And when that didn't work, I went to using a string that is declared before the ajax call. I also tried using .split() but got the same error.
Not sure what I'm doing wrong.
UPDATE:
As many have pointed out, my return data is not a string, but an object:
(4) ["Adam Brown", "Karl Walser", "Jeremy Smith", "Nathan Graham"]
0 : "Adam Brown"
1 : "Karl Walser"
2 : "Jeremy Smith"
3 : "Nathan Graham"
So, now I gotta figure out how to split this array into a string :-)
My guess is that the data param is actually an array, not a string, and you're seeing it with commas only because JS is sneakily stringifying it that way. You could combine them in a string using the join method for arrays:
supervisors.join('<br />')
However, if you try to use "<br />" in jQuery's text function, it will get escaped. You can use the html function instead. So,
$('#divSupervisorList').html(supervisors.join('<br />'));
The data you are having in response is a Json and not a string.
function AddSupervisor()
{
var employeeID = $('#ID').val();
var supervisorId = $('#SupervisorId').val();
var supervisors = '';
if (supervisorId > 0)
{
$.ajax({
url: '#Url.Action("AddSupervisor", "Contact")',
type: 'GET',
dataType: 'json',
data: { EmployeeID: employeeID, SupervisorID: supervisorId },
success: function(data) {
supervisors =JSON.stringify( data);
$('#divSupervisorList').text(supervisors.replace(",", "<br />"));
},
error: function(data) {
}
});
}
}
Read more:. [https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify].
To replace commas inside each member of your array, you need to map .replace() on the array values:
let result = data.map(function(o){return o.replace(',','<br />')});
To join the members of the array, separating them with a <br />, you need .join():
let result = data.join('<br />');
Note there are no actual commas separating the array members, that's just a conventional way of displaying array values so humans can read and understand them, but there's nothing to replace. All you need to do is join the members with the separator of your choice (<br />) which, by default, is a comma.
So this would also give you the same result:
let result = data.join().replace(',','<br />');
... because .join() would glue the strings using , and .replace() would replace them with <br />s.
According to the jQuery docs:
[dataType is] "json": Evaluates the response as JSON and returns a JavaScript object
So your data is actually an object. You need to access the relevant string property, e.g. data.supervisors.replace(...) - depending on your object model.
I recommend adding a console.log(data) call to your success callback and checking the developer console in your browser by pressing F12 to investigate the source of your issue.
Update: The output of above call to console.log hints at data being an array. Thus, you need to replace
$('#divSupervisorList').text(data.replace(",", "<br />"));
with
$('#divSupervisorList').html(data.join("<br />"));

Preserving order of an associative PHP array while passing it to javascript through ajax

So Here is my php file code
GetUserArray.php
$Users = array('7'=>'samei', '4'=>"chaya", '10'=>'abetterchutia');
echo json_encode($Users);
and this is my ajax request
$.ajax({
url: './GetUserArray.php',
type: 'POST',
dataType: "json",
success: function(users) {
console.log(users);
$.each( users, function( key, value ) {
console.log(key, value);
});
}
});
now what it gives me is in the console is an object sorted by the keys of that array while i want the orignal order which was 7 4 10 in my php file
Object {4: "chaya", 7: "samei", 10: "abetterchutia"}
4 chutiya
7 sali
10 abetterchutia
The problem with using hashmaps is that they don't actually specify order. Though, in PHP, an array is actually an ordered hashmap, so it does. Once you translate that into an object in Javascript, the order is no longer preserved. The only way to guarantee order in Javascript is to use an array.
So in PHP this works as expected and preserves order.
$arr = [4 => "I'm first", 1 => "I'm second", 3 => "I'm third"];
foreach($arr as $value) {
echo $value, "\n";
}
Which gives us
I'm first
I'm second
I'm third
But encode that to Javascript Object Notation (i.e. JSON) and you get an object, because in Javascript arrays don't have keys, they have indexes.
echo json_encode($arr);
Gives us...
{"4":"I'm first","1":"I'm second","3":"I'm third"}
If you tried to do the same in Javascript with this object you might not get the same order
var obj = {"4":"I'm first","1":"I'm second","3":"I'm third"};
var s = "";
for(var x in obj) {
s += + obj[x] + "\n";
}
document.write("<pre>" + s + "</pre>");
This might give you something more like...
I'm second
I'm third
I'm first
So the only way to fix that is to use an array...
json_encode(array_values($arr));
Now this gives us...
["I'm first","I'm second","I'm third"]
And the order is maintained.
However, if you want to preserve the keys as well, you'll have to create an array of objects.
$json = [];
foreach($arr as $key => $value) {
$json[] = [$key => $value];
}
echo json_encode($json);
Now you get...
[{"4":"I'm first"},{"1":"I'm second"},{"3":"I'm third"}]
Which in javascript, works perfectly as expected...
for(var x in obj) {
for(var n in obj[x]) {
obj[x][n]; // now you can both maintain order and have access to the key
}
}

How to get the second data of this JSON in jQuery?

How can I get the second data of this JSON - I am beta. in jQuery?
{"alpha":["I am alpha"],"beta":["I am beta."]}
You can go through array and search for keys what you want... but dont forget to encode json string
$data= json.encode($input)
foreach($data as $key => $val)
{
if($key=='beta')
do something
else
do something else
}
I hope it help you.
Assuming that your json is in a string variable as:
var data = '{"alpha":["I am alpha"],"beta":["I am beta."]}';
You can parse the string as a json object and then access the content like this:
json = JSON.parse(data);
//or if you strictly need to use jQuery
json = $.parseJSON(data);
alert(json.alpha[0]);
alert(json.beta[0]);
If you don't know which is the json content you can iterate through json object like this:
for (var key in json) {
if (json.hasOwnProperty(key)) {
alert(key + " -> " + json[key]);
}
}
Finally I come up with this
Step 1: Json parsed,
Step 2 : Declared in another string
Step 3 : And then looped inside each entry
obj=JSON.parse(data);
var error_string='';
$.each(obj, function(entry) {
error_string+=obj[entry]+'<br/>';
});
$('#stage').html(error_string);
}
And then i got the values that is inside, Now i can able to get the values inside the object even for n numbers.

Parsing JSON to something usable

I know there are 1 million and 1 questions on this, but I cannot seem to find an answer.
I am receiving data via PHP as such
echo json_encode($result);
From a typical MYSQL query.
I get the result back like this in the console.
[{"id" : "1", "name" : "bob"}]
I am trying to use $.each to iterate through this so I can process my results but I only get errors, undefineds or 0[object Object].. things like that.
My goal is to append each value to a input box (retrieving data from a table to put into an edit box).
$.post('getstuff.php', { id : id } function(data){
$.each(data), function(k,v){
$('input[name= k ]').val(v);
});
});
As you can see i was hoping it was as simple as a key=>value pair but apparantly not. I have tried parsing, stringifiying.. really I am lost at this point. I also cannot tell $.post that I am using JSON because I am using a more arbitrary function, but am just posting that as my example.
Edit
var retrievedData = JSON.parse(data);
$.each(retrievedData, function(k,v){
for (var property in retrievedData) {
if (retrievedData.hasOwnProperty(property)) {
console.log(k);
console.log(v);
console.log(property);
//$('input[name= k ]').val(v);
}
}
});
In your second code sample, retrievedData is an array, which you iterate using jQuery $each...
$.each(retrievedData, function(k, v) {
OK so far. But then you try to iterate retrievedData again like an object, which it isn't. This is why you are getting undefined messages in the console
for (var property in retrievedData) {
if (retrievedData.hasOwnProperty(property)) {
console.log(k);
console.log(v);
console.log(property);
//$('input[name= k ]').val(v);
}
}
On the inner loop you should be iterating v not retrievedData. On each pass of $each v will be an object.Try this:
$.each(retrievedData, function(k,v){
for (var key in v) {
if (v.hasOwnProperty(key)) {
console.log("key: " + key);
console.log("value: " + v[key]);
}
}
});
You should do some type checking that v is an object first and catch any errors.
Use either :
$.ajax({
'dataType' : 'json'
});
Or
$.getJSON
Or if you want to use $.post, just do in your success function :
var good_data = JSON.parse(data);
$.each(good_data, function(k,v) {
$('input[name= k ]').val(v);
});
Answering your question based on your comments on other answer.
My assumption is you are getting data as JSON,if not you need to parse it,for that you can use JSON.parse(string).
Here I'm using Underscore.js
var data=[{"id" : "1", "name" : "bob"}]
$(data).each(function(ind,obj){
var keys=_.keys(obj);
$(keys).each(function(i,ke){
console.log(ke)
console.log(obj[ke]);
})
});
Here is JSFiddle of working code
First you need to define you're expecting JSON in your POST request - http://api.jquery.com/jQuery.post/
Then you need to iterate through the response.
$.post('getstuff.php', { id : id } function(data){
//Assuming you get your response as [{"id" : "1", "name" : "bob"}], this is an array
//you need to iterate through it and get the object and then access the attributes in there
$.each(data), function(item){
$('input[name=' + item.name + ']').val(item.id);
});
}, 'json');
EDIT
If you want to iterate over the properties of the objects returned, you need to put another loop inside the $.each
for (var property in item) {
if (object.hasOwnProperty(property)) {
// do stuff
}
}
More about it here - Iterate through object properties
EDIT 2
To address the solution you've posted. You've used the wrong variable names. Here's a working fiddle - http://jsfiddle.net/EYsA5/
var $log = $('#log');
var data = '[{"id" : "1", "name" : "bob"}]'; //because we're parsing it in the next step
var retrievedData = JSON.parse(data);
for (var parentProp in retrievedData) { //this gets us each object in the array passed to us
if (retrievedData.hasOwnProperty(parentProp)) {
var item = retrievedData[parentProp];
for (var property in item) { //this gives us each property in each object
if (item.hasOwnProperty(property)) {
console.log(item[property]);
$log.prepend("<br>");
$log.prepend("Property name is - " + property);
$log.prepend("<br>");
$log.prepend("Value of property is - " + item[property]);
//do stuff
}
}
}
};

Create array of arrays from JSON

I am receiving after an ajax call the following as response using in php json_encode:
"['2013-02-24', 0]", "['2013-02-25', 0]", "['2013-02-26', 1]", "['2013-02-27', 6]", "['2013-02-28', 6]", "['2013-03-01', 3]", ...
How can I make in JavaScript from this an array of arrays? Is this even possible? I mean, I've tried with jQuery makeArray or with parseJSON with no success. What is the most preferred method?
Edit:
function submitForm(t) {
$.ajax({type:'GET', url: 'charts.php', data:$(page_id).serialize(), success:
function(response) {
var myFanRemovesData = new Array(response);
var myChart = new JSChart(chart_id, 'line');
myChart.setDataArray(myFanRemovesData);
I have to use the array of arrays to set myFanRemovesData with it
1) strip out the double-quotes ("):
var json = json.replace(/"/g, '');
2) wrap the whole thing in square brackets:
json = "[" + json + "]";
3) replace the single-quotes with double-quotes (because the singles won't parse):
json = json.replace(/'/g, '"');
4) parse the json string:
var arrays = JSON.parse(json);
Here is a working example. It will alert the first date in the first array. (note: the data is pulled from the DIV to simulate the AJAX call and to avoid me having to mess around with escaping quote characters)
Try:
var response = ["['2013-02-24', 0]", "['2013-02-25', 0]", "['2013-02-26', 1]"];
for (var i = 0; i < response.length; i++) {
var cleaned = response[i].replace(/'/g, "\"");
response[i] = $.parseJSON(cleaned);
}
DEMO: http://jsfiddle.net/hu3Eu/
After this code, the response array will contain arrays, made out of the original strings.
Just example.. because you haven't provide us with any code...
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" },
dataType: 'json',
}).done(function( responde ) {
$.each(responde, function(i, v){
alert(v.0 + ' --- ' + v.1);
});
});
If you receive and expecting json you directly can use it as array/object :)
If its array you have to make a each loop so you can access each value..

Categories