How to use ajax filter - javascript

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

Related

javascript and jquery weird array object

i have stuck on this weird thing for 03 day and don't understand why it created that object "id[]" when jquery sending data to server. i tried to push the element to new array so i can get the normal {id: 'value01'} but it does not work, the server response is still showing the weird array in object: {'id[]': 'value01}. i am stuck on this because if i do var id = masoid[0] it work as the server show normal {id: 'value01'} but i need to filter the array before sending it. Thank you for your time
here is jquery code
function onlyUnique(value, index, self) {
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
if(isNumeric(value)){
return self.indexOf(value) === index;
}
};
// var id = {masoid.filter(onlyUnique)};
// var idDaFilter = new Array;
// id.forEach(element => {
// idDaFilter.push(element);
// });
var id = masoid.filter(onlyUnique);
console.log(id);
$.ajax({
url: deleteUrl,
type: 'POST',
data: {id:id},
});
the server response:
server code
let id = JSON.parse(JSON.stringify(req.body));
console.log(req.body);
You're using the method filter in the variable id. This method return a new array (shallow of original), so this is why you're getting 'id[ ]' on response. Use find instead.
var id = masoid.find(onlyUnique);
See an example here.
When you set var id = masoid[0] you're getting the first element of that array, than it works.
See more details on documentation find method and filter method

Can't get the value of json object

I have this json object, and i want to get the value of the error but it always returning me an undefined result.
Here is the json object
{"isValid":false,"errors":["Username is required.","Password is required."]}
my code is:
success: function (response) {
var JSONstring = JSON.stringify(response);
var JSONobject = JSON.parse(JSONstring);
alert(JSONstring);
alert(JSONobject);
console.log(JSONobject);
var _result = JSONobject.errors;
i have also tried:
var _result = JSONobject[0]['errors'];
var _result = JSONobject['errors'][0];
but still i can't access the value.
If you already have access to the JSON object you can work with it without manipulation. If your question was also looking to get it in that form, see this StackOverflow answer for how to format your request.
success: function (response) {
// Assuming response = {"isValid":false,"errors":["Username is required.","Password is required."]}
// Directly access the property errors
var errors = response.errors;
console.log(errors); // ["Username is required.","Password is required."]
JSFiddle

Unable to access JSON Element in Javascript via Object.property

I am unable to access a simple JSON Element from a JSON Structure that looks like:
{
"ACTION": "AA",
"MESSAGE": "Customer: 30xxx Already Approved on 2017/01/01"
}
I get the data in JSON Format but when i do data.ACTION or data.MESSAGE i get Undefined as the output.
By doing case sensitive also, its not working( Image attached )
var url = base + query;
var getJSON = function (url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.withCredentials = true;
xhr.onload = function () {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
getJSON(url).then(function (data) {
console.log(data); //Getting JSON Data
var output = JSON.stringify(data);
var obj = JSON.parse(output.replace(/ 0+(?![\. }])/g, ' '));
console.log(output);
console.log(obj.message); //Here getting UNDEFINED
}, function (status) { //error detection....
alert('Something went wrong.');
});
Console:
{"ACTION":"AA","MESSAGE":"Customer No. 0000030332 Already Approved On 20170113"}
stringify returns the following
{\"ACTION\":\"AA\",\"MESSAGE\":\"Customer No. 0000030332 Already Approved On 20170113\"}"
EDITED. I first thought the error was due to parsing, given the print. -.-
Solution:
When you print the output, obj it's still a string, not an object. So it is OK at that point.
Your "undefined" property message should be replaced by MESSAGE.
Instead of console.log(obj.message); just use console.log(obj.MESSAGE);
Also. An example of parsing JSON:
var myJson = '{"ACTION":"AA","MESSAGE":"Customer No. 0000030332 Already Approved On 20170113"}';
console.log(myJson); // This prints the literal string
console.log(JSON.parse(myJson)); // this prints an "object"
obj.message property is not defined and when you try to get the property which is not defined on an object, you get undefined.
Javascript is case sensitive. You should try obj.MESSAGE instead to get the property value. Also, to check if a property exists on an object you can make use of object.hasOwnProperty([propName]) method to check if a property exists on a object or not.
EDIT 1: Try running the following code snippet. JSON data string is parsed before accessing the property.
var jsonString = "{\"ACTION\":\"AA\",\"MESSAGE\":\"Customer No. 0000030332 Already Approved On 20170113\"}";
var obj = JSON.parse(jsonString);
console.log(obj.MESSAGE);
data already is a JSON string, there's no need to JSON.stringify it (which returns a string with a JSON-encoded string literal). Parsing it into output only leads to a string again, which has no properties. You should use
console.log(data);
var obj = JSON.parse(data);
console.log(obj);
obj.MESSAGE = obj.MESSAGE.replace(/ 0+(?![\. }])/g, ' ');
(notice the proper casing of the property name)
You can try:
var jsonObject = data.data;
console.log(jsonObject.ACTION)

JSON.stringify not working - undefined

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.

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