Not able to set text in input field from json response - javascript

I have a form in which I have to fill data after I have got a json object from httpGet in javascript.
$("#getDetails").click(function() {
$.get("/servlet",{
mID : 5
})
.done(function(data) {
$("#input1").val(data["some key"]);
$("#input2").val(data.name);
$("#input3").val("directvalue");
});
});
In the above 3 fields, only input3 gets filled with "directvalue".
Is there some problem in accessing json object or in setting value of input fields.
Note: the json object contains keys with spaces like "some key":"some value"
edit:
When I tried Object.keys(data)[index] to access the object field, I got Uncaught TypeError: Object.keys called on non-object

Try This
$("#getDetails").click(function () {
$.get("/servlet", {
mID: 5 })
.success(function (data) {
$("#input1").val(data.d.somekey);
$("#input2").val(data.d.name);
$("#input3").val("directvalue");
});
});

In the comments, you say it's returning this object:
{
"Name": "my name",
"my address": "23,round street",
"Description": "PM Speech at Red Fort on Indep Day 2014"
}
Try:
$("#input2").val(data.Name);

When I did console.out(data), it was printing a json object.
But when I tried Object.keys(data)[index] to access the object field, I got Uncaught TypeError: Object.keys called on non-object.
This means that dataitself was not a json object.
So I got a hint that server was giving a string in which json object was written. I had to simply parse the json object from the data string.
Following is the working code:
$("#getDetails").click(function() {
$.get("/servlet",{
mID : 5
})
.done(function(data) {
var dataObj=JSON.parse(data);
$("#input1").val(dataObj["some key"]);
$("#input2").val(dataObj.name);
});
});

Related

Suitescript RESTlet data get Error Empty JSON string

I have issue using POST Function, I want to transform Transfer Order to Item Receipt, But when I tried to execute the script, it failed with error "org.mozilla.javascript.EcmaError: SyntaxError: Empty JSON string (INVOCATION_WRAPPER$sys#24".
Anyone can help me about my issue ?
Here is my Suitescript Code :
function postData (receiptItem) {
doValidation([receiptItem.recordtype], ['recordtype'], 'POST');
if (receiptItem.recordtype == 'transferorder') {
var recordId = [];
var recStr = [];
var objRecord = record.transform({
fromType: record.Type.TRANSFER_ORDER,
fromId: 131, // transfer Order internalid
toType: record.Type.ITEM_RECEIPT,
defaultValues: {
customform: '433'}
});
var itemReceiptId = objRecord.save({
enableSourcing: false,
ignoreMandatoryField: false
});
recordId.push(itemReceiptId)
log.debug({
"title": "[success] recordId: ",
"details": recordId
});
var recLoad = record.load({
type: receiptItem.recordtype,
id: recordId.getValue('internalid')
});
recStr.push({
use_form: recLoad.getText('customform'),
tran_id: recLoad.getValue('tranid'),
tran_date: recLoad.getValue('trandate'),
tran_from: recLoad.getValue('transferlocation'),
tran_to: recLoad.getValue('location'),
tran_ord_id: recLoad.getvalue('createdfrom'),
tran_memo: recLoad.getValue('memo')
});
log.debug({
"title": "recStr",
"details": recStr
});
return recStr;
}
}
return {
post: postData
};
});
It's a syntax error, very likely some misplaced bracket.
Make sure you are posting valid JSON and that the content type is set on your request
You must send data as JSON. if empty or no data then send {} at least in POST as ContentType is Application/JSON. ECMA Standard. The error message clearly states that "Empty JSON string".
Then try this in Postman tool.

jQuery: Get JSON error

