JSON.stringify not working - undefined - javascript

I'm getting into troubles with JSON in javascript. I have one code where I use the JSON.stringify all the time and never had problems with it. But when I enter my application, I cannot use it. It keeps returning me in console (Google Chrome) the following:
Uncaught TypeError: undefined is not a function lista.js:188
which is definetly the line where the stringify function is on.
Do any of you know any ways to solve this problem? It's like the JSON unit is not found or something. Or maybe a workaround... I'll post my code below:
Thanks in advance!
in my index.php I have a header with:
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
//This is the code to the function.
function Salvar(AIdProcesso){
var Respostas = new Array ();
var Registro = 1;
$('.chkResposta').each(function(){
var chk = $(this);
var IdTitulo = chk.attr("idTitulo");
var Valor = chk.isChecked() ? 'true' : 'false';
var Item = [IdTitulo, Valor];
Respostas[Registro] = Item;
Registro = Registro+1;
});
$('.edtValor').each(function(){
var edt = $(this);
var IdTitulo = edt.attr("idTitulo");
var Valor = edt.val();
var Item = [IdTitulo, Valor];
Respostas[Registro] = Item;
Registro = Registro+1;
});
//this is where I get the error!!
var JsonString = JSON.stringify(Respostas, function(){}, 2);
$.post(
'processos/lista.php', {
Op: 'Inscricao',
Id: AIdProcesso,
Itens: JsonString
}, function(rHtml){
JSON = jQuery.parseJSON(rHtml);
$('.breadcrumb').html(JSON.breadcrumb);
$('.Box').html(JSON.box);
});
}

On this line
var JsonString = JSON.stringify(Respostas, function(){}, 2);
you're passing in a replacer function that doesn't return anything. The replacer function you pass into stringify is expected to return something. Refer to the specification for details.
Side note: You're including json2.js in your page, but note that all modern browsers, as well as IE8, support JSON natively. Unless you need to support IE7 and earlier, or truly old browsers from other vendors, you don't need that script anymore.

Related

javascript 'object object' from localstorage

I am getting an alert saying [object] object when I execute showlogsf function
var fdata = {fidval, fweightval, feggslaidval, fgraineatenval, fwaterval};
var fidval = document.getElementById('#fid');
var fweightval = document.getElementById('#fweight');
var feggslaidval = document.getElementById('#feggslaid');
var fgraineatenval = document.getElementById('#fgraineaten');
var fwaterval = document.getElementById('#fwater');
These are the two functions that could be triggered from button click
$('#submitf').click(function (){
localStorage.setItem ("fdatak", JSON.stringify(fdata));
});
$('#showlogsf').click(function(){
var fdataload = JSON.parse(localStorage.getItem("fdatak"));
alert(fdataload);
});
});
You're pushing an object as an alert. the HTML displays this as [object Object]. You have to address the actual properties of this object, so:
$('#showlogsf').click(function(){
var fdataload = JSON.parse(localStorage.getItem("fdatak"));
alert(fdataload.fidval);
alert(fdataload.fweightval);
alert(fdataload.feggslaidval);
// etc etc...
});
EDIT: Seems like you're also saving the document element, rather than the value. I assume the fdataload.properties are actual values, you should either grab the raw HTML data or input value of this instead of the HTML element itself
I guess your fdata is an array right?.
Try this var fdata = [fidval, fweightval, feggslaidval, fgraineatenval, fwaterval];
I edited values of array as xxx.value instead of xxx
var fdata = new Array();
$('#submitf').click(function (){
var fidval = document.getElementById('fid');
var fweightval = document.getElementById('fweight');
var feggslaidval = document.getElementById('feggslaid');
var fgraineatenval = document.getElementById('fgraineaten');
var fwaterval = document.getElementById('fwater');
var fdata = [];
like this
fdata.push (fidval.value, fweightval.value, feggslaidval.value, fgraineatenval.value, fwaterval.value);
localStorage.setItem ("fdata", JSON.stringify(fdata));
});
$('#showlogsf').click(function(){
var fdataload = JSON.parse(localStorage.getItem('fdata'));
document.getElementById("flogview").innerHTML = fdataload;
});
Now it saves but I have another problem, why it is replacing data every time I click showlogsf button??

Object handling in Chrome/FF?

