Unable to access nested value in JSON string from ajax response - json

I understand there's multiple questions on this but none of the answers are working for me
I return an enocoded JSON string from PHP through a .ajax response
$.ajax({
url : ajax_object.ajax_url,
type : 'post',
data : {
action: 'rt_check_for_new_messages',
uid : $uid,
pid : $pid,
sessionStart : $sessionStart,
room_array :$roomArray,
messages_array : $messagesArray,
},
dataType : "json",
success: function(data) {
console.log(data);
In the console I get
{html: "[]", messageData: "[{"roomName":"master","msgID":1638}, {"roomName":"beta","msgID":1640}]"}
So now I need to access "roomName" so I can filter out matches
var matches = $(data).filter(function(i,n) {
return n.messageData[].roomName === 'master';
});
console.log(matches);
I tried every combination I could find

n.messageData[].roomName === 'master'; is not valid JavaScript syntax.
I believe this is what you need to do:
var matches = $(JSON.parse(data.messageData)).filter(function(i,n) {
return n.roomName === 'master';
});
Note that I am parsing data.messageData here - based on the consle output you've shown us, it looks like messageData is a string containing JSON, and not an array.

Related

My Ajax script not work with datatype json

In my codes, i could post data without error. but i cant return data from php file to show in my html tag. If i delete dataType: 'json', it works fine but as you know i cant get data. I get this error while datatype = json
error : {"readyState":4,"responseText":"<head>\n<meta charset=\"UTF-8\">\n</head>\n-1","status":200,"statusText":"parsererror"}
My ajax;
$(document).ready(function(){
// like and unlike click
$(".like, .unlike").click(function(){
var id = this.id; // Getting Button id
var split_id = id.split("_");
var text = split_id[0];
var postid = split_id[1]; // postid
// Finding click type
var type = 0;
if(text == "like"){
type = 1;
}else{
type = 0;
}
// AJAX Request
$.ajax({
url: 'likeunlike.php',
type: 'post',
data: {baslikid:postid,type:type},
dataType: 'json',
success: function(data){
var likes = data['likesonuc'];
$("#sonuc_"+postid).text(likes); // setting likes
if(type == 1){
$("#like_"+postid).css("color","#ffa449");
$("#unlike_"+postid).css("color","lightseagreen");
}
if(type == 0){
$("#unlike_"+postid).css("color","#ffa449");
$("#like_"+postid).css("color","lightseagreen");
}
},
error: function(data){
alert("error : " + JSON.stringify(data));
}
});
});
});
My php file(I didnt share above to avoid confusion. I get int result from $likesonuc)
$likesonuc= $total_likes - $total_unlikes;
echo json_encode($likesonuc);
In your response, you can see that the body you're returning from PHP:
<head>\n<meta charset=\"UTF-8\">\n</head>\n-1
...is not JSON. It looks like you're writing out the head of the HTML somewhere and then the JSON number -1. You need to send just the JSON in your response or it can't be parsed as JSON.

How to get data from json response

target url
function purchasetable(Request $request){
$material = $request->get('query');
$unitprice = DB::table('materials')->where('name',$material)->select('unit_price','id')->get();
echo json_encode($unitprice);
}
code segment on the view
$('#add-btn').click(function() {
var material = $('select[name="material"]').val();
var quantity = $('input[name="qty"]').val();
var _token = $('input[name="_token"]').val();
alert(material);
$.ajax({
url: "{{ route('autocomplete.purchasetable') }}",
method: "POST",
data: {
query: material,
_token: _token
},
success: function(data) {
//console.log(data);
data = JSON.parse(data);
console.log(data);
}
});
});
Console output
I want to access 'id' and 'unit_price' on my view how can I do that explain me.
Thanks
As you are using jQuery and also your response is an array, then you can iterate the array like this
$.each(data, function(key, value) {
console.log(value.id, value.unit_price);
});
Your output seems to be an Array of Objects.
Any array value can accessed used the " [] " notation.
Since the array contains objects hence it can be accessed using the " . " operator
hence
data[0].id and data[0].valuewill give you the desired result.
[0] -> indicates the array position, which is 0 in this case and
.id - > indicates the object name you want to access.

Wrong data format for store loadData method ExtJS

I want to call JSON data as much as the amount of data in the store. Here is the code:
storeASF.each(function(stores) {
var trano = stores.data['arf_no'];
Ext.Ajax.request({
results: 0,
url: '/default/home/getdataforeditasf/data2/'+trano+'/id/'+id,
method:'POST',
success: function(result, request){
var returnData = Ext.util.JSON.decode(result.responseText);
arraydata.push(returnData);
Ext.getCmp('save-list').enable();
Ext.getCmp('cancel-list').enable();
},
failure:function( action){
if(action.failureType == 'server'){
obj = Ext.util.JSON.decode(action.response.responseText);
Ext.Msg.alert('Error!', obj.errors.reason);
}else{
Ext.Msg.alert('Warning!', 'Server is unreachable : ' + action.response.responseText);
}
}
});
id++;
});
storeARF.loadData(arraydata);
StoreASF contains data[arf_no] which will be used as a parameter in Ajax request url. StoreASF could contain more than one set of the object store, so looping is possible. For every called JSON data from request would be put to array data, and after the looping is complete, I save it to storeARF with the loadData method.
The problem is, my data format is wrong since loadData can only read JSON type data. I already try JSON stringify and parse, but couldn't replicate the data format. Any suggestion how to do this? Thank you.
Rather than using Ext.util.Json.decode(), normalize the data in success() method using your own logic. For example:
success: function (response) {
console.log(response);
var myData = [];
Ext.Array.forEach(response.data, function (item) {
myData.push({
name: item.name,
email: item.email,
phone: item.phone
});
});
store.load();
}

Parsing JSON object sent through AJAX in Django

This is my code creating a json file:
$( ".save" ).on("click", function(){
var items=[];
$("tr.data").each(function() {
var item = {
itemCode : $(this).find('td:nth-child(1) span').html(),
itemQuantity : $(this).find('td:nth-child(4) span').html()
};
items.push(item);
});
});
Now the json object looks like:
[{"itemcode":"code1","itemquantity":"quantity1"},{"itemcode":"code2","itemquantity":"quantity2"},...]
My question is how do I parse this data in Django view?
Following is my AJAX function for reference:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ bill_details: JSON.stringify(items),
calltype:'save'},
dataType: "application/json", // datatype being sent
success : function(jsondata) {
//do something
},
error : function() {
//do something
}
});
}());
Since I'm sending multiple AJAX request to the same view, I need the 'calltype' data as well.
Thanks you on your answer!! BTW, I badly need to know this simple stuff, which I'm missing
This is my code snippet for parsing:
if (calltype == 'save'):
response_data = {}
bill_data = json.loads(request.POST.get('bill_details'))
itemcode1=bill_details[0]['itemCode']
#this part is just for checking
response_data['name'] = itemcode1
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
The error being raised is
string indices must be integers
Request your help
For your reference, this is my POST response (taken from traceback):
bill_details = '[{"itemCode":"sav","itemQuantity":"4"}]'
calltype = 'save'
csrfmiddlewaretoken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
EDITED Django View
This is my edited view:
if (calltype == 'save'):
bill_detail = request.POST.get('bill_details')
response_data = {}
bill_data = json.loads(bill_detail)
itemcode1=bill_data[0]['itemCode']
#this part is just for checking
response_data['name'] = itemcode1
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
I fail to understand the problem. SO, to solve it, my question: what is the datatype of the return for get call and what should be the input datatype for json.loads. Bcoz the error being shown is json.loads file has to be string type!! (Seriously in limbo)
Error:
the JSON object must be str, not 'NoneType'