I'm trying to get certain elements from a JSON file but I'm just not able to do so, I've tried different ways, this is the JSON file:
// data.json
{
"stuff": [
{
"userId": 1,
"date": "19 Oct 2014",
"content": "#New Hello on g.co/ABC",
"entities": {
"hashtags": ["#New"],
"urls": ["g.co/ABC"]
}
}
],
"user": {
"avatar": "/assets/avatar.jpg",
"name": "Daniel"
}
}
Now my jQuery code is:
$(document).ready(function(){
$.getJSON('data.json', function(data) {
//console.log(data);
$.each(data,function(i,item){
console.log(item.stuff.content); // I want to print 'content'
});
});
});
And all I get is an Uncaught error type:
What am I doing wrong? Thanks in advance
stuff is an array of object.
To access item of an array you have to access it via index
like this
console.log(data.stuff[0].content);
JSFIDDLE
May be you are iterating an object instead of array of object
If data is an object then try like this
$.each(data.stuff,function(i,item){
console.log(item.content);
});
JSFIDDLE
This should work:
$.getJSON('data.json', function(data) {
console.log(data['stuff'][0]['content']);
}
It is getting the stuff element of the JSON object then the first element of that pair, since the pair of key "stuff" is an array of JSON Objects. Then from that last JSON object, its grabbing content.
You json data is not an array. so you don't need to use each. But stuff is an array so take it's specific index or loop through it.
$(document).ready(function(){
$.getJSON('data.json', function(data) {
console.log(data.stuff[0].content);
//or loop through like
//$.each(data.stuff,function(i,item){
// console.log(item.content);
//});
});
});

AngularJS $http patch request not sending data

The data is being passed to the replyMessage as the console log is showing the correct data, however, the API isn't receiving this data. Input is empty?
replyMessage: function(data) {
console.log(data);
return $http.patch('/api/email/inbox/0', data);
}
Can you see any issues with this or any things to look at?
Are you formatting patch correctly?
It needs to be a JSON.stringify(data) Array.
With data being formatted like so:
[
{
"op" : "replace",
"path" : "/Name", // <-- this is what field you're editing
"value" : "John Doe"
}
]
Also you might need your contentType to be application/json-patch+json;

Read attributes of json external link with javascript

Hi I want to do a reverse geocodoing from longitude and lontitude google map api to do that I should add the LonLat to a link to get a JSON structure this the link of JSON file http://maps.googleapis.com/maps/api/geocode/json?latlng=34.0235202,-6.8317697&sensor=true
from this link I want to read the attribute
formatted_address
this how I get the JSON file
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?latlng='+loca.toString()+'&sensor=true',
function(data) {
alert(data.results.formatted_address[0]);
}); }
but it shows me this error Uncaught TypeError: Cannot read property '0' of undefined
and thank you for helping me
The response from the api looks something like this:
{
results: [{
...
formatted_address: "39 Tirle Bank Way, Tewkesbury, Gloucestershire GL20 8ES, UK"
...
},
...
],
status: "OK"
}
You're trying to access formatted_address like an array with [0], when it is actually a string. It's results that is an array. This should work for you if you only care about the first result:
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?latlng='+loca.toString()+'&sensor=true', function(data) {
if (data.status === 'OK') {
alert(data.results[0].formatted_address);
}
else {
alert('Error! ' + data.status)
}
});
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?latlng=34.0235202,-6.8317697&sensor=true',
function(data) { alert(data.results[0].formatted_address); });

Parsed elements coming up as undefined

I'm trying to parse the following JSON:
{
"customers": [
{ "name":"joe" , "cars":[
{"name":"honda","visits":[
{"date":"01/30/14","Id":"201"},
{"date":"01/30/14","Id":"201"},
{"date":"02/12/14","Id":"109"}
]},
{"name":"Nissan","visits":[
{"date":"01/30/14","Id":"201"},
{"date":"02/12/14","Id":"109"}
]}
]},
{ "name":"bob" , "cars":[
{"name":"escalade","visits":[
{"date":"01/05/14","Id":"301"},
{"date":"01/18/14","Id":"551"}
]},
{"name":"corvette","visits":[
{"date":"01/05/14","Id":"301"},
{"date":"01/18/14","Id":"551"}
]}
]}
]
}
Using the following jQuery script:
$("document").ready(function(){
$.getJSON("data1.json", function(json) {
console.log(json); // this will show the info it in firebug console
$.each(json.customers,function(customer){
console.log(customer.name);
console.log(customer.cars);
});
});
});
The JSON is coming through in the console but the fields I'm trying to parse are coming up as undefined. Can anyone ell me what I'm doing wrong?
I think the issue here is your usage of $.each, your callback function will receive the index as the first argument and the value as the second argument and it looks like you are expecting the first argument to be the value. So in your current code customer will be an index (0, 1, etc.) rather than the object from your JSON.
Try changing your $.each call to the following:
$.each(json.customers, function(index, customer) {
console.log(customer.name);
console.log(customer.cars);
});

Categories

Resources