javascript strange error, console is not giving any errors.. - javascript

The following is my code, i intend to use it as a bookmarklet.
javascript: (function () {
var jsCode = document.createElement('script');
jsCode.setAttribute('src', '//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js');
document.body.appendChild(jsCode);
console.log("Everything is fine upto here!");
data = [["#txtApplcntName","test"],["#txtApplcntAdd","test"]];
console.log(data);
var obj = $.parseJSON(data);
for (var i = obj.length - 1; i >= 0; i--) {
var current = obj[i];
console.log(current);
$(current[0]).val(current[1]);
};
})();
Problems start when the actions in the for loop never take place. It gets even weirder when i can successfully log the variable obj and it logs, but when i do obj.length a null is encountered?
I am experimenting on Google chrome

Try this:
data = '[["#txtApplcntName","test"],["#txtApplcntAdd","test"]]';
Method JSON.parse(str, reviver) reads a string.
What you're trying to do is treat an ordinary array as JSON.

var obj = $.parseJSON(data)
obj get a null ."data" can't convert to json object.

Related

Am I building the JavaScript objects correctly for a JSON string array?

In JavaScript I have the following code:
for (i = 1; i<3; i++)
{
// above I collect check_a and check_b through radio button responses.
var connectJSON = ",";
var passObj = {id:i, ask:check_a, description:check_b};
// adding object string together in tempObj
var tempObj = tempObj + connectJSON + passObj;
}
// get ready for transport to server and display result of string
var data = JSON.stringify(tempObj);
console.info("info: " + data);
// post string to server
$.ajax
({
type: 'POST',
url: 'out.php',
data: {data: data},
success: function(msg)
{
alert(msg);
}
});
In out.php I try to determine the result back from the server. The code is as follows:
<?php
if (ISSET($_POST['data']))
{
echo "TRUE";
}
ELSE
{
echo "False";
}
var_dump($_POST['data']);
?>
I am getting this message, AJAX alert (msg) :
**True** string(42) ""question, [object Object], [object Object]""
Apparently this message is describing the string array being passed.
What I now need to do, if the format is correct, is to be able to access the string array - maybe with JSON_decode and identify properties of the array so that I can make insertions into a MySQL database.
Thanks for any AND all help...
var connectJSON = ",";
var passObj = {id:i, ask:check_a, description:check_b};
// adding object string together in tempObj
var tempObj = tempObj + connectJSON + passObj;
First of all. If you just test this part in the console you will see that if you concatenate JS object and the string ',' you get the string "[object Object],[object Object]". You need to first stringify the JS object before concatenating it with strings.
Second I can really seem to understand your code but looping that code will just override those variables because they are declared in the loop so that doesn't seem correct. Probably you want to get the declarations out of the loop.
Otherwise it's kind of like this - you stringify the Js object and pass it as data to the ajax.
No. To build JSON, first build a valid structure, then use JSON.stringify on the result; don't convert to string while building the structure. connectJSON + passObj will force passObj to string, resulting in "[object Object]".
Instead:
var array = []; // <== An empty array
for (i = 1; i<3; i++)
{
// Push entries into the array
array.push({id:i, ask:check_a, description:check_b});
}
// Convert to JSON
var data = JSON.stringify(array);
Side note: The code in your question didn't declare i anywhere. If your real code doesn't, it's falling prey to The Horror of Implicit Globals.* Be sure to declare your variables. :-)
* (that's a post on my anemic little blog)
The issue is here var tempObj = tempObj + connectJSON + passObj;. You are concatinating objects and strings. In that case JavaScript will use Object.prototype.toString() first and then do the concatination. and Object.prototype.toString() in case of objects will produce [object Object]. To fix this you have to create an array like below.
var tempObj = [];
for (i = 1; i < 3; i++) {
// above I collect check_a and check_b through radio button responses.
var connectJSON = ",";
var passObj = {
id: i,
ask: check_a,
description: check_b
};
tempObj.push(passObj);
}
Also, you can skip JSON.stringify() and directly submit the JS object.
I'm trying to understand how is this deceleration :
var tempObj = tempObj + etc...;
possible ?
you cant set the value of something you just declared,
to the same thing you just declared .

Get JSON data after it's stored in a variable

After getting JSON back from the ajax call, the data "response" is stored in the "theObj" variable; however, when I try to log "theObj" to the console, it results in multiple "[Object object]", even with JSON.stringify().
If I do a "theObj[0]" (response.results[0] works fine), I get "[", for the first character in "[Object object]".
Q: How can I store JSON in a variable and get the data back out afterward?
$.ajax(settings).done(function(response) {
for (var i = 0; i < 19; i++) {
//creating JSONenter[enter image description here][1]
theObj += response.results[i];
if (i == 18) {
//console.log(theObj.id)
console.log(JSON.stringify(theObj[0].id))
}
}
}
I think the error is in the line
theObj += response.results[i];
So try this instead
function (response) {
var list = response.results;
// if there is no reason for having 19, replace this with var end = list.length
var end = Math.min(list.length, 19);
for(var index = 0; index < end; index++) {
theObj.push(list[index]);
}
console.log(theObj);
}
We don't see the initialization of theObj variable
If it is an array you should use the push function to add elements to it
If it is a common object then use theObj[id] = list[index];
DISCOURAGED If it is a string then you should use theObj += JSON.stringify(response.results[i];) + ", ";, then make sure that you add } or ] at the end if it is an object or array respectively (and that it has also has { or [ in the begining) and then use JSON.parse(theObj) to convert it back to an object
Please let me know which of the above are you using
try this
$.ajax(settings).done(function(response) {
$.each( response, function( key, val ) {
console.log(val.id)
});
}
I assumed you want to get the data as object and not a string.
For that you have to use var object = JSON.parse(yourJSONString). This method returns an object based on your JSON string.
Example:
JSON result:
{
"name":"John Doe"
}
Javascript code:
var john = JSON.parse(result);
console.log(john.name); //prints John Doe

How to access Object within JSON?

Context
If I have the following JSON data:
{"response":"success","data":[{"id":"2"}]}
I'm trying to get the ID that is sent through, 2.
Attempts
I've tried the following:
var r = JSON.parse('{"response":"success","data":[{"id":"2"}]}');
if(r.response=="success"){
var usr = r.data;
console.log(usr.id);
}
The above outputs undefined.
var r = JSON.parse('{"response":"success","data":[{"id":"2"}]}');
if(r.response=="success"){
var usr = r.data;
for(var k in usr){
if(usr.hasOwnProperty(k)){
console.log(usr.k);
}
}
}
The above outputs undefined.
var r = JSON.parse('{"response":"success","data":[{"id":"2"}]}');
if(r.response=="success"){
var usr = r.data;
var ret = [];
for(var key in usr){
ret.push(key);
}
console.log(ret);
}
The above outputs 0.
var r = JSON.parse('{"response":"success","data":[{"id":"2"}]}');
if(r.response=="success"){
var usr = JSON.parse(r.data);
console.log(usr.id);
}
The above outputs an error - bear in mind this is running via Nativescript so the simulation environment (Android Emulator) may be causing this error:
chromium: [INFO:library_loader_hooks.cc(120)] Chromium logging enabled: level = 0, default verbosity = 0
01-26 19:20:55.423 4875 4875 I BrowserStartupController: Initializing chromium process, singleProcess=true
chromium: [WARNING:resource_bundle.cc(285)] locale_file_path.empty()
01-26 19:20:55.441 4875 4875 E DataReductionProxySettingListener: No DRP key due to exception:java.lang.ClassNotFoundException: com.android.webview.chromium.Drp
chromium: [WARNING:data_reduction_proxy_config.cc(423)] SPDY proxy OFF at startup
Question
How can I access the id property of data in the following JSON string with JavaScript:
{"response":"success","data":[{"id":"2"}]}
You can try with following code. You firstly need to access the data property and then since data is an array, you need an index to access the first elements like data[0] Property and then the id property can be retrieved by r.data[0].id
var r = JSON.parse('{"response":"success","data":[{"id":"2"}]}');
if(r.response === "success"){
console.log(r.data[0].id)
}
You can access console.log(usr[0].id);
Your data value is an array not an object
so on your first attempt, update this:
console.log(usr.id);
to this:
console.log(usr[0].id);
Or you could do a for loop:
if(r.response=="success"){
var usr = r.data;
for(i=0; i < usr.length; i++) {
console.log(usr[i].id);
}
}
Fiddle
Your data object is an array, so you must access first to the position of the array:
usr[0]
the you get the id value
usr[0].id
If you want to access directly with usr.id you need change your JSON data object array to a simple object:
{"response":"success","data":{"id":"2"}}
or make an ugly reasignation:
usr = usr[0]
This is because you have used [] where {} only to be used. If [] is used, then it is an array property, then to access 2, [0].id should be used.
remove [] from [{"id":"2"}]

Can't acces a string in multidimensional array

I'm writing a function that should read a csv file and then process it so I can use it to generate an HTML table. Basically the output of the function should be a multidimensional array that looks like this : [["prop", "type"], ["prop", "type"]...]
The problem is that when e.g. I try to access to "prop" using importProps[0][0], it will actually output a "p". The weirdest thing is the output of the console in the two last lines of the function; I consider them as being the same thing, but they deliver a different output. I don't understand why I can't access to the whole string like on the console.log(elem[0]) line.
Here is my code.
function importProperties() {
//read the data
var importProps = readTextFile(getProjectDirectory() + '/test.csv'); //outputs ["prop; type", "prop; type"...]
// process it to become [["prop", "type"], ["prop", "type"]...]
for (var i = 0; i < importProps.length; i++) {
var elem = importProps[i].split(';');
importProps[i] = elem;
console.log(elem[0]); // Outputs $"prop"
console.log(importProps[i][0]); // Outputs $"p" <--WHY ?
}
My original loop was
for (var i = 0; i < importProps.length; i++) {
importProps[i] = importProps[i].split(';');
}
which produces the same unexpected result. I just added the element variable for debugging purposes.
By the way, I'm writing this in a software-embedded browser which communicates with the software through a provided API. The console in this browser has only very limited capabilities and makes it hard to do some proper debugging.
Unfortunatelly I am not allowed to comment :(
The code runs fine in console and provides what you asked for.
My guess would be that in the real code you assigned the string instead of the array importProps[i] = elem[0];
var importProps = ["prop; type", "prop; type"];
for (var i = 0; i < importProps.length; i++) {
var elem = importProps[i].split(';');
importProps[i] = elem[0]; //Maybe you have this line live instead of importProps[i] = elem;?
console.log(elem[0]);
console.log(importProps[i][0]);
}
I finally found the solution. The browser that is embedded in the software is actually based on Webkit. After I've tried pasting the code in Firefox as suggested by Mike, I got to the same conclusion as he did : it worked perfectly.
After a little research and multiple typeof statements, I found where the problem came from. It actually came from the importProps[i] = elem; line. elem is an array here (typeof outputs object) while importProps[i] is a string (typeof outputs string). After I assign elem to importProps[i], importProps[i] is still a string ! (typeof returns string).
for (var i = 0; i < importProps.length; i++) {
var elem = importProps[i].split(';');
importProps[i] = elem;
console.log(typeof importProps[i]); // Logs 'string'!!! Firefox logs 'object' here
console.log(typeof elem); // Logs 'object'
};
That is not the case in Firefox, and I don't know why this behavior has been implemented to Webkit. The solution was finally to create a multidimensional array and assign the split string to it.
function importProperties() {
//read the data ["prop;type", "prop;type"]
var importProps = xxxAPI.readTextFile(xxxAPI.getProjectDirectory() + '/test.csv');
//process to be [["prop", "type"], ["prop", "type"]...]
var importPropsArray = [[]]
for (var i = 0; i < importProps.length; i++) {
var elem = importProps[i].split(';');
importPropsArray[i] = elem;
};
return importPropsArray;
};
I don't know if this is kind of a bug or a desired behavior, but it's very weird.

How to parse read json elements with jquery

I have to create cart system in my mobile application, i want to store the id and the quantity of products, the id should be the key of my array (for modifying product quantity) , tried to use object instead of array but i get error: undefined is not a function when i try to read my json variable
by JSON.stringify(cart)
My cart code is like this
var cart = [];
var produit = {};
produit['qte'] = $('.'+id_prd).text();
produit['id_produit'] = id_prd;
cart[id_prd] = produit;
window.sessionStorage["cart1"]= JSON.stringify(cart);
return me
{"7":{"qte":"1","id_produit":7},"8":{"qte":"1","id_produit":8}}
when I tried to parse the json string with
var parsed = $.parseJSON(window.sessionStorage["cart1"]);
i get the error 'undefined is not a function'
when triying to read the json with
var i=0;
for (k in parsed) {
var k_data = parsed[k];
k_data.forEach(function(entry) {
alert(entry);
ch+=entry.id_produit;
if(i<parsed.length-1)
ch+= ',';
if(i==parsed.length-1)
ch+=')';
i++;
});
}
Can you clarify me the error cause, and if there's a solution to better read the json
The problem is that you are using k_data.forEach(function(entry) but forEach is for Arrays, and k_data is just a simple javascript object.
Try changing:
k_data.forEach(function(entry){
to this:
$(k_data).each(function(entry){
Even more, if the JSON is always in the same structure you posted, I think the each function is not necessary, maybe this is the way you are looking for:
var i=0;
var ch = "(";
for (k in parsed) {
var k_data = parsed[k];
alert(k_data);
ch+=k_data.id_produit;
ch+= ',';
i++;
}
ch = ch.substring(0, ch.length - 1) + ")";
You shouldn't need jQuery for this. The same JSON object you used to stringify has a parse function:
var parsed = JSON.parse(window.sessionStorage["cart1"]);
If that still breaks, there's probably something wrong with another undefined object.
You can try something like this:
<script type="text/javascript">
var finalArr = new Array();
var dataArr = new Array();
dataArr = window.sessionStorage["cart1"];
if (JSON.parse(dataArr).length > 0) {
for (var i = 0; i < JSON.parse(dataArr).length; i++) {
finalArr.push((JSON.parse(dataArr))[i]);
}
}
</script>

Categories