fail to get json object in javascript from php - javascript

I am trying to pass json string to javascript from php, so at first i did
<div id="picker" data-dates=\''.json_encode(unserialize($a->available_datetime)).'\'></div>
and then, i try to grab it in jquery
if($("#picker").length){
available = $("#picker").attr("data-dates");
}
However, it seems it then fail to loop through the object to get key and val
$.each(available,function(key,val)
{}
It keep getting error of
var length = !!obj && "length" in obj && obj.length,
Tried for several hours now, cant find a solution to solve. Anyone can help? Thanks.

Use $("#picker").data("dates") it will get the data stored in the attribute data-dates and convert it to JSON, assuming you have a JSON string in that attribute.
Then use:
for (var i in available) {
//do something with available[i]
}
check example: https://jsfiddle.net/fud6sfjo/

Related

Json Keys Are Undefined When Using Them From Script Tag

I've been trying to load certain Json with Ajax GET request and then parsing it.
However when trying to access the Json key from HTML script tag it was undefined.
In order to debug this issue, I logged all the keys of Json in console as well as the Json itself. Therefore i utilized this function:
function getInv() {
$.get( "/inventory/", function( data ) {
var invList = data.split(",, "); // Explanation is below
console.log(invList[0]) // Just testing with first object
console.log(Object.keys(invList[0]));
});
}
getInv();
Purpose of data.split(",, "):
Since my backend script uses different programming language, I had to interpret it to the one suitable for Javascript.
There also were multiple Json objects, So i separated them with ",, " and then split them in Javascript in order to create a list of Json objects.
After calling the function, Following output was present:
Although the interesting part is that after pasting Json object in console like this:
This was the output:
So basically, in script tag, i was unable to access object's keys, although once i used it manually in console, all keys could be accessed.
What could be the purpose behind this? It seems quite strange that different outputs are given. Perhaps invList[0] is not Json object at all in the script tag? Thanks!
data.split() returns an array of strings, not objects. You need to use JSON.parse() to parse the JSON string to the corresponding objects.
function getInv() {
$.get( "/inventory/", function( data ) {
var invList = data.split(",, ");
console.log(invList[0]) // Just testing with first object
var obj = JSON.parse(invList[0]);
console.log(Object.keys(obj));
});
}
You can use .map() to parse all of them, then you'll get an array of objects like you were expecting:
var invList = data.split(",, ").map(JSON.parse);

loop in JSON with undefined elements

I am trying to figure out how to retrieve the values of a json of which i do not know the number of elements.
Example:
my json can be something like
var json = ["fixelement1":"value1","fixelement2":"value2","fixelement3":"value3","variableelement4":"value4","variableelement5":"value5"]
or
var json =["fixelement1":"value1","fixelement2":"value2","fixelement3":"value3","variableelement7":"value7","variableelement8":"value8", "variableelementN":"valueN"]
the only thing that I know is that the first 3 elements are always the same.
I use .indexOf() to search a value in fixelement3. What I would like to do is, if I find the element, I would like to retrieve the name of all the following elements (which number is variable and that are unknown) and their values.
javascript or jquery would work for me, but I have no idea..
thank you in advance!
var json ={
"fixelement1":"value1",
"fixelement2":"value2",
"fixelement3":"value3",
"variableelement7":"value7",
"variableelement8":"value8",
"variableelementN":"valueN"
}
for(prop in json){
console.log('key ======> value', prop, '=====>', json[prop]);
}

Json associative array accessing in jQuery

I am getting response in below format for every product and in a single call there can be many products. I am trying to access this data via jQuery but I'm not able to access it.
Productdata['someid'] = { "Product Json data"}
I am using below syntax in jQuery but not getting the data. Please suggest.
alert(Productdata['someid']);
Its not going as JSON format .
JSON is a key : value pair format ;
so your Productdata should be in below format:
Productdata = { 'someid' : "Product Json data"}
A Json like this
var data={"name":"somebody"};
To call
return data.name
Or
return data["name"]
The problem here is that JavaScript does not support associative arrays (scroll down to "Associative arrays, no way!"). It has some internal workarounds which make it appear as if it does, but really all it does is just adding the keys as properties.
So you would most likely be able to access it using Productdata.someid = ....
EDIT:
So assuming you have the following JSON string: {"id":"123"} (which is valid JSON), you can use it like this:
var jsonString = '{"id":"123"}';
var parsedJSON = $.parseJSON(jsonString);
var productID = "product_" + parsedJSON.id;
Does this help?
Some useful links: JSON format checker to make sure the JSON is valid.
Unfortunately I wasn't allowed to add more than 2 links, so the jQuery parseJSON function link is still in the comment below.

How to get json value in js code?

I have a json code and i want get json value units_num in alert jQuery. How can don it?
My json code:
[{"id":"11","name":"hiih","units_num":00}]
I tried as in js code: http://jsfiddle.net/Wj8ZL/
var obj = $.parseJSON('[{"id":"11","name":"hiih","units_num":00}]');
alert(obj['units_num']); // This don't work
var t = JSON.parse('[{"id":"11","name":"hiih","units_num":00}]');
alert(t['units_num']) // This don't work
Your json contains an array of objects, even if there is only one in there. So you need to access that first object in the array
var obj = $.parseJSON('[{"id":"11","name":"hiih","units_num":"00"}]');
alert(obj[0]['units_num']);
#TravisJ gave a big part of the issue, the other one being quite easy to spot if you read the error log:
"units_num":00
is not valid. It should read
"units_num":0

How to retrieve value from object in JavaScript

Hi I am using a Java script variable
var parameter = $(this).find('#[id$=hfUrl]').val();
This value return to parameter now
"{'objType':'100','objID':'226','prevVoting':'" // THIS VALUE RETURN BY
$(this).find('[$id=hfurl]').val();
I want to store objType value in new:
var OBJECTTYPE = //WHAT SHOULD I WRITE so OBJECTTYPE contain 400
I am trying
OBJECTTYPE = parameter.objType; // but it's not working...
What should I do?
Try using parameter['objType'].
Just a note: your code snippet doesn't look right, but I guess you just posted it wrong.
Ok, not sure if I am correct but lets see:
You say you are storing {'objType':'100','objID':'226','prevVoting':' as string in a hidden field. The string is not a correct JSON string. It should look like this:
{"objType":100,"objID":226,"prevVoting":""}
You have to use double-quotes for strings inside a JSON object. For more information, see http://json.org/
Now, I think with $(this).find('[$id=hfurl]'); you want to retrieve that value. It looks like you are trying to find an element with ID hfurl,but $id is not a valid HTML attribute. This seems like very wrong jQuery to me. Try this instead:
var parameter = $('#hfurl').val();
parameter will contain a JSON string, so you have to parse it before you can access the values:
parameter = $.parseJSON(parameter);
Then you should be able to access the data with parameter.objType.
Update:
I would not store "broken" JSON in the field. Store the string similar to the one I shoed above and if you want to add values you can do it after parsing like so:
parameter.vote = vote;
parameter.myvote = vote;
It is less error prone.

Categories

Resources