Using jquery to parse items from a JSON response - javascript

I am using PHP and Ajax to parse some JSON. The PHP is creating the array like this.
$myObj->pid = $_POST["parentid"];
$myObj->comp = $comp;
$myObj->colour = $statuscolour;
$myJSON = json_encode($myObj);
header('Content-Type: application/json');
echo $myJSON;
I use the following jquery code
$.ajax({
type: "POST",
dataType: "json",
url: "msstatup.php",
data: data
}).done(function(msg) {
var response = jQuery.parseJSON(JSON.stringify(msg));
console.log(response);
pid = response[0].pid;
console.log('id = ' + pid);
});
I can see the output from the first console.log as
Object {pid: "p1", comp: 20, colour: "red"}
However I cannot extract the individual variables, it gives the message
Uncaught TypeError: Cannot read property 'pid'
How can I extract the variable?

You've made this more complicated than it needs to be. msg is already an object, which you then convert to a string and back to an object with stringify and parseJSON. And then you try to use it like an array, when it is an object.
Try this:
$.ajax({
type: "POST",
dataType: "json",
url: "msstatup.php",
data: data
}).done(function(msg) {
var pid = msg.pid;
console.log('id = ' + pid);
});

You are returning an object, not an array.
Also it makes no sense to stringify the data object and parse that string back to object again
Try
var pid = msg.pid;
console.log('id = ' + pid);

First of all, it can't imagine why it would be neccessary to first stringify, then parse the JSON response.
Second, you are trying to access response[0] as if it were an array, which it isn't. You can simply use
response.pid;
To access the object key.
As you don't need to stringify then parse the response, you can just access msg directly, so it all comes down to
$.ajax({
type: "POST",
dataType: "json",
url: "msstatup.php",
data: data
}).done(function(msg) {
console.log(msg.pid);
});

Related

Javascript object properties undefined after ajax request

I've made an ajax call which has returned a json string from a .Net JsonConvert.SerializeObject() call, the json is automatically parsed into an object at the browser but I am currently unable to access the properties without "undefined" being returned.
My current json string being returned is (removed bulk of byte array):
"[{\"filename\":\"\",\"size\":6,\"csize\":\" 5.85 KB\",\"extfile\":\"/9j/4AAQSkZJRgABAQEASABIAAD/2wBDA....AAAAAAAAAAAf//Z\"}]"
I've validated this and it's all fine.
My javascript is:
function GetItemImage() {
let kditem = $("#txtItem").text();
let url = GetUrl();
$.ajax({
url: url,
type: "POST",
data: JSON.stringify({
"kditem": kditem
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data != null) {
$("#ImgItem").attr("src", "data:image/png;base64,'" + data.extfile + "'");
}
}
});
}
I have made sure it is definitely an object. I've tried accessing as data.extfile, data["extfile"], passing extfile in as a byte array and then accessing that but it is always coming up as "undefined". In desperation I even tried accessing indexes, iterating through the object etc. and still nothing.
I have a feeling that there is an issue in the json string which is preventing it from converting properly but I can't see it as I haven't worked much with json. Could someone point out where I'm going wrong?
Solution
Javascript was parsing the response into an object with a single property "data.d", parsed data.d and that created the object correctly.
function GetItemImage() {
let kditem = $("#txtItem").text();
let url = GetUrl();
$.ajax({
url: url,
type: "POST",
data: JSON.stringify({
"kditem": kditem
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data != null && data.d != null) {
let imgData = JSON.parse(data.d);
$("#ImgItem").attr("src", "data:image/png;base64," + imgData[0].extfile);
}
}
});
}
basically if the string that you pasted is the response (data), when using JSON.parse() it converts into an array , so you should use it like that.
const stringResponse = "[{\"filename\":\"\",\"size\":6,\"csize\":\" 5.85 KB\",\"extfile\":\"/9j/4AAQSkZJRgABAQEASABIAAD/2wBDA....AAAAAAAAAAAf//Z\"}]"
const parsedResponse = JSON.parse(stringResponse);
console.log(parsedResponse)
const entry = parsedResponse[0];
console.log(entry.extfile)
so basically, you need to do:
data[0].extfile
Since the console.log(data) statement returns:
{d: "[{"filename":"","size":6,"csize":" 5.85 KB",…AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf//Z"}]"}
The data you are actually trying to obtain is contained in a JSON string contained in the d property of the data received. If you were to parse the string and then access the extfile property you would have your data:
var actualData= JSON.parse(data.d);
var extfile = actualData[0].extfile;
Don't know if this will help but here it is:
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
http://api.jquery.com/jquery.ajax/
Also the data is an Array, maybe grab the first object in the array data[0].extfile.
I'm thinking it maybe reworked as such:
function GetItemImage() {
let kditem = $("#txtItem").text();
let url = GetUrl();
$.ajax({
url: url,
type: "POST",
data: JSON.stringify({
"kditem": kditem
}),
dataType: "json",
contentType: "application/json; charset=utf-8"
}).done(function(data){
if (data != null) {
$("#ImgItem").attr("src", "data:image/png;base64,'" +
data[0].extfile + "'");
}
});
}

