I have a Dojo ajax request and i am posting the data as json however the data is not reaching the server in json format. I am also not able to see the JSON tab in the browsers Net option of the console. I need the data in json format on the server.
Ajax Request
var someData = [{id:"1",age:"44",name:"John"},
{ id:"2",age:"25",name:"Doe"},
{ id:"3",age:"30",name:"Alice"}];
function SendData() {
var xhrArgs = {
url:'processData',
postData: someData,
handleAs: "json",
headers: { "Content-Type": "application/json", "Accept": "application/json" },
load:function(data){
console.log('data was posted');
},
error:function(error){
console.log(error);
}
};
dojo.xhrPost(xhrArgs);
Screenshot of server details
I would like the JSON data under to appear in the following format under with the name MyData. How is this format possible on the server?
JSON
MyData [Object{id:"1",age:"44",name:"John"},
Object{ id:"2",age:"25",name:"Doe"},
Object{ id:"3",age:"30",name:"Alice"}]
SOURCE
{"MyData":[{id:"1",age:"44",name:"John"},
{ id:"2",age:"25",name:"Doe"},
{ id:"3",age:"30",name:"Alice"}]}
Actually url:'' is empty in your Ajax call. Please provide action url,
for suppose
url: "AddTrackServlet"
After playing around with the variable i saw it could be declared
var someData = [{id:"1",age:"44",name:"John"},
{ id:"2",age:"25",name:"Doe"},
{ id:"3",age:"30",name:"Alice"}];
var formData = {MyData:someData}
function SendData() {
var xhrArgs = {
url:'processData',
postData: dojo.toJson(formData),
handleAs: "json",
headers: { "Content-Type": "application/json", "Accept": "application/json" },
load:function(data){
console.log('data was posted');
},
error:function(error){
console.log(error);
}
};
dojo.xhrPost(xhrArgs);
Related
Im working on a project, where we try to exchange different parameters between the UI and a RestAPI via AJAX. The RestAPI defines how the data has to look:
I tried to solve it this way:
$(document).ready(function(){
$("#submit").click(function(){
var credentials = [
{user_name: $("#uname").val(),
password: $("#pwd").val()
}
];
alert(credentials);
$.ajax({
url:"../rest/user/login",
type:"POST",
data:JSON.stringify({credentials: credentials}),
success: function(){
window.location.href = "startrackhome.html";
},
error: function error(response){
try{
var json = JSON.parse(response.responseText);
if(typeof json.message === 'undefined'){
throw new Error("Response json has no message");
}
else{
alert(json.message);
}
}
catch(ex){
alert("unexpected error (code:" + response.status +")");
}
}
});
});
});
The alert shows this: [object Object]
And I always get an error message (error: 400), which means that I mus have made a mistake and I think the format I'm sendig is wrong but I dont know how to fix it.
I hope you can help me! :)
I made some changes to your code :
// credentials is an object
var credentials = {
user_name: $("#uname").val(),
password: $("#pwd").val()
}
alert(credentials);
$.ajax({
// check this url seems a bit off
url: "../rest/user/login",
type: "POST",
data: {
credentials: credentials
},
success: function() {
window.location.href = "startrackhome.html";
},
error: function error(response) {
try {
var json = JSON.parse(response.responseText);
if (typeof json.message === 'undefined') {
throw new Error("Response json has no message");
} else {
alert(json.message);
}
} catch (ex) {
alert("unexpected error (code:" + response.status + ")");
}
}
});
in my case it makes this request :
fetch("https://stackoverflow.com/posts/rest/user/login", {
"headers": {
"accept": "*/*",
"accept-language": "",
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"102\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"Linux\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-requested-with": "XMLHttpRequest"
},
"referrer": "https://stackoverflow.com/posts/72620005/edit",
"referrerPolicy": "strict-origin-when-cross-origin",
"body": "credentials%5Buser_name%5D=test&credentials%5Bpassword%5D=test",
"method": "POST",
"mode": "cors",
"credentials": "include"
});
credentials[user_name]: test
credentials[password]: test
which seems good, if the server needs a json, you can stringify the credentials, which gives this paylaod :
credentials: {"user_name":"test","password":"test"}
I need to fetch all data from an xml link but I couldn't as it displays only 300 rows, so I found a solution that says I should use __next, I have the code below but it doesn't work, in the console I get the next url but the items (TaskName) of the first page. I want to get the TaskName(s) of the next pages.
window.addEventListener('load',function() {
$.ajax({url: _spPageContextInfo.siteAbsoluteUrl + "/_api/ProjectData/[en-US]/Tasks",
method: "GET",
dataType: "json",
headers: {Accept: "application/json;odata=verbose"},
success: function(data) {
var dataResults = data.d.results;
if (data.d.__next) {
url = data.d.__next;
console.log("url: "+url);
}
$.each(dataResults, function(key, value)
{
var tasky = value.TaskName;
console.log(tasky);
});
}});
});
I found a solution, here the code is:
function GetListItems(){
$.ajax({
url: urly,
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function(data){
response = response.concat(data.d.results);
if (data.d.__next) {
urly = data.d.__next;
GetListItems();
}
$.each(response, function(key, value)
{
var tasky = value.TaskName;
console.log(tasky);
});
},
error: function(error){
}
});
}
Trying to be more consistent with HTTP verbs, I'm trying to call a delete Handler on a Razor Page via AJAX;
Here's my AJAX code, followed by the C# code on my page :
return new Promise(function (resolve: any, reject: any) {
let ajaxConfig: JQuery.UrlAjaxSettings =
{
type: "DELETE",
url: url,
data: JSON.stringify(myData),
dataType: "json",
contentType: "application/json",
success: function (data) { resolve(data); },
error: function (data) { reject(data); }
};
$.ajax(ajaxConfig);
});
my handler on my cshtml page :
public IActionResult OnDeleteSupprimerEntite(int idEntite, string infoCmpl)
{
// my code
}
which never reaches ... getting a bad request instead !
When I switch to a 'GET' - both the type of the ajax request and the name of my handler function ( OnGetSupprimerEntite ) - it does work like a charm.
Any ideas ? Thanks !
Short answer: The 400 bad request indicates the request doesn't fulfill the server side's needs.
Firstly, your server is expecting a form by;
public IActionResult OnDeleteSupprimerEntite(int idEntite, string infoCmpl)
{
// my code
}
However, you're sending the payload in application/json format.
Secondly, when you sending a form data, don't forget to add a csrf token:
#inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
<script>
function deleteSupprimerEntite(myData){
var url = "Index?handler=SupprimerEntite";
return new Promise(function (resolve, reject) {
let ajaxConfig = {
type: "DELETE",
url: url,
data: myData ,
success: function (data) { resolve(data); },
error: function (data) { reject(data); }
};
$.ajax(ajaxConfig);
})
}
document.querySelector("#testbtn").addEventListener("click",function(e){
var myData ={
idEntite:1,
infoCmpl:"abc",
__RequestVerificationToken: "#(Xsrf.GetAndStoreTokens(HttpContext).RequestToken)",
};
deleteSupprimerEntite(myData);
});
</script>
A Working Demo:
Finally, in case you want to send in json format, you could change the server side Handler to:
public class MyModel {
public int idEntite {get;set;}
public string infoCmpl{get;set;}
}
public IActionResult OnDeleteSupprimerEntite([FromBody]MyModel xmodel)
{
return new JsonResult(xmodel);
}
And the js code should be :
function deleteSupprimerEntiteInJson(myData){
var url = "Index?handler=SupprimerEntite";
return new Promise(function (resolve, reject) {
let ajaxConfig = {
type: "DELETE",
url: url,
data: JSON.stringify(myData) ,
contentType:"application/json",
headers:{
"RequestVerificationToken": "#(Xsrf.GetAndStoreTokens(HttpContext).RequestToken)",
},
success: function (data) { resolve(data); },
error: function (data) { reject(data); }
};
$.ajax(ajaxConfig);
})
}
document.querySelector("#testbtn").addEventListener("click",function(e){
var myData ={
idEntite:1,
infoCmpl:"abc",
};
deleteSupprimerEntiteInJson(myData);
});
Is it possible to access and modify data in Kendo UI grid before updating?
Below is an example to illustrate what I need. The options.data contains the sent data but it is already formatted in string "models=%B7%22Id22%.... etc" not really convenient form.
dataSource = new kendo.data.DataSource({
transport: {
read: {
...
},
update: {
url: baseURL + "update",
beforeSend: function(xhr, options){
xhr.setRequestHeader('API-KEY', apikey );
var modifiedData = doSomething(options.data);
return modifiedData;
},
dataType: "json",
method: "POST",
dataFilter: function(data){
... some data recieved modification
return JSON.stringify(somedata);
},
complete: function(e) {
....
}
},
You should be able to use the parameterMap function, check the type for "update" and change the options.data anyway you want.
parameterMap: function(options, type) {
if(type === "update") {
options.someProperty = "somenewvalue";
}
return kendo.data.transports.odata.parameterMap(options, type);
}
In my ASP.NET page I have the following method:
public static void UpdatePage(string accessCode, string newURL)
{
HttpContext.Current.Cache[accessCode] = newURL;
}
It actually should receive the accessCode and newURL and update the Cache accordingly. I want to pass the values to that method from JavaScript, using an AJAX request. The code for it is as follows:
function sendUpdate() {
var code = jsGetQueryString("code");
var url = $("#url_field").val();
var dataToSend = [ {accessCode: code, newURL: url} ];
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "lite_host.aspx/UpdatePage",
data: {"items":dataToSend},
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) { var results = response.d; } };
$.ajax(options);
}
However this doesn't seem to work. Could anybody help me figure out where the bug is?
UpdatePage is a void method that doesn't return anything, so there is nothing to look at in the response.
You could look at the HTTP return code and check that it was 200 OK or you could modify the web method:
public static bool UpdatePage(string accessCode, string newURL)
{
bool result = true;
try {
HttpContext.Current.Cache[accessCode] = newURL;
}
catch {
result = false;
}
return result
}
Edit:
It looks like your JSON arguments to the WebMethod are incorrect, you don't need the "items" in your JSON. The arguments should match your webmethod exactly.
function sendUpdate() {
var code = jsGetQueryString("code");
var url = $("#url_field").val();
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "lite_host.aspx/UpdatePage",
data: {'accessCode': code, 'newURL': url},
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) { var results = response.d; } };
$.ajax(options);
}