Parse JSON from JQuery.ajax success data

I am having trouble getting the contents of JSON object from a JQery.ajax call. My call:
$('#Search').click(function () {
var query = $('#query').valueOf();
$.ajax({
url: '/Products/Search',
type: "POST",
data: query,
dataType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
for (var x = 0; x < data.length; x++) {
content = data[x].Id;
content += "<br>";
content += data[x].Name;
content += "<br>";
$(content).appendTo("#ProductList");
// updateListing(data[x]);
}
}
});
});
It seems that the JSON object is being returned correctly because "alert(data)" displays the following
[{"Id": "1", "Name": "Shirt"}, {"Id": "2", "Name":"Pants"}]
but when I try displaying the Id or Name to the page using:
content = data[x].Id;
content += "<br>";
content += data[x].Name;
content += "<br>";
it returns "undefined" to the page. What am I doing wrong?
Thanks for the help.
The data is coming back as the string representation of the JSON and you aren't converting it back to a JavaScript object. Set the dataType to just 'json' to have it converted automatically.
I recommend you use:
var returnedData = JSON.parse(response);
to convert the JSON string (if it is just text) to a JavaScript object.
It works fine,
Ex :
$.ajax({
url: "http://localhost:11141/Search/BasicSearchContent?ContentTitle=" + "تهران",
type: 'GET',
cache: false,
success: function(result) {
// alert(jQuery.dataType);
if (result) {
// var dd = JSON.parse(result);
alert(result[0].Id)
}
},
error: function() {
alert("No");
}
});
Finally, you need to use this statement ...
result[0].Whatever
One of the way you can ensure that this type of mistake (using string instead of json) doesn't happen is to see what gets printed in the alert. When you do
alert(data)
if data is a string, it will print everything that is contains. However if you print is json object. you will get the following response in the alert
[object Object]
If this the response then you can be sure that you can use this as an object (json in this case).
Thus, you need to convert your string into json first, before using it by doing this:
JSON.parse(data)
Well... you are about 3/4 of the way there... you already have your JSON as text.
The problem is that you appear to be handling this string as if it was already a JavaScript object with properties relating to the fields that were transmitted.
It isn't... its just a string.
Queries like "content = data[x].Id;" are bound to fail because JavaScript is not finding these properties attached to the string that it is looking at... again, its JUST a string.
You should be able to simply parse the data as JSON through... yup... the parse method of the JSON object.
myResult = JSON.parse(request.responseText);
Now myResult is a javascript object containing the properties that were transmitted through AJAX.
That should allow you to handle it the way you appear to be trying to.
Looks like JSON.parse was added when ECMA5 was added, so anything fairly modern should be able to handle this natively... if you have to handle fossils, you could also try external libraries to handle this, such as jQuery or JSON2.
For the record, this was already answered by Andy E for someone else HERE.
edit - Saw the request for 'official or credible sources', and probably one of the coders that I find the most credible would be John Resig ~ ECMA5 JSON ~ i would have linked to the actual ECMA5 spec regarding native JSON support, but I would rather refer someone to a master like Resig than a dry specification.
Try the jquery each function to walk through your json object:
$.each(data,function(i,j){
content ='<span>'+j[i].Id+'<br />'+j[i].Name+'<br /></span>';
$('#ProductList').append(content);
});
you can use the jQuery parseJSON method:
var Data = $.parseJSON(response);
input type Button
<input type="button" Id="update" value="Update">
I've successfully posted a form with AJAX in perl. After posting the form, controller returns a JSON response as below
$(function() {
$('#Search').click(function() {
var query = $('#query').val();
var update = $('#update').val();
$.ajax({
type: 'POST',
url: '/Products/Search/',
data: {
'insert': update,
'query': address,
},
success: function(res) {
$('#ProductList').empty('');
console.log(res);
json = JSON.parse(res);
for (var i in json) {
var row = $('<tr>');
row.append($('<td id=' + json[i].Id + '>').html(json[i].Id));
row.append($('<td id=' + json[i].Name + '>').html(json[i].Name));
$('</tr>');
$('#ProductList').append(row);
}
},
error: function() {
alert("did not work");
location.reload(true);
}
});
});
});
I'm not sure whats going wrong with your set up. Maybe the server is not setting the headers properly. Not sure. As a long shot, you can try this
$.ajax({
url : url,
dataType : 'json'
})
.done(function(data, statusText, resObject) {
var jsonData = resObject.responseJSON
})
From the jQuery API: with the setting of dataType, If none is specified, jQuery will try to infer it with $.parseJSON() based on the MIME type (the MIME type for JSON text is "application/json") of the response (in 1.4 JSON will yield a JavaScript object).
Or you can set the dataType to json to convert it automatically.
parse and convert it to js object that's it.
success: function(response) {
var content = "";
var jsondata = JSON.parse(response);
for (var x = 0; x < jsonData.length; x++) {
content += jsondata[x].Id;
content += "<br>";
content += jsondata[x].Name;
content += "<br>";
}
$("#ProductList").append(content);
}
Use
dataType: 'json'
In .NET you could also return Json(yourModel) in your action method/API controller.
And parse the returned JSON as follows in the Jquery .ajax:
if you've a complex object: navigate to it directly.
success: function (res) {
$.each(res.YourObject, function (index, element) {
console.log(element.text);
console.log(element.value);
});
});