Sending Json Array in POST request for JavaScript

I am having trouble in sending a JSON array in an AJAX call. Following is my Code
var company_name = $('input#company_name').val();
var company_localname = $('input#company_localname').val();
var companytype = $('#companytype').val();
if (companytype == 'retailer') {
var bank_name = $('input#bank_name').val();
var account_title = $('input#account_title').val();
var business_nature = $('input#business_nature').val();
var gross_sales = $('input#gross_sales').val();
}
After getting all the values I am storing the data in Json like the following
var jsonArray = [];
jsonArray["company_name"] = company_name;
jsonArray["company_localname "] = company_localname;
if (companytype == 'retailer') {
jsonArray["bank_name"] = bank_name;
jsonArray["account_title"] = account_title;
jsonArray["business_nature"] = business_nature;
jsonArray["gross_sales"] = gross_sales;
}
Now for sending the jsonArray in Ajax call
$.ajax({
url : url,
type : "POST",
dataType : 'json',
contentType : 'application/json; charset=UTF-8',
data : JSON.stringify(jsonArray),
success : function(response) {
//Some Code here
}
});
Please help me sending data. Or tell me if I am making any mistake here. Thank you
In JavaScript / JSON arrays are 0 based indexed data structures. What you are using here is more like a Map:
var jsonArray = [];
jsonArray["company_name"]=company_name ;
In JavaScript you cannot use arrays like this (well you can, but it is probably not what you want). For a data structure like a map that maps strings to objects rather then an index to objects, just use an object.
Or in short: Use var jsonArray = {}; rather than var jsonArray = []; The {} will create an object that you can assign properties to like you did. And JSON.stringify will correctly translate this into a JSON string like this:
{ "property": value, "otherProperty", otherValue }
Do something like this.
$.ajax({
url: url,
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data: JSON.parse(JSON.stringify(jsonArray)),
success: function(response) {
//Some Code here
}
});
The JSON.parse() method parses a string as JSON, optionally transforming the value produced by parsing. Read more about JSON.parse() method
The JSON.stringify() method converts a JavaScript value to a JSON string. Read more about JSON.stringify() method
Here simply you can send an array and Parse it in server side.
$.ajax({
url : url,
type : "POST",
dataType : 'json',
data : jsonArray,
success : function(response) {
//Some Code here
}
});

Convert json object to string

I have the following controller:
public function getPrice()
{
$id = $this->input->post('q');
$data['price'] = $this->emodel->get_peUniformPrice($id);
echo json_encode($data);
}
which outputs this:
"{\"price\":[{\"Price\":\"250\"}]}"
How can I make it like 250? My jQuery:
function showPrice(size) {
$.ajax({
type: "POST",
url: "<?php echo site_url('enrollment/getPrice/');?>",
data: {
q: size
},
success: function(data) {
$("#txtpeUniform").val(data);
},
});
}
I can see that you are using jQuery.. if you want to turn the json object into a javascript object you could do something like
var convertedObject = $.parseJSON($data);
alert(convertedObject.Price);
what this effectively does is converts your Json string into a javascript object which you can reference the properties out of and the get the value from these properties.. let me give you another example
var jsonString = {'Firstname':'Thiren','Lastname':'Govender'};
var jObject = $.parseJSON(jsonString);
console.log(jObject.Firstname) // this will output Thiren.
console.log(jObject.Lastname) // this will output Govender.
modify your code
function showPrice(size) {
$.ajax({
type: "POST",
url: "<?php echo site_url('enrollment/getPrice/');?>",
data: {
q: size
},
success: function(data) {
console.log(data); // make sure this is returning something..
$("#txtpeUniform").val(data);
},
});
}
I hope this helps you..
Regards
The $.ajax method will automatically deserialise the string to an object for you, so you simply need to access the required property. Assuming that you only ever want to retrieve the first price returned in the price array, you can access it directly by index. Try this:
success: function(data) {
$("#txtpeUniform").val(data.price[0].Price); // = 250
},

