from controller Json is returned and in function i get an object which contains
{
"readyState":4,
"responseText":"{\"Success\":0,\"Failed\":0}",
"responseJSON":{
"Success":0,
"Failed":0
},
"status":200,
"statusText":"OK"
}
How can I take Success and Failed values?
data.Successand JSON.parse(data) is not working
You dont need to parse that because that IS already an object:
var obj = {"readyState":4,"responseText":"{\"Success\":0,\"Failed\":0}","responseJSON":{"Success":0,"Failed":0},"status":200,"statusText":"OK"};
var failed = obj.responseJSON.Failed;
var success = obj.responseJSON.Success;
var json_data = '{"readyState":4,"responseText":"{\"Success\":0,\"Failed\":0}",
"responseJSON":{"Success":0,"Failed":0},"status":200,"statusText":"OK"}';
var obj = JSON.parse(json_data);
alert(obj.responseJSON.Success); // for success that in responseJSON
alert(obj.responseJSON.Failed);
Thanks :)
Related
I try to take object from my controller, when I console.log(response) it show the value correctly which is in
[
{
"itemValue":100,
"itemUnit":"2"
}
]
unfortunately I try to use the object like response.itemValue when I console it show undefined. I try var object = response. during the console it show the same value. Please I want to use the response data.
if(itemID){
$.ajax({
type:'POST',
url:'?syspath=ajax&controller=ajax&action=getActItemDose',
data: { 'itemId': itemID, 'itemType': itemType },
success:function(response){
// var obj = jQuery.parseJSON(data);
console.log(response);
var object = response;
var value = object.itemValue;
var unit = object.itemUnit;
console.log(object);
console.log(value);
}
});
}
This is controller where I encode the object into Json
$row = $getProcess->fetch();
$object[] = array(
'itemValue' => $row['each_dose'],
'itemUnit' => $row['unit_dose']
);
echo json_encode($object);
I recommend using the jQuery library. For parsing JSON, simply do
var obj = JSON.parse(data);
// Accessing individual value from JS object
alert(obj.itemValue);
alert(obj.itemUnit);
It worked, by changing this few item
$object[] = array();
into
$object = array();
and JSON.parse(data)
var object = JSON.parse(data);
value = object.itemValue;
unit = object.itemUnit;
Your response is an array. So you need to access it like
response[0].itemValue
or you can loop through the array
response.forEach(element => {
console.log(element.itemValue);
});
Below is the example
const response = JSON.parse(`[
{
"itemValue":100,
"itemUnit":"2"
}
]
`);
response.forEach(element => {
console.log(element.itemValue);
});
In javascript:
var post = {};
post.arr = ["hi", "hello"];
$.post("http://localhost:8000/test", post);
and in node:
var body = "";
request.on('data', function (data) {
body += data
});
request.on('end', function (data) {
var post = qs.parse(body);
console.log(post); // I see { 'arr[]': ['hi', 'hello'] };
console.log(post.arr); // undefined
}
Any idea what might have caused this?
Based on your comments, it looks like somehow the map key is literally arr[]. Try console.log(post['arr[]']);
jQuery will modify the name of arrays as #MikeC pointed out. More info here: https://stackoverflow.com/a/5888057/1861459
How to access values of localStorage.getItem(JSONObj)
var result = JSON.parse(localStorage.getItem("resultData")); // ---In Ajax SuccessCallBack I have written var parseResult = JSON.stringify(result);localStorage.setItem("resultData",parseResult); ---
alert("Result :"+result); // I get proper result here
var obj_res = result.getTest_Data; // PHP - $data['getTest_Data'] = $query->result(); ----// tried with result.getTest_Data[0] , result.["getTest_Data"]
//alert(obj_res);// Undefined
$("#txtTTDNo1").val(obj_res.QC_TTDNo1); // Assigning Value to Text box
Getting error :
"Can not read property "QC_TTDNo1" of undefined.
Resolved. I had to again parse JSON as I was JSON.stringify() while localStorage.setItem("")...... var data1 = JSON.parse(result); var data = data1.getTest_Data;
I missed a lot of time that to resolve this problem but unlucky. I know how to render d3 tree with external file, but how to do that with generated object. I'm getting Json object thru this code:
$.when($.getJSON('data/clinical.json'), $.getJSON('data/industry.json'))
.then(function (a, b) {
return $.extend(a[0], b[0]);
})
.then(function (data) {
var json = JSON.stringify(data);
console.log('['+ json +']');
and have added json to d3.json
treeJSON = d3.json(json, function (error, treeData) {
so whole part of code looks like:
function load() {
$.when($.getJSON('data/clinical.json'), $.getJSON('data/industry.json'))
.then(function (a, b) {
return $.extend(a[0], b[0]);
})
.then(function (data) {
var json = JSON.stringify(data);
console.log('['+ json +']');
// Get JSON data
treeJSON = d3.json(json, function (error, treeData) {
the most interesting part is that console log self defined such as right string:
[{"text":"Alas","icon":"icons/tree.png","children":[{"text":"CDISC","children":[{"text":"SDTM","children":[{"text":"SDTM 3.1.1","icon":"icons/file.png"},{"text":"SDTM 3.1.3","icon":"icons/file.png"},{"text":"SDTM 3.2","icon":"icons/file.png"}]},{"text":"ADaM"},{"text":"CDASH"}]},{"text":"CDISC"},{"text":"BRIDG"}]}]
but I'm still getting an error:
GET http://localhost:63342/testMerg/%7B%22text%22:%22Alas%22,%22icon%22:%22…SH%22%7D]%7D,%7B%22text%22:%22CDISC%22%7D,%7B%22text%22:%22BRIDG%22%7D]%7D 404 (Not Found)
I've tried to use string method from some example which I found somewhere here:
.then(function (data) {
var json = JSON.stringify(data);
// Get JSON data
treeData = JSON.parse( data );
but got an error
Uncaught SyntaxError: Unexpected token o
so I give up... could anybody help me?
The problem arises because data is an Object and your trying to parse the object. But JSON.parse function expects a string as the parameter.
You can either directly assign treeData = data. (No need for parsing).
Or else you should try stringifying the object and then parse the stringified json.
var json = JSON.stringify(data);
treeData = JSON.parse(json);
var data = {"text":"Alas","icon":"icons/tree.png","children":[{"text":"CDISC","children":[{"text":"SDTM","children":[{"text":"SDTM 3.1.1","icon":"icons/file.png"},{"text":"SDTM 3.1.3","icon":"icons/file.png"},{"text":"SDTM 3.2","icon":"icons/file.png"}]},{"text":"ADaM"},{"text":"CDASH"}]},{"text":"CDISC"},{"text":"BRIDG"}]};
//treeData = data;
json = JSON.stringify(data);
console.log(JSON.parse(json));
I'm trying to merge two objects I receive as JSON via Ajax, but I can not access the variable and declaring it global. What am I doing wrong?
var parametroswatcher = {
// asinid: $('#rate').attr('data-id'),
asinid: GetURLParameter('asin'),
mod: '0'
};
var post = $.post("../../likes/like.php", parametros, 'json');
post.done(function( data ) {
postdata = jQuery.parseJSON(data);
});
var postwatch = $.post("../../watcher/watch.php", parametroswatcher, 'json');
postwatch.done(function( data ) {
postwatchdata = jQuery.parseJSON(data);
});
var postmerge = $.extend(postdata,postwatchdata);
console.log(postmerge);
The answer of postdata = jQuery.parseJSON(data) should be:
{"resplike":"needlogin"}.
And the answer of postwatchdata = jQuery.parseJSON(data) should be:
{"respwatch":"needlogin"}.
But to access the console, instead of getting postdata and postwatchdata merged, I get an empty object.
Object {} product.js:61
Edit:
I want when post and postwatch done, use data in product function.
The answer of postdata = jQuery.parseJSON(data) should be: {"resplike":"needlogin"}.
And the answer of postwatchdata = jQuery.parseJSON(data) should be: {"respwatch":"needlogin"}.
function product(data){
var obj = jQuery.parseJSON(data);
if (obj.resplike=='like'){
var respuesta = 'No te gusta';
}
else if(obj.resplike=='dislike'){
var respuesta = 'Te gusta';....blabla
I want to get in obj: {"resplike":"needlogin", "respwatch":"needlogin"}
You cannot handle the result of an asynchronous call like that. All operations done on a async function call must be done within the callbacks of that async method. read more about this in answer
var parametroswatcher = {
// asinid: $('#rate').attr('data-id'),
asinid: GetURLParameter('asin'),
mod: '0'
};
var post = $.post("../../likes/like.php", parametros, 'json');
var postwatch = $.post("../../watcher/watch.php", parametroswatcher, 'json');
$.when(post, postwatch).then(function(arg1, arg2){
var postmerge = $.extend(arg1[0], arg2[0]);
console.log(postmerge);
})
Also since you need to wait for the responses from two different requests you can use $.when() which will back the success handlers once all the passed promises are resolved.