Passing PHP array to JAVASCRIPT (issue) - javascript

There's some weird issue it seems.
I'm trying to pass a php array to js, which I've accomplished. I can display the array size like so
document.getElementById("test").innerHTML = (jarr.length);
and it works perfectly fine, however, when I try to display a value in said array, it says object Object
and what's weird is if I go try to read a value which isnt stored, for example jarr[234] it says undefined because there's no value stored, so I know some data is being transferred.
Any help?
edit: here's how I passed the array to js
var jarr = <?php echo json_encode($testing); ?>;
edit: I forgot the remove the parse part before copying it, I was experimenting beforehand.

You should be able to just directly use jarr without parsing it, for example:
document.getElementById("test").innerHTML = jarr.length;
document.getElementById("first_element").innerHTML = jarr.length > 0 ? jarr[0] : "empty array";
If you are doing the above and the elements are showing up as object Object it means that inside your array, you are storing objects rather than primitive data types. So maybe try something like the following to generate a nice string representation of those objects (noting that this is needed for displaying them, but not for using them directly in your JavaScript code):
document.getElementById("first_element").innerHTML = jarr.length > 0 ? JSON.stringify(jarr[0]) : "empty array";

What Chris said fixed the issue!
"To show the entire array: document.getElementById("test").innerHTML = JSON.stringify(jarr); To show a single string: document.getElementById("test").innerHTML = jarr[0]; – Chris G 7 mins ago
"
For whatever reason adding the (stringify) fixes it for me.
An example
document.getElementById("test").innerHTML = JSON.stringify(jarr[2].title);

Related

Passing a json array to javascript function in a jade rendered page