Passing php string as json to be received by jquery

I am trying to echo a string which is structured like json, but the jquery ajax post is not able to parse it properly. What I want to know is if this string will be treated like json in the jquery json parse just like when we echo a json_encode.
echo '{"mobno":'.$mobno.',"charge":'.$charge.',"capacity":'.$capacity.'}';
ajax code:
jQuery.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
success: function(response){
var Vals = JSON.parse(response);
if(!Vals){
alert("Error1");
}else{
var capacity = parseInt(Vals.capacity);
if(capacity>0){
alert("worked1");
}else{
alert("worked2");
}
}
}
});
I don't get a single alert out of the 3.
As per your edit and comment, your json string is correct. You just have to change your AJAX request.
Add this setting dataType: "json" in your AJAX request if you're expecting a json object as response from server.
So your AJAX request should be like this:
jQuery.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
dataType: "json",
success: function(response){
// you can access json properties like this:
// response.mobno
// response.charge
// response.capacity
var capacity = response.capacity;
if(capacity > 0){
alert("worked1");
}else{
alert("worked2");
}
}
});
Just so JavaScript can differ string and properties of json, please use double quote for starting and ending the string and for json properties use single quote or vice-versa. Try that out and let me know if you could not figure that out.
As other answers suggest you need to fix the quotes of the JSON the web service is sending back in the response.
Regarding you question, everything sent back in the response is actually a string. You need to decide what to do with it once it arrives.
One of the ways to allow both client side and server side programs understand what was sent is setting the right content type header.
For JSON the best way is to set the content type header to "application/json".
If you're using php you can do this:
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);
On the client side jquery ajax you can do this:
$.ajax({
dataType: "json",
url: url,
data: data,
success: function(data, textStatus, jqXHR){}
});
In this example the "data" parameter passed to the "success" callback function is already a js object (after JSON.parse). This is due to the use of the "dataType" parameter in the ajax declaration.
Optionally, you can do this manually and write a simple $.post which receives a string and do the JSON.parse yourself.
Maybe you should do the manual parsing yourself at first, and use the console.log(data) before and after the parsing so you'd know you're doing it correctly. Then, move on to the automatic way with "dataType" set to "json".
Please see #Rajdeep Paul's JSON string correction. Then, have your response JSON object remapped to an array.
JSON string
echo "{\"mobno\":\"".$mobno."\",\"charge\":\"".$charge."\",\"capacity\":\"".$capacity."\"}";
Ajax
$.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
success: function(response){
// map JSON object to one-dimensional array
var Vals = $.map( JSON.parse(response), function(el) { return el });
if(!Vals){
alert("Error1");
}else{
var count = parseInt(Vals.length);
if(count>0){
alert("worked1");
}else{
alert("worked2");
}
}
}
});
Reference: Converting JSON Object into Javascript array

How to navigate JSON Object in jQuery?

I made this webservice that handles my database functions, and this is an AJAX call to one of the methods.
$.ajax({
type: "POST",
url: "Service/dataBaseService.asmx/getRMAData",
data: '{"RMAId": 1 }',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (data) {
console.log(data);
alert(data.RMA_ID);
}
});
this is what is logged:
({d:"[{\"RMA_ID\":1,\"RequestDate\":\"2013-02-28T00:00:00\",\"Company\":1,\"Status\":\"Accepted \",\"Serial\":201764,\"LastChangeDate\":\"2013-02-28T00:00:00\",\"LastChangeBy\":\"Foreign \",\"Price\":null}]"})
However alert(data.RMA_ID) returns undefined aswell as data.d.RMA_ID?
How can I get hold of the values?
The value of data that you've logged is an object with a property named d, that contains a string value. You could probably make adjustments at your server side to make the value of d an object rather than a string, but the way it is currently constructed, you would be able to parse it into an object using JSON.parse.
Once you've done that, the resulting object should be an array, containing one single object. Thus, your access to RMA_ID would be as follows:
var data = JSON.parse(data.d);
alert(data[0].RMA_ID);
Using simple javascript you need to parse JSON response
var resp = eval('(' + data + ')');
or thru jQuery
var resp = jQuery.parseJSON(data);
now you can access the data using '.' and key name
console.log(resp.d[0].RMA_ID)

Categories