Can not get value from JSON object - javascript

I'm having trouble getting the data value from JSON object. Here is my code:
var ab_id = $( "#ab_id" ).val();
$.ajax({
type: 'GET',
contentType: 'application/json',
url: 'edit_account.php',
data: {ab_id:ab_id, u_id:u_id},
success: function(data)
{
alert(data.ab_name);
},
});
When I do alert(data), I got the actual data like this:
{
"ab_id":"7",
"ab_name":"Lily's Storage Address",
"ab_ship_name":"LIly C\/O SELF STORAGE",
"ab_addr_1":"C\/O Lily",
"ab_addr_2":"16 PIUMA AVENUE, UNIT #2",
"ab_city":"CERI",
"ab_state":"CA",
"ab_postal":"90700",
"ab_phone":null,
"ab_default":"0",
"ab_is_storage":"1"
}
However, when I retrieve the data value by using data.ab_name, it returns undefined.
Am I missing something here?

Use bracket notation
alert(data['ab_name']);
for reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

Parse your string to a object
data = JSON.parse(data);
alert(data.ab_name);

Related

Can not get item of JSON-response

I am trying to create a AJAX call - and I would like to work with the response.
This is my response I see in my browser's network console:
{
"message": "success",
"file": "dump.xml"
}
And this is what I want to do:
onComplete: function onComplete(data) {
var vm = this;
console.log(data.file);
this.$set('upload', data);
this.$set('filename', file);
this.modal.show();
}
Okay. Well - I'm getting a response and if I write data to console.log, I'm getting this:
{"message":"success","file":"dump.xml"}
But if I try to do:
console.log(data.file);
I'm getting undefined. But why?
You are receiving it as a string. You have to parse it first to JSON by:
data = JSON.parse(data);
console.log( data.file )
OTHER OPTION: Or you can define it on request, add dataType: "json" so that you will receive json.
Like:
$.ajax(
{
type: "POST",
dataType: "json",
url: url,
data: {},
success: function( response ) {}
}
I think the problem is that data is a JSON string, so it will be printed in console, but when you call data.file it will be undefined. as string doesn't have a file property.
You need to parse your data object, before accessing file property:
data = JSON.parse(data);
console.log(data.file);
Most probably your data will be a JSON string. You have parse it into an Object like below
onComplete: function onComplete(data) {
data = JSON.parse(data)
var vm = this;
console.log(data.file);
this.$set('upload', data);
this.$set('filename', file);
this.modal.show();
}

Unable to get value from json object

I am trying to get a value from a json object after making an ajax call. Not sure what I am doing wrong it seems straight forward but not able to get the data
The data that comes back looks like this
{"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
The code, removed some of the code
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
console.log(result.data); //<== the data show here like above
alert(result.data.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I tried in the Chrome console like this
obj2 = {}
Object {}
obj2 = {"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
Object {data: "[{"Id":3,"Name":"D\u0027Costa"}]"}
obj2.data
"[{"Id":3,"Name":"D\u0027Costa"}]"
obj2.data.Id
undefined
obj2.Id
undefined
Update
The line that solved the issue as suggested here is
var retValue = JSON.parse(result.data)[0]
Now I can used
retValue.Name
to get the value
Actually, looking at this, my best guess is that you're missing JSON.parse()
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
var javascriptObject = JSON.parse(result);
console.log(javascriptObject ); //<== the data show here like above
alert(javascriptObject.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I also find that doing ajax requests like this is better:
var result = $.ajax({
url: "someUrl",
data: { some: "data" },
method: "POST/GET"
});
result.done(function (data, result) {
if (result == "success") { // ajax success
var data = JSON.parse(data);
//do something here
}
});
For clarity it just looks better, also copying and pasting into different functions as well is better.
The id property is in the first element of the data-array. So, alert(result.data[0].Id) should give the desired result. Just for the record: there is no such thing as a 'JSON-object'. You can parse a JSON (JavaScript Object Notation) string to a Javascript Object, which [parsing] supposedly is handled by the .ajax method here.
The data field is just a string, you should parse it to a JSON object with JSON.parse(result.data), since data is now an array you will need to need to use an index [0] to have access to the object. Know you will be able to get the Id property.
JSON.parse(result.data)[0].Id

.serialize() an array of variables in Javascript

I have a list of variables available to me and I want to send it via $.ajax post. What format would I have to keep these in to use the function .serialize? I keep getting this error:
Object 'blank' has no method 'serialize'
I've tried to make them an array and I've tried jQuery.param(). I have a feeling this is simple but I can't seem to get it. Thanks!
var $data = jQuery.makeArray(attachmentId = attachmentID, action = 'rename', oldName = filename, newName, bucketName, oldFolderName, newFolderName, projectId = PID, businessId = BID);
var serializedData = $data.serializeArray();
//alert(theurl);
$.ajax({ type: "post", url: theurl, data: serializedData, dataType: 'json', success: reCreateTree });
.serialize is for form elements:
Encode a set of form elements as a string for submission.
The $.ajax documentation says for the data option:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
So all you need to do is passing an object. For example:
$.ajax({
type: "post",
url: theurl,
data: { // <-- just pass an object
attachmentId: attachmentID,
action: 'rename',
// ...
},
dataType: 'json',
success: reCreateTree
});
It seems you're used to the PHP style of array's (associated arrays). In Javascript, objects are basically the same thing (though can be MUCH more complicated).
So if you are trying to create an array like this in php it would be
$array = array(
"foo" => "bar",
"bar" => "foo",
);
in Javascript using an object instead of an array it would be
var arr = {
foo: "bar",
bar: "foo"
}

JQuery $.ajax() post - data in a java servlet

I want to send data to a java servlet for processing. The data will have a variable length and be in key/value pairs:
{ A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }
The data doesn't need to be formated this way, it is just how I have it now.
var saveData = $.ajax({
type: "POST",
url: "someaction.do?action=saveData",
data: myDataVar.toString(),
dataType: "text",
success: function(resultData){
alert("Save Complete");
}
});
saveData.error(function() { alert("Something went wrong"); });
The $.ajax() function works fine as I do get an alert for "Save Complete". My dilemna is on the servlet. How do I retrieve the data? I tried to use a HashMap like this...
HashMap hm = new HashMap();
hm.putAll(request.getParameterMap());
...but hm turns out to be null which I am guessing means the .getParameterMap() isn't finding the key/value pairs. Where am I going wrong or what am I missing?
You don't want a string, you really want a JS map of key value pairs. E.g., change:
data: myDataVar.toString(),
with:
var myKeyVals = { A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }
var saveData = $.ajax({
type: 'POST',
url: "someaction.do?action=saveData",
data: myKeyVals,
dataType: "text",
success: function(resultData) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });
jQuery understands key value pairs like that, it does NOT understand a big string. It passes it simply as a string.
UPDATE: Code fixed.
Simple method to sending data using java script and ajex call.
First right your form like this
<form id="frm_details" method="post" name="frm_details">
<input id="email" name="email" placeholder="Your Email id" type="text" />
<button class="subscribe-box__btn" type="submit">Need Assistance</button>
</form>
javascript logic target on form id #frm_details after sumbit
$(function(){
$("#frm_details").on("submit", function(event) {
event.preventDefault();
var formData = {
'email': $('input[name=email]').val() //for get email
};
console.log(formData);
$.ajax({
url: "/tsmisc/api/subscribe-newsletter",
type: "post",
data: formData,
success: function(d) {
alert(d);
}
});
});
})
General
Request URL:https://test.abc
Request Method:POST
Status Code:200
Remote Address:13.76.33.57:443
From Data
email:abc#invalid.ts
you can use ajax post as :
$.ajax({
url: "url",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ name: 'value1', email: 'value2' }),
success: function (result) {
// when call is sucessfull
},
error: function (err) {
// check the err for error details
}
}); // ajax call closing
For the time being I am going a different route than I previous stated. I changed the way I am formatting the data to:
&A2168=1&A1837=5&A8472=1&A1987=2
On the server side I am using getParameterNames() to place all the keys into an Enumerator and then iterating over the Enumerator and placing the keys and values into a HashMap. It looks something like this:
Enumeration keys = request.getParameterNames();
HashMap map = new HashMap();
String key = null;
while(keys.hasMoreElements()){
key = keys.nextElement().toString();
map.put(key, request.getParameter(key));
}
To get the value from the servlet from POST command, you can follow the approach as explained on this post by using request.getParameter(key) format which will return the value you want.

How to convert variables into json?

I want to send json data to ajax but how do you convert variables into json or convert an array to json?
$(".confirm_order").click(function(event) {
event.preventDefault();
var street = $("#street").val();
var location = $("#location").val();
var number = $("#number").val();
var f = ???
$.ajax({
type: 'post',
url: "/orders",
dataType: "json",
data: f,
success: function (l) {
alert("Done");
}
});
});
If you really want to convert the data into JSON, you have to create an object or array and use JSON.stringify (available in newer browser and can be loaded form here):
var f = JSON.stringify({street: street, location: location, number: number});
but you cannot just set the data attribute to f then. You have to assign it to another variable:
data: {data: f}
This will produce the POST parameters like so:
data={"number":"value of number","location:...}
However, there is not reason to create JSON here. I would sent the values as normal post parameters. For that you just create an object like above and assign it to data:
data: {street: street, location: location, number: number}
This will create the POST parameters:
street=valueofstreet&location=valueoflocation&...
This would be easier as you don't have to parse the JSON at the server side.
If you want to send a JSON formatted request to the server you could specify the proper content type for this request and then use the JSON.stringify method:
var street = $('#street').val();
var location = $('#location').val();
var number = $('#number').val();
$.ajax({
type: 'post',
url: '/orders',
dataType: 'json',
data: JSON.stringify({ street: street, location: location, number: number }),
contentType: 'application/json; charset=utf-8',
success: function (l) {
alert("Done");
}
});
This will send the following in the POST body:
{ street: 'foo', location: 'bar', number: 'baz' }
Obviously the server side script you are sending this AJAX to need to be capable of handling and parsing JSON strings.
var f = {}
f['street'] = $("#street").val();
f['location'] = $("#location").val();
f['number'] = $("#number").val();
var f = {
"street": street,
"location": location,
"number": number
};
Use JSON.stringify from json2.js
Don't forget to specify contentType: 'application/json' in your config object.
try this. values will be replaced respectively
{street : street,location : location, number : number}

Categories

Resources