Retrieving data from JSON data in Javascript - javascript

I have the following JSON data from my API
[{"email":"user#gmail.com","status":"Active"}]
This is the JS/jQuery code I am using to get the data
function formLogin() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var dataString = "email=" + email + "&password=" + password;
jQuery.ajax({
url: "http://localhost/OnlineShop/API/fetch_user_login_api.php",
data: dataString,
type: "POST",
success: function(data) {
$("#login-form").html(data);
console.log('success');
//window.location.href = "store.html?shopper=";
var obj = jQuery.parseJSON(data);
alert(obj.email);
},
error: function() {
console.log('error');
}
});
return true;
}
alert(obj.email) is throwing undefined. How do I retrieve the email and status from the JSON result?

Your "data" variable is already an object or an array, you don't need to call parseJSON.
Then, it seems that your object is an Array of objects
This should work:
alert(data[0].email);
I advice you to check if your array is empty or not before calling this line.

The API returns [{"email":"user#gmail.com","status":"Active"}] as it is of type Array.
first you need to take the first element of the Array by obj = obj[0].
then it is something like {"email":"user#gmail.com","status":"Active"}.
now you can get the email element by simply obj["email"]

if you call your api and get the result like this:
[{"email":"user#gmail.com","status":"Active"}]
it's an array, what you can do to fix the error is:
1) change your api response structure to JSON not array
2) use for to iterate your response
And I advice you next time, you have this kind of error, just console.log the raw data to find what's the structure of it, and you'll have the solution.

Related

How to print JSON array with AJAX call in a pretty format for UI

I am trying to validate data in a modal. If there is an error, an alert box is displayed. I am getting the output of the API in this format:
[{"Column":"ReportId","Result":"Invalid","Value":"repTest"},
{"Column":"Category","Result":"Invalid","Value":"testing"}]
I want to make it more readable to the user. How to get an output something like this in the alert box:
ReportId is invalid due to repTest
Category is invalid due to testing ( or any custom string between the corresponding values)
$.ajax({
type: 'POST',
url: 'validate_report',
contentType: 'application/json',
data: JSON.stringify(AddreportRepoFinalObj),
success: function (data) {
if(data.indexOf('Failure') > -1){
var e=JSON.stringify(data);
pwIsf.alert({msg:'Failure'+e ,type:'error'});
}
else if(data.indexOf('Success')>-1)
{
document.getElementById('btn_addUpdate').removeAttribute('disabled')
pwIsf.alert({msg:'Valid',type:'info'});
$(validAddRepbtn).off();
}
else{
var a=data; // I want to access the value part here from the data. Like I want to get rcaReportID, Invalid and repTest only and not column result and value
pwIsf.alert({msg:a, type:'error'});
}
},
})
Assuming that data in the final if condition in your example is a JSON string then you first need to parse it to an array of objects. From there you can loop through it and build your string output:
let data = '[{"Column":"ReportId","Result":"Invalid","Value":"repTest"},{"Column":"Category","Result":"Invalid","Value":"testing"}]'
let arr = JSON.parse(data);
var message = arr.map(o => `${o.Column} is ${o.Result} due to ${o.Value}`).join('\r\n');
console.log(message);

Unable to access json object property and value is displayed undefined in rails view

