Insert variable value into ajax post data - javascript

I have created a form with textboxes and a dropdown menu, inside my code I've created a script which will be called when clicking "Send Form"
Lets say my field are : firstName, lastName, country (dropdown)
Here is the script:
function f1() {
var settings = {
"async": true,
"url": "https://api.TheSite.com/v2/applications/123456789/newJson.json",
"method": "POST",
"headers": {
"x-api-key": "123456789123456",
"content-type": "application/json",
},
"processData": false,
"data": "{\r\n \"deployment\": {\r\n \"revision\": \"string\",\r\n \"changelog\": \"string\",\r\n \"description\": \"string\",\r\n \"user\": \"string\"\r\n }\r\n}"
}
$.ajax(settings).done(function(response) {
console.log(response);
alert("The Form Was Sent");
});
}
I would like to insert those 3 variables' values inside the "data" string like so:
"data": "{\r\n \"deployment\": {\r\n \"revision\": \`firstName
\",\r\n \"changelog\": \"`lastName
and so on...
In the dropdown menu, I assume it will be displayed as an array. How do I include my variable inside?

First create an empty object and insert the data into it.
Next use JSON.strigify() to convert that into a JSON blob before you send it over to the server.
var data = {};
data.deployment = {};
data.deployment.revision = firstName;
data.deployment.changelog = lastName;
var settings = {
....,
data: JSON.stringify(data)
};

Since you are already using jQuery to perform your AJAX request, you should be aware that you can actually pass a native JavaScript object into the data portion of the request. You don't need to have it converted to a JSON string. If you want to, you can just stringify it.
You can actually establish default request options and then merge them with the data you want to request.
var defaults = {
url: 'https://api.TheSite.com/v2/applications/123456789/newJson.json',
method: 'POST',
contentType: 'application/json',
headers: {
'x-api-key': '123456789123456',
},
processData: false,
async: true
};
function makeXhrRequest(config) {
var xhrRequest = $.extend(true, defaults, config);
// If you want to convert the request to a json String.
//xhrRequest.data = JSON.stringify(data);
$.ajax(xhrRequest).done(function(data, textStatus, jqXHR) {
console.log(data);
alert("The Form was sent...");
});
}
var $myForm = $('form[name="my-form"]');
makeXhrRequest({
data : {
deployment : {
revision : $myForm.find('input[name="firstname"]').val(),
changelog : $myForm.find('input[name="lastname"]').val(),
description : 'string',
user : 'string'
}
}
});

SOLVED
this is the syntax that worked for me +$("#firstName")[0].value+ and this is the code :
"data":"{\r\n\deployment\: {\r\n revision\:"+"\""+$("#firstName")[0].value+"\","+"\r\n"

Related

Passing a string array from JS to C# controller