I have this code:
$('.gBook').click(function(){
var values = [];
var getDiff = $('#totalPrice').attr("data-value");
var i = 0;
$('td[data-check="true"]').each(function(){
var valueToPush = { };
valueToPush["price"] = $(this).attr("data-price");
valueToPush["id"] = $(this).attr("data-id");
valueToPush["diff"] = getDiff;
values.push(valueToPush);
i++;
});
var arrayToSend = {values};
$.post( '<?php echo PATH;?>ajax/updateRoom.php',arrayToSend, function(data){
if(data != "ERROR"){
$('#all-content').html(data).css("overflow-y","auto");
}else{
alert("ERROR");
}
});
});
In Chrome, this line gives an error var arrayToSend = {values}; (Uncaught SyntaxError: Unexpected token }) In Firefox everything is fine.
I guess it's because of the rather "loose" error handling of FF, but how am I doing it correctly?
I tried to initialize the object with var arrayToSend = new Object(); before the $.each, but that gives an empty array after POST.
Where is my mistake?
try this
var arrayToSend = {optionsChosen:values};
Then in php or whatever you use for data handling look for the POST variable optionsChosen.
What you did was try to make an Object with parameter array = nothing
You basically did this in your code. It doesn't take an expert to see whats wrong with this statement.
arrayToSend = new function() {
this.(new Array(1,2,3)); // This is cringeworthy if you see it like this.
}
In the example I gave it translates to this:
arrayToSend = new function() {
this.optionsChosen = new Array(1,2,3);
}

How to use ajax filter

I'm trying to filter out some values from an AJAX call. Here's what I have tried:
var year = 200908; // for example
var resultArray = data.filter(function (a) {
return a.proddate == year;
});
var firstTask = resultArray[0];
var lastTask = resultArray[resultArray.length - 1];
data is coming from success function in an ajax call. But I'm getting this error:
JavaScript runtime error: Object doesn't support property or method 'filter'
Here is a sample of the returned data:
"[{
"tasknum":6,
"dependtask":5,
"jobname":"prc",
"proddate":"200908",
"activity":"Pr‌​elim",
"groupname":"CNSPROD-EST",
"parametername":"n/a",
"parametervalue":"n/a"
}]"
Any ideas?
First, try doing a console.log on data and verify what exactly you're retrieving. filter only works on arrays so this would work:
var resultArray = [1,2,3].filter(function(a) {
return a > 2;
});
But this will not:
// "Object doesn't support property or method 'filter'"
var resultArray = {1: true, 2: true, 3: true}.filter(function() { ... });
I suspect that data is not the variable assigned to the response. Or perhaps you haven't parsed response to js array from JSON using JSON.parse()
Your code works fine here:
DEMO

Code not getting expected values when reading URL parameters

I've been racking my brain about this and I can not figure out why this isn't working.
I have a link that looks like this:
http://exampledomain.com/page.html?var1=42&var2=hello
and page.html is calling a javascript page that says:
alert(var1);
alert(var2);
But when I test the page all I get is function Number() { [native code] }
Anybody know what I could be going wrong?
Use this function:
var GET = function(query){
var varsArray = [],
url = window.location.search.match(/[^\?\&]+/g),
vars = [];
for(var i=0;i<url.length;i++)
if(/\=/.test(url[i]))
vars.push(url[i]);
for(var i=0;i<url.length;i++){
var This = url[i].split('=');
varsArray[This[0]] = This[1];
}
return query ? varsArray[query] : (varsArray || '');
}

Javascript array into jQuery .post AJAX call

I have a JAVASCRIPT array that looks like this:
postarray['min_price'] = 120000;
postarray['max_price'] = 150000;
I'm trying to pass this to an AJAX call via jQuery .post function so that the .PHP file gets it in this format:
$_REQUEST['query']['min_price'] = 120000;
$_REQUEST['query']['max_price'] = 150000;
So far I've tried:
$.post("ajax_findproperties.php", {query: postarray},
function(data){
// processing function with JSON result
}
,'json');
But I've had no luck. I even tried changing the var postarray to query and then tried query.serialize() in place of the bracketed variable block, but with no luck either.
When I check my status on Firebug, the AJAX call has absolutely no POST vars set whatsoever - complete blank.
The javascript array is not an array, it's an object. Define it before:
var postarray = {};
postarray['min_price'] = 120000;
postarray['max_price'] = 150000;
or replace with:
var postarray = {
min_price: 120000,
max_price: 150000
};
Now the JSON.stringify works:
alert(JSON.stringify(postarray));
Also see this example.
But this object should also be send without JSON.stringify():
$.post("ajax_findproperties.php", {query: postarray}, ... );
Have you tried converting it with JSON.stringify(); and then doing a json_decode(...); in the PHP script?
Try this solution : add [] to your query key
$.post("ajax_findproperties.php", { 'query[]': postarray },
function(data) { },
'json');
Source : http://api.jquery.com/jQuery.post/#example-2

Categories

Resources