I have a json array being passed to a jade template.
This template then runs through the array adding rows to the html output.
However a new requirement no needs that json object to be passed to a javascript function, so I tried:
- var json = JSON.stringify(rows);
input.medium.success.button.error(type='submit', id='update_details', value= sendCommandLabel, onclick='sendCommand(' + json + ')')
which gives the following output (the full array omitted from brevity):
<input type="submit" id="update_details" value="Send Command" onclick="sendCommand([{"id":"id1;,"param1":value1, ... "}])">
Which is not useful as I am want to use this output in the javascript function and as it stands I can't consume it.
I am hoping I am missing something simple as my other option is to recreate the json array by looping through the objects in the renderer to recreate it!
UPDATE: I modified the code so instead of passing the array to the function, the array is hardcoded into the function while the jade page was being compiled. So this:
function sendStopCommandToAllSensors()
{
var hardcode = !{JSON.stringify(rows)};
became
function sendStopCommandToAllSensors()
{
var hardcode = [{"id":"id1", ... }, {"id":"id2", ... }];
But that still didn't work.
Puzzlingly adding a couple of simple alerts in there showed that there was the correct number of objects (later confirmed that there by cutting and pasting the resultant string directly into code and then manually adding a third object).
alert(hardcode.length); // displays 2
alert("rows: " + hardcode); // displays [object Object],[object Object]
Which is why in the loop that follows the
for (var row in hardcode)
{
alert("row: " + row); // displays 0 or 1, not an object
if (row.active == 1)
{
alert("Reached here"); // never reached
the final line is never reached.
UPDATE II: By stringifying hardcode I can output the human readable json.
alert("rows: " + JSON.stringify(hardcode));
Why is the code not seemingly parsing the array correctly and what to I do need to do correct it?
UPDATE III: I now having it working by using a two step traditional loop and assignment.
for (var i=0; i<rows.length; i++)
{
var row = rows[i];
So the question seems to be now, why didn't the for..in loop work as expected?
I am new to this, but I was going through similar problem I think.
But I am totally ok with JSON.stringify method, which was your first solution. It looks ugly in generated hmtl, but I found it useful in my case.
At least I think I understood it right and you are not trying to do some kind of magic what I can't absorb yet.
if
rows=[{id:id,param:param},{id:id2,param:param2}]
JADE:
- var json = JSON.stringify(rows);
input(type='submit', onclick='myFunction(' + json + ')')
JS:
function myFunction(myRows) {
console.log(myRows[0].id);
console.log(myRows[0].param);
console.log(myRows[1].id);
console.log(myRows[1].param);
.
.
at least it is ok in what I am working on.
I hope I didn't wrote pile of nonsense :)

addition in javascript is resulting in an object

I am tring to add 2 values together in a javascript application however when I try and do this the output I get is;
Total Price £[object Object]116.96
Where [object Object] is the value I am trying to add to 116.96
the code I am using to do the addition is bellow;
document.getElementById("getTotal").addEventListener("click", function()
{
var STotal = (($('#SeatPrice')+(subTotal)).toString());
$('#total').text(STotal);
});
these are where the values for '#seatPrice' and '#total' are derived from
$('#total').text(subTotal.toString());
$('#SeatPrice').text((($('td.selected').length)+count)*pricing);
If anyone has any ideas on how to resolve this issue please let me know.
Thanks!
The problem lies here: var STotal = (($('#SeatPrice')+(subTotal)).toString());
$('#SeatPrice') is a jquery function which returns an object - the html element you've searched for. So when you add that to your subTotal, you are adding the object to a string which, in javascript, will just create a string out of both.
You probably want to get the value of that element using something like $('#SeatPrice').val() or $('#SeatPrice').text()

Java Script + JSON Parsing and converting into Array

I'm looking for help in converting a particular elements in JSON message to an array using java script at run time. We wanted the script to be more generic. Actually we were trying the following which worked for single element and while changing it to handle for multiple elements at run time its not working.
//Working for Single element - Static
var bodyContext = JSON.parse(response.content)
if(bodyContext.companylist.company.constructor !== Array){
bodyContext.companylist.company = [bodyContext.companylist.company]
}
The above code works and converts Company in JSON message as a Array, Where as the below we tried for multiple elements is not working
//Not Working for multiple elements - dynamic
var bodyContext = JSON.parse(response.content)
var elementName = "";
//Loop runs every time and changes the value of elementName at every iteration
if(bodyContext.elementName .constructor !== Array){ //not working
bodyContext.elementName = [bodyContext.elementName] //Not working
}
instead of looking for "bodyContext.companylist.company" and converting into Array, "bodyContext.elementName" is checked and added to the bodycontext object.
how to handle this. ElementName variable along with JavaScript object is not recognized.
Please help.
you can JSON.parse(data) then you can fetch data from Javascript object like
$.each(Obj,function(key,value){
});
You'll want to use
bodyContext[elementName]
since
bodyContext.elementName
looks for a field in bodyContext named elementName, not the a field named after the value in elementName.
Also, you initialize elementName with "", and this won't match anything on the first iteration.

Concatenating a value onto the end of an object property?

I'm saving user preferences using localStorage, like this:
choicesObject = { //put values in an object
"measure1" : $("#m1").is(':checked'),
"measure2" : $("#m2").is(':checked'),
"measure3" : $("#m3").is(':checked'),
"measure4" : $("#m4").is(':checked'),
"measure5" : $("#m5").is(':checked'),
"measure6" : $("#m6").is(':checked'),
"measure7" : $("#m7").is(':checked'),
"measure8" : $("#m8").is(':checked')
}
localStorage.setItem("choices", JSON.stringify(choicesObject));
Then I'm getting them back out like this:
retrieveChoices = localStorage.getItem("choices");
choicesObject = JSON.parse(retrieveChoices);
for(var i = 0;i<9 ;i++){
This nex t line is the problem:
ticked = choicesObject.measure+i;
It just doesn't work and I've tried using quotes and square brackets.
element = "#m" + i;
if(ticked==true){
$(element).prop('checked', true);
}
else{
$(element).prop('checked', false);
}
}
}
I want to loop though the measure properties and restore the checkbox elements.
I'm aware that even my object create is inefficient and I could use a for loop for that but I just don't know how to deal with object properties when it comes to looping because I don't get how you can do it without breaking the object.
At least that works and I can get data into and out of objects that get stored in localStorage, but this really simple issue has me stumped.
PS. Would
choicesObject = localStorage.getItem(JSON.parse("choices"));
be a better shorthand? Just thought this now whilst re-reading my question.
Edit: Thanks everyone. I got 3 correct answers so quickly! Amazing. Thanks so much. This site and its members amaze me every day and have revolutionised my coding!
I'm going to choose the correct answer as the one that also gave me the new shorthand for my parsing, but all of you gave me what i needed to know. I'm going to go see if I can answer some noob questions now!
Use
ticked = choicesObject["measure"+i];
EDIT: Your shorthand would not work, use instead:
choicesObject = JSON.parse(localStorage.getItem("choices"));
An object is just like a "dictionary" of values, so you can access a property either by doing myobject.propertyName or myobject["propertyname"]. They are equivalent.
In your case you just have to replace ticked = choicesObject.measure+i; with
ticked = choicesObject["measure"+i];
Also, consider using the var keyword when defining variables, each time you ommit it a new global variable will be created in the window object, that is the case for retrievedChoices and choicesObject. You can confirm this by accessing them via window["choicesObject"] or window.choicesObject or just choicesObject anywhere after that script has run.

oocharts invalid filter parameters after array is converted to string

I've been having trouble setting a dynamic filter for oocharts.
I've looped through some things and have created an array (scenefilters) which I've joined to make a string. I've then tried to use this as a filter, which returns the error:
*JSONP.callbacks.request_63 && JSONP.callbacks.request_63({"error":"Invalid param {filters}: Filter string is not in valid format"});*
Now if I console.log the variable 'locationfilter2' and copy and paste it directly into the filter, it works fine - but it doesn't work just with the variable. Do I need to do something else to the variable to make sure it's a string?
var locationfilter = scenefilters.join(",");
var locationfilter2 = '"'+ locationfilter +'"';
var visits = new oo.Metric("54190402", "12m");
visits.setMetric("ga:visits");
visits.query.setFilter(locationfilter2);
visits.draw(timeline);
EDIT
I've tried outputting the variable to a textfield and copying it from there, same thing. The output is "ga:pagePath=~s101$,ga:pagePath=~s102$,ga:pagePath=~s103$,ga:pagePath=~s104$,ga:pagePath=~s105$,ga:pagePath=~s106$,ga:pagePath=~s107$,ga:pagePath=~s108$,ga:pagePath=~s109$,ga:pagePath=~s110$,ga:pagePath=~s111$,ga:pagePath=~s112$,ga:pagePath=~s113$,ga:pagePath=~s114$,ga:pagePath=~s115$,ga:pagePath=~s116$,ga:pagePath=~s117$,ga:pagePath=~s118$,ga:pagePath=~s119$,ga:pagePath=~s293$,ga:pagePath=~s301$"
And if I copy this directly into the filter, i.e. visits.query.setFilter("ga:pagePath=~s101$,ga:pagePath=~s102$,ga:pagePath=~s103$,ga:pagePath=~s104$,ga:pagePath=~s105$,ga:pagePath=~s106$,ga:pagePath=~s107$,ga:pagePath=~s108$,ga:pagePath=~s109$,ga:pagePath=~s110$,ga:pagePath=~s111$,ga:pagePath=~s112$,ga:pagePath=~s113$,ga:pagePath=~s114$,ga:pagePath=~s115$,ga:pagePath=~s116$,ga:pagePath=~s117$,ga:pagePath=~s118$,ga:pagePath=~s119$,ga:pagePath=~s293$,ga:pagePath=~s301$");
It works well. But if I use the variable I get the error. Anyone any ideas?
OK stupid one. Removed the ""s and it works fine.

Categories

Resources