JavaScript - Building JSON object - javascript

I'm trying to understand how to build a JSON object in JavaScript. This JSON object will get passed to a JQuery ajax call. Currently, I'm hard-coding my JSON and making my JQuery call as shown here:
$.ajax({
url: "/services/myService.svc/PostComment",
type: "POST",
contentType: "application/json; charset=utf-8",
data: '{"comments":"test","priority":"1"}',
dataType: "json",
success: function (res) {
alert("Thank you!");
},
error: function (req, msg, obj) {
alert("There was an error");
}
});
This approach works. But, I need to dynamically build my JSON and pass it onto the JQuery call. However, I cannot figure out how to dynamically build the JSON object. Currently, I'm trying the following without any luck:
var comments = $("#commentText").val();
var priority = $("#priority").val();
var json = { "comments":comments,"priority":priority };
$.ajax({
url: "/services/myService.svc/PostComment",
type: "POST",
contentType: "application/json; charset=utf-8",
data: json,
dataType: "json",
success: function (res) {
alert("Thank you!");
},
error: function (req, msg, obj) {
alert("There was an error");
}
});
Can someone please tell me what I am doing wrong? I noticed that with the second version, my service is not even getting reached.
Thank you

You may want to look at the JSON JavaScript library. It has a stringify() function which I think will do exactly what you need.

Your code:
var comments = $("#commentText").val();
var priority = $("#priority").val();
var json = { "comments":comments,"priority":priority };
Take out the quotes ( line 3 ):
var comments = $("#commentText").val();
var priority = $("#priority").val();
var json = { comments: comments, priority: priority };

Remove the quotes
data: '{"comments":"test","priority":"1"}',
becomes
data: {"comments":"test","priority":"1"},
JSONs are objects not strings.

This should work
var json = { comments: "comments",priority: "priority" };

this works for me.
var json = "{ 'comments': '" + *comments* +"','priority:' '" + *priority* +"' }";
italics are the variables.

Related

Cannot read JSON returned by .Net Core controller on client side