I have an array in JS ( var selectedEmails = []; )
After I collect the selected Emails from a grid, I call a GET to C# controller:
$.ajax({
type: 'GET',
url: '#Url.Action("SendEmailBatchs", "account")',
data: { emails: selectedEmails },
contentType: 'application/json',
success: (data) => {
console.log("data", data);
}
})
When called, the parameter in C# gets no data. I've checked in JS, and the emails are in the array. Using breakpoints, I've confirmed the Controller's method is getting called:
Controller:
[HttpGet("sendemailbatchs")]
public async Task<ActionResult> SendEmailBatchs(string[] emails)
{
...
foreach (ApplicationUser user in users)
{
await SendEmailConfirmation(user);
}
return Ok;
}
Changing the data to data: { emails: JSON.stringify(selectedEmails) }, will pass an array with 1 element only, containing a stringified list of emails "[\"loes.vea#phanc.com\",\"MaAlonso.Mfizer.com\",\"cech#mll-int.cm\",\"jier.aris#si.com\"]"
What would be the correct parameter from JS so that I get a string ARRAY where each email is an element of the array?
emails = [0]: "loes.vea#phanc.com\",
[1]: \"MaAlonso.Mfizer.com\", ...
There is a gap between what you are expecting in the controller and what you are sending through ajax call.
public async Task<ActionResult> SendEmailBatchs(string[] emails)
Let's understand the parameter of the above function, you are expecting an array of strings and will refer to it as emails in the function body. So, you will have to pass an array of strings in the request body.
PFB my simple controller and corresponding ajax call:
[HttpGet("api/test")]
public ActionResult<int> RecieveData(string[] emails)
{
return emails.Count();
}
Call from UI like this:
var settings = {
"url": "https://localhost:5000/api/test",
"method": "GET",
"headers": {
"Content-Type": "application/json"
},
"data": JSON.stringify([
"john#example.com",
"jane#example.com"
]),
};
$.ajax(settings).done(function (response) {
console.log(response);
});
so, after following Devesh's suggestions I ended up with
var settings = {
"url": '#Url.Action("SendEmailBatchs", "account")',
"method": "GET",
"headers": {
"Content-Type": "application/json"
},
"data": {
emails: JSON.stringify(selectedEmails)},
};
the issue persisted, because I needed to DESERIALIZE the result, in C#:
public async Task<ActionResult> SendEmailBatchs(string emails)
{
var selectedEmails = JsonConvert.DeserializeObject<string[]>(emails);
//DO STUFF
}
Thx

Parse return value from $ajax call in JavaScript from MVC Controller

I'm using VS2022 with C# and I'm trying to use an $ajax get method in my JavaScript function. I'm sending a parameter and returning a string[] list but when I receive the return I use JSON.stringify but when I try to use JSON.Parse it fails. The Javascript code is
$.ajax({
type: "GET",
url: '/Home/GetCategories/',
contentType: 'application/json',
datatype: 'json',
data: { ctgData: JSON.stringify(relvalue)}
}).done(function(result) {
let userObj = JSON.stringify(result);
let resultList = JSON.parse(userObj);
});
The code in the controller which returns the list is simple at the moment until I get the return working
[HttpGet]
public ActionResult GetCategories(string ctgData)
{
string[] categoryList = { "Food & Drink", "Sport & Fitness", "Education", "Housework", "Fiction", "Horror Books", "Fantasy", "Magic" };
return Json(new { data = categoryList });
}
The value in result is
{"data":["Food & Drink","Sport & Fitness","Education","Housework","Fiction","Horror Books","Fantasy","Magic"]}
I've tried a number of different ways in Parse but it always fails, can you tell me what I'm missing to get my resultList to contain the string array.
You don' t need to parse anything. It is already java script object
$.ajax({
type: "GET",
url: '/Home/GetCategories/',
contentType: 'application/json',
datatype: 'json',
data: { ctgData: JSON.stringify(relvalue)}
sucess: function(result) {
let data=result.data; // data = ["Food & Drink","Sport & Fitness",..]
}
});
use this:
JSON.parse(JSON.stringify(data))
const data = {"data":["Food & Drink","Sport & Fitness","Education","Housework","Fiction","Horror Books","Fantasy","Magic"]}
const resultJSON = JSON.parse(JSON.stringify(data))
console.log("json >>>", resultJSON)

POST Request to cycle through 8 different urls