I've almost viewed similar kind of questions but my problem has not solved yet.
I've following codes.
Controller
def create
#task_list = TaskList.new(task_list_params)
if #task_list.save
respond_to do |format|
format.json { render json: #task_list}
end
else
return
end
end
Ajax Script
$(document).on('click','.add', function(){
count = 0;
user_id = $('#user_id').val();
var name = $('.new-list').val();
var current = $(this);
if(name){
$.ajax({
method: 'POST',
url: action,
dataType: 'JSON',
data: {
task_list: {
name: name,
user_id: user_id
}
}
}).success(function(response){
var data = JSON.stringify(response);
alert(data.id);
$(current).parent().parent().parent().before(
'<div class="col-md-12">'+
''+name+''+
'</div>'
);
$(current).parent().parent().parent().remove();
$('.add-list').show();
});
}else{
alert('please add title');
}
});
I just want to take id of the record just saved to the database through ajax post request. Here, in success function it just alerts undefined and I don't know what's going wrong.
This is sample response.
.success(function(response){
alert(response.id);
Remove JSON.stringify from your success function. Response is already in JSON format you can directly get the value from it.
JSON.stringfy converts javascript object into string.
Explanation
Your response is already in JSON format and you have used dataType: "JSON" in your AJAX call. Which will make it possible to transfer JSON data between server and client.
When your response is already in JSON format you can use its property without parsing it. I.e response.id
If you have not used dataType: "JSON" and you are passing json encoded response from your controller to view file you have to first decode the response to get its values.
var d = $.parseJSON(response);
alert(d.id);

Accessing Ajax Response JSON Data in javascript

I use an AJAX request to get the data from the backend when user select an option from a dropdown menu.
$('#adSpace').change(function () {
var sel_opt = $(this).val();
alert(sel_opt);
var location = null;
var width = null;
var height = null;
$.ajax({
type: "GET",
dataType: 'json',
url: "advertisements-controller.php",
data: {
action: "getDimension",
location: sel_opt
},
success: function (response) {
location = response.banner_location;
alert(location);
},
error: function (xhr) {
alert("error");
}
});
});
Now i'm getting the data from backend in JSON format like below:
[{"banner_location":"category_group_sidebar","banner_width":250,"banner_height":225}]
I want to access the values of banner_location, banner_width, banner_height by assigning those to javascript variables but I'm failing to do it.
Any ideas?
Use this
location = response[0].banner_location;
Your response comes in the form of an array: [...]. That means you can access the first array item by using the index. Also if there are multiple objects you can iterate response with forEach or jQuery's each($(response).each).
response[0].banner_location
response is an array of json. In order to access the json you need to firsr access the index of the array which is done by array[indexNumber] then the key of the json.
In your case it will be response[0].banner_location

How to parse json object datalist in ajax sucess using javascript

i am trying to parse json datalist in ajax success bt it couldnot work. i have passed object containing list of data using json from controller to view,i help to parse json object in ajax success. i have attached my code below.
//return json object from controller
PurchaseDetails pd = new PurchaseDetails();
foreach (DataRow dr in dt.Rows)
{
pd.serialList.Add(new SerialInfo {
Machine_serial_no = dr[0].ToString(), macAddress = dr[1].ToString(), isMacPresent = _TD1.CheckMac(machineTypes_MTId),brandName=obj.brandName,machineName=obj.machineName,MachineModel=obj.MachineModel,modelId=modelId,machineId=obj.machineId,brandId=obj.brandId});
// pd.macaddressList.Add(new MacAddressInfo { MacAddress = dr[1].ToString() });
}
}
}
return Json(new {pd}, JsonRequestBehavior.AllowGet);
return Json(new {pd}, JsonRequestBehavior.AllowGet);
// my ajax code
$.ajax({
url: "/Import/ImportPurchase",
type: "POST",
data: function () {
var data = new FormData();
data.append("file", jQuery("#file").get(0).files[0]);
data.append("machineTypes_MTId", jQuery('#machineTypes_MTId').val());
data.append("modelId", jQuery('#searchValue').val());
data.append("modelName", jQuery('#searchid').val());
return data;
}(),
dataType:"JSON",
contentType: false,
processData: false,
success: function (data) {
alert(data.Machine_serial_no)
Your controller method is returning
return Json(new { serialObj = pd}, JsonRequestBehavior.AllowGet);
which is an object containing a name serialObj
So in the ajax success call back, you would need to access it using
success: function (data) {
var PurchaseDetails = data.serialObj;
Since PurchaseDetails contains a collection named serialList which is a collection of SerialInfo, then to access the value of the first Machine_serial_no, it would be
var serialNo = data.serialObj.serialList[0].Machine_serial_no;
However it would be easier to just use
return Json(pd, JsonRequestBehavior.AllowGet);
If you then want to access each Machine_serial_no property in the collection, use
success: function (data) {
$.each(data.serialList, function(index, item) {
var serialNo = item.Machine_serial_no;
you can use jQuery.parseJSON() to parse ajax response to JSON.
but seeing from your code, seems the response should already be in JSON because dataType parameter is already set to "JSON".
try this:
remove "()" after the ending bracket of function in "data" parameter.
try to console.log(data) and look at the response from your browser console,
the response might not be a valid json string.
If you are looking for convert js array to JSON then just use JSON.stringify() function. This will convert your JS variable data value to JSON format.
You can more find here.

How to use JSON data from wcf url in javascript

I am trying to receive the JSON data from the WCF service url in javascript.
I used the following javascript code.
$(function(){
$("input:button").click(function() {
$.ajax({
dataType: 'json',
type: "GET",
url: "http://192.168.1.109/EIM/EIS.svc/json/getLatestLocation/Mobile/Mobile/1001",
success: function (data) {
var innerHtml = "";
document.getElementById('test').innerHTML=data;
//'test' is ID of <div>
document.getElementById('testlab').innerHTML=data.getLatestLocationResult.status.code;
//'testlab' is ID of <label>
$("#test").html(innerHtml);
alert("JSON DATA");
alert(data.getLatestLocationResult.status.code);
}
});
});
});
JSON data from url is:
{"getLatestLocationResult":{"status":{"code":"00","description":"Request
OK"},"reason":{"code":"000","description":"Request
OK"},"PersonDetails":{"PersonName":"Santosh Kumar
Sahu","PersonNumber":"1001","Identification":"Pan
Card","IdentificationNumber":"P567","ContactNo":"987654","Gender":"Male"},"location":[{"dateandtime":"7\/17\/2013
10:45:20 AM","latitude":"19.0469536","longitude":"72.9112502","address":"ND","city":"ND","state":"ND","country":"ND"}]}}
Please give me a suggestion to use receive this data.
Thank you.
You should eval the data - otherwise it's just a string.
obj = eval('(' + data + ')');
Now you can use obj as a rightful JS object and access it's members.
Here is the fiddle which evaluates your data string and accesses the resulting object members http://jsfiddle.net/M4BK5/

Categories