In my controller I have a method that gets triggered by an AJAX call. I have a list of strings that I want to return
List<string> Usernames = new List<string>();
Then when data is loaded into Usernames I convert it into JSON
var JsonResults = Json(Usernames);
finally I return that JSON as below
return Json(new { success = true, resultsList =JsonResults });
In JavaScript, How can I loop through that array resultsList? Here is what the JS code looks like -
$.ajax({
url: "#Url.Action("StartNewChat")",
data: { SearchedText: searchedText },
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.success == true) {
// READ THROUGH result.resultsList
}
}
});
I tried JSON.parse() and result.resultsList[0] and converting result.resultsList into string and back to JSON it didn't work.
Edit:
When I do a console.log(result.resultsList) here is what I get which is pretty strange
{"contentType":null,"serializerSettings":null,"statusCode":null,"value":["a","aa","aaa"]}
the last array is the result from Username array in c#
I'm not familiar with the Json method you are using, but from version 3.1 .Net Core has its own json serializer JsonSerializer (in System.Text.Json namespace) and I'm going to use that one in my answer.
As of your issue, you are serializing twice and it might not give you the resultsList in your final result as an array of string which you might be expecting.
Your first conversion will result in an array of strings -
["alice","bob","charlie"]
But your second conversion, depending on the serializer used, might put the entire array above inside a string and give that as the value of resultsList in your final result.
You should serialize once, the final object only -
// you need to import the following
// using System.Text.Json;
List<string> userNames = new List<string>();
names.Add("alice");
names.Add("bob");
names.Add("charlie");
return JsonSerializer.Serialize(new { success = true, resultsList = userNames });
It will give you resultsList as an array of strings -
{"success":true,"resultsList":["alice","bob","charlie"]}
Then you can loop through that array on the client end like -
result.resultsList.forEach(p=> console.log(p))
The response has already a JSON so no need to parse anything.
It will be something like this:
$.ajax({
url: "#Url.Action("StartNewChat")",
data: { SearchedText: searchedText},
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.success == true)
{
result.resultsList.forEach( el => {
console.log(el)
})
}
}
});
});
```
sometimes you have to parse the json response first try this. straight after the success line
let result = JSON.parse(result);
Then
if (result.success == true)
{
result.resultsList.forEach( el => {
console.log(el)
})
}
You can try this using by through the resultlist length.
$.ajax({
url: "#Url.Action("StartNewChat")",
data: { SearchedText: searchedText},
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.success == true)
{
for (var i = 0; i <result.resultsList.length; i++) {
console.log(result.resultsList[i]);
}
}
}
});

Rails/AJAX Stringify Data Returning Undefined

I'm trying to POST a comment to a using AJAX in Rails (without using remote: true and am having difficulty understanding why my myJSON variable is returning as undefined, when data is returning as expected.
Here's my code:
function submitViaAjax() {
$("#new_comment_button").on("click", function (e) {
e.preventDefault();
url = $(this.form).attr('action')
data = {
'comment': {
'content': $("#comment_body").val()
}
};
var myJSON = JSON.stringify(data);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: url,
data: myJSON,
// headers: { 'Content-Type': 'application/json' },
success: function (response) {
var $ul = $("div.comments_section ul");
$ul.append(response)
}
}).done(function(response){
debugger
var $ul = $("div.comments_section ul");
$ul.append(response)
})
})
};
I can run var myJSON = JSON.stringify(data); in the browser console just fine, so I'm not sure why it's not doing anything in my code.
Any help would be appreciated.
I found out why I wasn't getting the response I expected. It's a jQuery function, but I was using JavaScript variable declaration to define myJSON.
In short, I need to remove var from var myJSON = JSON.stringify(data);
EDIT:
Implementing 'use strict'; within that function renders those variables undefined, which may mean that I was originally overwriting them - causing the 400 and/or 422 error.
EDIT 2:
I was getting the 422 error because my data object had a key of content when my param was looking for body.

Recursive ajax query

I was hoping that someone may be able to give me a pointer on how to achieve the following.
Currently, I have:
A JS function: A jQuery AJAX query that will get items from a SharePoint custom list.
A JS function: it will put the list results in to a datatable.
A JS function, that can turn an InitatorId into the real name of a user (GetDisplayName).
function GetDisplayName(userid) {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
$.ajax({
url : requestUri,
contentType : "application/json;odata=verbose",
headers : requestHeaders,
success : GetDisplayNameSuccess,
error : GetDisplayNameFail
});
}
function populateMyOutstandingItems() {
SP.SOD.executeFunc("sp.js", "SP.ClientContext", function() {
SP.SOD.executeFunc("sp.runtime.js", "SP.ClientContext", function() {
var context = SP.ClientContext.get_current();
var queryUrl = "https://companyname.sharepoint.com/subsite/_api/Web/Lists/getbytitle('Read%20Requests')/GetItems"; //change the Url
var camlXML = "<Query><Where><And><Eq><FieldRef Name='ReaderId' LookupId='True' /><Value Type='Integer'>" + _spPageContextInfo.userId + "</Value></Eq><Neq><FieldRef Name='Read' /><Value Type='Text'>YES</Value></Neq></And></Where></Query>"
var requestData = { "query" :
{"__metadata":
{ "type": "SP.CamlQuery" }
, "ViewXml": camlXML
}
};
return jQuery.ajax({
url: queryUrl,
type: "POST",
data: JSON.stringify(requestData),
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Accept": "application/json; odata=verbose",
"Content-Type": "application/json; odata=verbose"
},
success: onQuerySuccessMyOutstandingItems,
error: onQueryErrorMyOutstandingItems
});
});
});
}
function onQuerySuccessMyOutstandingItems(data) {
var jsonData = data.d.results
console.log(jsonData)
$("#resultsDivMyOutstandingItems").dataTable( {
"data" : jsonData,
columns: [
{ data: "Document_x0020_Name" },
{ data: "Document_x0020_Library_x0020_Nam" },
{ data: "Request_x0020_Made_x0020_Date" },
{ data: "InitatorId" },
{ data: "Request_x0020_ReadBy_x0020_Date" }, ],
order: [[3, "asc"]]
} ); }
At the moment, in the datatable, I have the InitatorID (ie. 30) but I would like to have the real name of the user in the table.
I understand some type of recursive AJAX query will be needed, but I'm not sure what the best way forward would be to achieve this, and was hoping that someone would be able to point me in the right direction.
After reading a bit about chained requests, I tried the code below, but it's wrong I guess, since Chrome complains of an 'unexpected ending':
var request = $.ajax({
url: queryUrl,
type: "POST",
data: JSON.stringify(requestData),
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Accept": "application/json; odata=verbose",
"Content-Type": "application/json; odata=verbose"
}
}),
chained = request.then(function( data ) {
return $.ajax( spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + data.InitatorId + ")",
{ data: { user: data.Title }} )
});
chained.done(function( data ) {
console.log(data)
});
In short, what is the best to achieve what I'm trying to do?
Many thanks
Glen
I am not sure I completely understand what you're asking, so here's my best guess at the scenario (please correct me if I am wrong)
Make an AJAX call to get a list of items from a SharePoint custom
list, but alas, one of the columns in this list has an InitatorID instead of a user name.
To fix this, we want to make another AJAX call that will get a list of usernames for a matching set of InitatorIDs we just retrieved.
Once we have that, we want to put the data in a dataTable for display.
Without knowing the details, I would just do nested AJAX calls. Basically, once the first call is done, call the second AJAX function. Once that one is done, update the dataTable. Something like:
$.ajax({
url: MY_FIRST_URL,
data: myFirstData
}).done(function (data) {
// The first call gets completed after some time and the 'done' function is called.
// here, extract the various InitatorID values, and pass them to the
// second AJAX call, so you can then get the usernames for those Ids
var initatorIds = // ... do data massaging here to get the initatorIds
// into the format you want from the 'data' variable
// passed in the done function...
$.ajax({
url: MY_SECOND_URL,
data: initatorIds
}).done(function (data2) {
// once the SECOND call is complete, populate the dataTables
var jsonData = // ... some manipulation of data and data2 results
// to get the combined output you want.
$("#resultsDivMyOutstandingItems").dataTable( {
"data" : jsonData,
columns: [
....
....
});
}).fail(function (jqXHR, textStatus) {
// do stuff if the second call fails
});
}).fail(function (jqXHR, textStatus) {
// do stuff if the first call fails
});
And at the risk of over-complicating the solution, I'd personally look to load the data directly into the table via the ajax functionality found within the dataTable plugin (read more about that here). But definitely if it minimizes confusion to lay it out as above, do that first!

I am Unable to Parse a JSON in JQuery

I have My jquery function that is returning me data of the formatt:
{"Suggestions":[{"name":"RR Restaurant","category_id":"166","locality":"Gayathri Nagar","listing_info":"listing","random_id":"1ll0f0wJ"},{"name":"Oko Restaurant","category_id":"166","locality":"Kumara Krupa","listing_info":"listing","random_id":"0F7ZGV9p"},{"name":"H2O Restaurant","category_id":"166","locality":"Maratha Halli","listing_info":"listing","random_id":"0JNPOyuP"},{"name":"Taj Restaurant","category_id":"166","locality":"Shivaji Nagar","listing_info":"listing","random_id":"7GeA0Kfq"},{"name":"PSR Restaurant","category_id":"166","locality":"Peenya Industrial Area","listing_info":"listing","random_id":"cRvJCwQ3"},{"name":"ac restaurant","category_id":"166","listing_info":"keyword"},{"name":"Indian Restaurant","category_id":"166","listing_info":"keyword"},{"name":"goan restaurant","category_id":"166","listing_info":"keyword"},{"name":"thai restaurant","category_id":"166","listing_info":"keyword"},{"name":"andhra restaurant","category_id":"166","listing_info":"keyword"}],"ImpressionID":"test"}
I wish to parse the same to get multiple variables with The field "Name" and "Random Id" in different js variables
$("#what").on("keypress", function() {
$.ajax({
type: "GET",
cache: false,
url: "/AutoComplete.do",
data: {
query: 'Pest',
city: 'Bangalore'
}, // multiple data sent using ajax
success: function(data) {
alert();
}
});
});
My JSON object seems to be nested with "Suggestions" as the parent. Please help.
If you add a property to $.ajax function you be ensure that is json parsing:
dataType: 'json'
EDIT
To iterate above the string you can use for(in) or each() jquery
json = "[{'key':'value'},{'key':'value']";
for(var i in json) {
console.log(json[i]);
//if you see in console [OBJECT Object] you are
//in a new object you must to iterate nested of this.
}
$("#what").on("keypress", function() {
$.ajax({
type: "GET",
dataType: "JSON", //You need this to be inserted in your ajax call.
cache: false,
url: "/AutoComplete.do",
data: {
query: 'Pest',
city: 'Bangalore'
}, // multiple data sent using ajax
success: function(data) {
alert();
}
});
});
After insert dataType you can probably do this.
console.log(data.Suggestions);
Also take a look at the API Doc at below url regardless of dataType.
http://api.jquery.com/jquery.ajax/
The data object you are specifying is what will be sent as the arguments to your success method, if you use the GET method.
$("#what).on("keypress", function() {
$.get("/AutoComplete.do", function(response) {
var data = JSON.parse(response);
//data.suggestions = [lots of objects];
//data.suggestions[0].locality = "Gayathri Nagar"
});
});

Extract JSON returned from Servlet in JavaScript

Basically I am trying to extract JSON returned from servlet in JavaScript. I have tested my servlet class already and it did returned some JSON so I guess I no need to post the code for that class. Here is my returned JSON format:
[{"mrtpopAmt":"7000","mrtpopX":"17854.99820","mrtpopY":"35056.35003"},{"mrtpopAmt":"6300","mrtpopX":"29798.58427","mrtpopY":"37036.56434"}]
And in my JavaScript, I am trying to extract mrtpopAmt, mrtpopX and mrtpopY as one object. Then I will add all object into an array:
function getAllMRTPop(time){
var jsonArray;
var Data = JSON.stringify({ time: time });
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time="+ Data + "",
type: "GET",
data: Data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var parsed = JSON.parse(data.d);
console.log(data.d);
$.each(parsed, function (i, jsondata) {
var jsonObject;
jsonObject.put("mrtpopAmt", jsondata.mrtpopAmt);
jsonObject.put("mrtstationX", jsondata.mrtstationX);
jsonObject.put("mrtstationY", jsondata.mrtstationY);
alert(jsonObject);
jsonArray.push(jsonObject);
});;
},
error: function (request, state, errors) {
}
});
}
However, I am getting error message like Unexpected token: u at this line:
var parsed = JSON.parse(data.d);
My URL for the servlet contains two parameter, one is action and the other one is time:
http://localhost:8080/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time=8:00
So I wonder am I passing the parameter correctly by passing it in url and as well as data from the code above?
I wonder which part went wrong? Thanks in advance.
EDIT
So I have updated my JavaScript part to this:
function getAllMRTPop(time){
var jsonArray = [];
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time=8:00",
type: "GET",
data: time,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
//var parsed = JSON.parse(data.d);
$.each(data, function (i, jsondata) {
var jsonObject;
console.log(mrtpopAmt);
jsonObject.put("mrtpopAmt", jsondata.mrtpopAmt);
jsonObject.put("mrtstationX", jsondata.mrtstationX);
jsonObject.put("mrtstationY", jsondata.mrtstationY);
jsonArray.push(jsonObject);
});;
},
error: function (request, state, errors) {
}
});
}
I tried to print out the mrtpopAmt and it did returned something. But there is an error message:
Cannot call method 'put' of undefined
Any ideas?
By specifying dataType: "json", jQuery already knows you will be getting a JSON response, there is no no need to do var parsed = JSON.parse(data.d)
Just do:
var parsed = data.d
Edit:
function getAllMRTPop(time){
var jsonArray = [];
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time=8:00",
type: "GET",
data: time,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
$.each(data, function (i, jsondata) {
var jsonObject = {};
jsonObject.mrtpopAmt = jsondata.mrtpopAmt;
jsonObject.mrtstationX = jsondata.mrtstationX;
jsonObject.mrtstationY = jsondata.mrtstationY;
jsonArray.push(jsonObject);
});;
},
error: function (request, state, errors) {
}
});
}
I think what is happening is that data.d is undefined, so you are getting the odd message about unexpected u.
Try this instead:
var parsed = JSON.parse(data);
Edit And I think you are probably not formatting your request right:
var Data = JSON.stringify({ time: time });
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time="+ Data + "",
Seems to me that would make the final bit: &time={"time":"time"}, so you probably want to look at how you construct Data. Maybe just pass time directly?
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time="+ time + "",

Categories

Resources