I have been working on a project for quite some time now.
I have found this post somewhat useful, but am unsure if it is correct or not for my utilization.
Functionality:
Read in SharePoint list items from 8 different subsites with a GET request.
Populate those items in an orderly(grouped) fashion in a DataTable on a single landing page.
DataTable has collapsible/expandable rows grouped by program, followed by deliverable.
Dropdown menu with buttons to print/excel/PDF/Update the table.
Update Table has a HTML form that sends data back to the SharePoint List correlated with the FORM input.
I am currently using 8 different subsites where all of the lists are located. I want to send the new item to the correct list based off of its "Program" value because each of the different lists are a different program. I know I would have to use an if/else statement, but how would I go about that with an AJAX call?
Here is my JS "POST" Code:
$("#btn").click(function(e) {
PostItem();
});
});
function PostItem() {
return getFormDigest("https://baseurl.sharepoint.com/sites/Projects/USMC/AMMO/Lists/AMMODeliverables/").then(function(digestData) {
console.log(digestData.d.GetContextWebInformation.FormDigestValue);
var item = {
"__metadata": { "type": "SP.Data.AMMODeliverablesListItem" },
"Title": "updated title",
"Program": $("#dProgram").val(),
"Deliverable": $("#dDeliverable").val(),
"To": $("#dTo").val(),
"Date": $("#dDate").val(),
"Approved": $("#dApproved").val(),
"Notes": $("#dNotes").val()
};
$.ajax({
async: true, // Async by default is set to “true” load the script asynchronously
// URL to post data into sharepoint list or your own url
url: "https://baseurl.sharepoint.com/sites/Projects/USMC/AMMO/_api/web/lists/getbytitle('AMMO Deliverables')/items",
method: "POST", //Specifies the operation to create the list item
data: JSON.stringify(item),
headers: {
"content-type": "application/json;odata=verbose",
"X-RequestDigest": digestData.d.GetContextWebInformation.FormDigestValue,
"Accept": "application/json;odata=verbose",
"If-Match": "*"
},
success: function(data) {
alert('Success'); // Used sweet alert for success message
console.log(data + " success in updating item");
},
error: function(data) {
alert(JSON.stringify(item));
console.log(data);
}
});
})
}
function getItemTypeForListName(listName) {
var itemType = "SP.Data." + listName.charAt(0).toUpperCase() + listName.slice(1) + "ListName";
var encItemType = itemType.replace(/\s/g,'_x0020_');
return(encItemType);
}
function getFormDigest(baseurl) {
return $.ajax({
url: "https://baseurl.sharepoint.com/sites/Projects/USMC/AMMO/_api/contextInfo",
method: 'POST',
headers: {
'Accept': 'application/json; odata=verbose'
}
});
}
UPDATE:
I feel like I am somewhat in the right direction, but it doesn't work:
function PostItem() {
return getFormDigest("https://siteurl.sharepoint.com/sites/Projects/USMC/AMMO/Lists/AMMODeliverables/").then(function(digestData) {
console.log(digestData.d.GetContextWebInformation.FormDigestValue);
var item = {
"__metadata": { "type": "SP.Data.AMMODeliverablesListItem" },
"Title": "updated title",
"Program": $("#dProgram").val(),
"Deliverable": $("#dDeliverable").val(),
"To": $("#dTo").val(),
"Date": $("#dDate").val(),
"Approved": $("#dApproved").val(),
"Notes": $("#dNotes").val()
};
if (dProgram == "AMMO"){
$.ajax({
async: true, // Async by default is set to “true” load the script asynchronously
// URL to post data into sharepoint list or your own url
url: "https://siteurl.sharepoint.com/sites/Projects/USMC/AMMO/_api/web/lists/getbytitle('AMMO Deliverables')/items",
method: "POST", //Specifies the operation to create the list item
data: JSON.stringify(item),
headers: {
"content-type": "application/json;odata=verbose",
"X-RequestDigest": digestData.d.GetContextWebInformation.FormDigestValue,
"Accept": "application/json;odata=verbose",
"If-Match": "*"
},
success: function(data) {
alert('Success'); // Used sweet alert for success message
console.log(data + " success in updating item");
},
error: function(data) {
alert(JSON.stringify(item));
console.log(data);
}
});
}
else if (dProgram == "AHR"){
First of all, your getFormDigest function is not quite right:
function getFormDigest(baseurl) {
// you pass in a "baseurl" value above, but you're not really doing anything with it.
// the URL you use below is hardcoded to always
// make the request to the /sites/Projects/USMC/AMMO site
return $.ajax({
url: "https://baseurl.sharepoint.com/sites/Projects/USMC/AMMO/_api/contextInfo",
method: 'POST',
headers: {
'Accept': 'application/json; odata=verbose'
}
});
}
What you need to do is change that so you can pass a site URL into it and get a valid form digest from the actual site you are trying to post a new item to:
function getFormDigest(siteUrl) {
return $.ajax({
url: siteUrl + "/_api/contextInfo",
method: 'POST',
headers: {
'Accept': 'application/json; odata=verbose'
}
});
}
Next, you need to change your PostItem function to react to the current value of the selected Program, and choose some correct values based on that. I see in the comments you have posted a little snippet where you are creating a map that will spit out the correct URL based on the key of the selected Program. That works if all you need is a single value, however, since you said that the list names are all different on each subsite, you actually need three different values to be generated dynamically based on the selected Program:
The URL to the site itself so you can get a valid form digest,
The list name, so you can get the correct List Item Entity Type value for your new item's JSON __metadata property. You have a function to do this, but you aren't using it. Also, you'll need the list name for:
A URL that includes the site and the list name so you can post the new list item (since the URL to do that is essentially [URL to site]/_api/web/lists/getbytitle('[list name]')/items)
You could do a sequence of if..then..else if..then..else if..then..else statements, but for more than two or three possible values, that gets cumbersome. A much cleaner way of doing it is using a switch statement. So here's what your PostItem function might look like if you used a switch to evaluate what the selected Program value is and then dynamically set the site URL and list name based on that:
function PostItem() {
// the base URL should be what is the same across all subsites. in comments
// you said the subsites start to differ after /sites/Projects.
var baseUrl = "https://your-tenant.sharepoint.com/sites/Projects";
// get the selected program from your form
var programName = $("#dProgram").val();
var siteUrl = null; // set this as empty for now
var listName = null; // set this as empty for now
// a "switch" statement is like a fancy "if" statement that is
// useful if you have more than just two or three options
switch (programName) {
case "AMMO":
// set the site url to be whatever it is after /sites/Projects.
// in the case of AMMO, you have already posted that the "AMMO"
// subsite is under a "USMC" subsite that is under "Projects"
siteUrl = baseUrl + "/USMC/AMMO";
listName = "AMMODeliverables";
break;
case "AHR":
// set the site url to be whatever it is after /sites/Projects.
// IF in this case the "AHR" subsite is directly under /Projects
// and NOT under another subsite (as is the case with /USMC/AMMO),
// you just add that directly:
siteUrl = baseUrl + "/AHR";
// HOWEVER, if it is under another subsite with a different name, similar
// to how "AMMO" is actually under another subsite called "USMC", then you
// would include that "Other" subsite here:
siteUrl = baseurl + "/Other/AHR";
// set the list name, since you said the list names
// are different in each of the subsites
listName = "AHR Deliverables";
break;
case "FOO":
// pretending that "FOO" is _directly_ under /sites/Projects
siteUrl = baseurl + "/FOO";
listName = "FOO Thingys";
break;
case "BAR":
// pretending that "BAR" is NOT directly under /sites/Projects,
// but is in fact under another "Different" subsite
siteUrl = baseurl + "/Different/BAR";
listName = "BAR Whatchamacallits";
default:
// all switch statements need a default option in case
// what we are checking does not match any any of the options
// we are expecting. in this instance, we will _not_ set
// a site URL or list name so that we do not try to post
// to s non-existent site or list
break;
}
// if we didn't get one of our expected choices for programName, then siteUrl
// will not have been populated in the switch, so we can check and make sure we
// actually have a valid siteUrl before we start sending AJAX requests out
if (siteUrl) {
// pass the siteUrl into your improved getFormDigest function so
// that you get the correct form digest from the site you are
// actually trying to post a new item to.
// also, you don't actuall need the "return" here.
getFormDigest(siteUrl).then(function(digestData) {
console.log(digestData.d.GetContextWebInformation.FormDigestValue);
// use your getItemTypeForListName function to get the
// correct SharePoint List Item Entity Type name based on
// the list name
var listItemEntityType = getItemTypeForListName(listName);
// construct the URL to post the new list item to based on the siteUrl
// and the listName, which vary based on the selected projecName
var postNewItemUrl = siteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items";
// construct your new item JSON. you said all the fields
// in all the lists are the same, so the only thing that really
// needs to dynamically chage here is the entity type name,
// which was generated based on the list name
var item = {
"__metadata": { "type": listItemEntityType },
"Title": "updated title",
"Program": programName,
"Deliverable": $("#dDeliverable").val(),
"To": $("#dTo").val(),
"Date": $("#dDate").val(),
"Approved": $("#dApproved").val(),
"Notes": $("#dNotes").val()
};
$.ajax({
// use your dynamically generated URL here
url: postNewItemUrl,
method: "POST", //Specifies the operation to create the list item
data: JSON.stringify(item),
headers: {
"content-type": "application/json;odata=verbose",
"X-RequestDigest": digestData.d.GetContextWebInformation.FormDigestValue,
"Accept": "application/json;odata=verbose",
"If-Match": "*"
},
success: function(data) {
alert('Success'); // Used sweet alert for success message
console.log(data + " success in updating item");
},
error: function(data) {
alert(JSON.stringify(item));
console.log(data);
}
});
});
}
}

How to solve error parsing in dataTables?

I have a function button that carry user info fullname, after clicking the button, it will send fullname and level to an API to be process and the result should be display in dataTable. Unfortunately, I got this error.
This is console.log for console.log(params). {"task_level":3,"fullname":"Administrator"}
Below is console.log for console.log(params).
Both console log is similar to API's result.
I don't know which is proper.
JS 1st Try (1st Ajax to send the parameter to API and after return success hopefully working but not.
"<button type='button' class='btn btn-dark btn-round' onclick='viewTablePerson(""+value.fullname+"")'>View Project</button>"+
function viewTablePerson(fullname){
var level = 3;
var fullname2 = fullname;
var obj = {
task_level : level,
fullname : fullname2
};
var params = JSON.stringify(obj);
console.log(params)
$.ajax({
url : url_api + '/api/user_task',
crossDomain: true,
type : 'POST',
dataType : 'json',
data: params,
success: function(response){
if (response.status == "Success"){
console.log(response)
$('#viewProgress').DataTable({
ajax: {
url: url_api + '/api/user_task',
crossDomain : true,
type : "POST",
cache : false,
dataType : "json",
contentType: false,
processData: true,
data : params,
timeout: 10000,
},
destroy: true,
columns: [
{ data : "task_name"},
{ data : "task_owner"},
{ data : "task_status"}
],
});
}
},
error: function(e){}
});
}
JS 2nd Try
<button type='button' class='btn btn-dark btn-round' onclick='viewTablePerson(""+value.fullname+"")'>View Project</button>"+
function viewTablePerson(fullname){
var level = 3;
var fullname2 = fullname;
var obj = {
task_level : level,
fullname : fullname2
};
var params = JSON.stringify(obj);
console.log(params)
$('#viewProgress').DataTable({
ajax: {
url: url_api + '/api/user_task',
crossDomain : true,
type : "POST",
cache : false,
dataType : "json",
contentType: false,
processData: true,
data : params,
timeout: 10000,
},
destroy: true,
columns: [
{ data : "task_name"},
{ data : "task_owner"},
{ data : "task_status"}
],
});
}
Documentation says:
When using the ajax option to load data for DataTables, a general error can be triggered if the server responds with anything other than a valid HTTP 2xx response.
So, you have to check server-side response instead of search for problems on the front-end.
Also, in your case make sure
the plugin sends request to the same domain from which the current page is loaded;
browser security system doesn't prevent loading of external scripts - for example on http://localhost you cannot Ajax load a script from http://google.com without special measures;
you are specifying a relative path without a domain name (if you are using a single domain);
JSON data in response is a valid.
If you cannot alter the backend system to fix the error, but don't want your end users to see the alert message, you can change DataTables' error reporting mechanism to throw a Javascript error to the browser's console, rather than alerting it:
$.fn.dataTable.ext.errMode = 'throw';

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.

Categories

Resources