Sending POST request with Amplifyjs - ajax

I want to send this POST request by amplifyjs
amplify.request.define('createItem', 'ajax', {
url: baseApiUrl + '/create/?folderid={folderid}',
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8'
});
after that, the execution will be something like this:
createItem = function (callbacks, folderid, itemdata) {
return amplify.request({
resourceId: 'createItem',
data : {
folderid: folderid,
data: itemdata
},
success: callbacks.success,
error: callbacks.error
});
};
"itemData" is already a JSON string. I keep getting the Bad Request status code.
If I change the API URL to:
baseApiUrl + '/create
And after that pass:
return amplify.request({
resourceId: 'createItem',
data :data,
success: callbacks.success,
error: callbacks.error
});
It works just fine, but I need to pass the Id as well. Maybe, I'm missing something here.

You need to combine folderid and itemdata into a single data object. When Amplify reads your data object it will extract the folderid property and place it in the URL of the request. Then it will POST the remaining properties of the data object.

Related

Empty arguments Ajax ASP.NET Core 3.0 MVC

I am using an ASP.NET Core 3.0 MVC application in which I make the following jQuery Ajax call:
return $.ajax({
type: type,
url: '/' + controller + '/' + action,
data: jsonData,
timeout: timeout,
contentType: "application/json; charset=utf-8",
success: function (returnedData) {
successFunc(returnedData);
},
error: function (errMsg) {
errorFunc(errMsg);
}
});
passing it the data object
{
input1: 'random',
input2: '1',
input3: '1',
},
But it always passes null arguments through:
I have also tried adding addnewtonsoftjson() in startup but it doesn't seem to change anything.
A similar question here, doesn't really have an answer:
.Net Core 3.0 AJAX POST Body Always Null
I think your problem is kinda relative to the HTTP method/type you are using and the contentType you are passing to the backend.
I've found a great summary of contentType here
If you don't wanna dive too deep into this you could change your contentType into application/x-www-form-urlencoded; charset=UTF-8 should resolve your problem
So keep the c# code as you have shown in your question.
In you js call:
var data = JSON.stringify({
'input1': ‘inputvalue’,
'input2':’inputvalue’,
‘input3’: ‘inputval’
});
$.ajax({
type: "POST",
url: same as you have in the question
data: data,
contentType: 'application/json',
success: function (returnedData) {
successFunc(returnedData);
},
error: function (errMsg) {
errorFunc(errMsg);
}
});
The error seems to com from defining the content type.
return $.ajax({
type: type,
url: '/' + controller + '/' + action,
data: jsonData,
success: function (returnedData) {
successFunc(returnedData);
},
error: function (errMsg) {
errorFunc(errMsg);
}
});
has no contentType defined and passes through to the action in the controller correctly.

Ajax request what?

So I have a stupid question about this:
$.ajax({
type: "GET",
url: `URL`,
data: DO STUFF WITH WHAT I GOT FROM THE REQUEST???,
});
In ajax, when I make a get request from a URL, with the data: parameter am I giving a response that is data or is data the data I received from the request?
You can do something with the data in the success part of the ajax call:
$.ajax({
dataType: 'json',
url: url,
data: data,
success: success
});
In this case, a potential success callback would look like this:
function success(data) {
// do something with data, which is an object
}
or if there is no data to send:
function testAjax(handleData) {
$.ajax({
url:"getvalue.php",
success:function(data) {
handleData(data);
}
});
}
The main thing to understand here is that any AJAX call (any web request really) has two components: A request and a response. The actual $.ajax() function call is sending the request, and a callback function is provided to handle the response.
To illustrate:
$.ajax({
type: "GET", // request type
url: "http://www.example.com/someResource", // destination URL
data: { name: "David", location: "Boston" } // data to send
});
This would make a GET request to the specified URL, sending it the specified data. The response in this case is ignored, since no callback is provided. But you can provide one:
$.ajax({
type: "GET",
url: "http://www.example.com/someResource",
data: { name: "David", location: "Boston" }
}).done(function(response) {
// handle the response
});
The function which contains "handle the response" will be called by the system when the AJAX response is received from the server. The response variable (or whatever you want to call that variable, the name doesn't matter) will contain whatever the server sent in return. Which could be anything, really.

Error when calling the URL for saving JSON in database: String is too long

This is the method from the controller api :
[HttpPost]
public void SaveFloor(int floorID, string json)
{
Floor floor = db.FloorSet.Find(floorID);
floor.SavedJson = json;
floorRepository.Update(floor);
floorRepository.Save();
}
Then I made an ajax call to pass the URL.
function SavingFloor(FloorId, Json) {
$.ajax({
url: "/api/Floor/SaveFloor?FloorID=" + FloorId + "&json=" + Json,
type: "POST",
dataType: 'json',
success: function (data) {
alert('success');
}
});
}
I'm trying to save JSON in database (datatype: nvarchar(MAX)), when I call the URL that executes the saving, I get this error Error HTTP 404.15 - Not Found and it says that the filter module applications is configured to deny a request if the string is too long.
So, what should I do? the JSON that I generate is in fact supposed to be too long, and that's the purpose. Please help.
Send the JSON string as the POST body not as part of the URL. Send it as text and json_decode on the server.
function SavingFloor(FloorId, Json) {
$.ajax({
url: "/api/Floor/SaveFloor?FloorID=" + FloorId,
type: "POST",
data: Json,
dataType: 'text/html',
success: function (data) {
alert('success');
}
});
}

wcf service json 400 Bad Request

I get a 400 Bad Request error when I try to call WCF service from client side using ajax. Following is my code,
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json)]
string[] GetUser(string Id);
$.ajax({
type: "POST", //GET or POST or PUT or DELETE verb
url: "http://localhost:58055/Service1.svc/GetUser",
crossDomain: true,
data: '{"Id": "3"}',
contentType: "application/json; charset=utf-8",
dataType: "json", //Expected data format from server
processdata: true, //True or False
success: function (msg) {//On Successfull service call
alert(msg.GetUserResult[0]);
console.log("success " + msg);
},
error: function (msg) {//On Successfull service call
console.log(msg);
}
});
Any insights would be really helpfull...
The first thing you should try is hit the URL using fiddler(so that you could post your data too) and see if you get the same error.
Are you making a cross domain request. From the example it looks like you are not. Could you remove
crossDomain: true,
line and try the jquery again.
There are other options also which unnecessay like processdata. Suggest you to use the following code and see if it works or not.
$.ajax({
type: "POST",
// the url to the service -
url: "url",
// the format that the data should be in when
// it is returned
contentType: "json",
data: '{"Id": "3"}',
// the function that executes when the server
// responds to this ajax request successfully
success: function(data) {
// put the JSON response in the employees table
}
According to the ajax api documentation the default content type is 'application/x-www-form-urlencoded'. When sending JSON, the content type should be 'application/json; charset=utf-8' except that WCF does not like that. I got the same error messages and when I removed the content type I stopped getting this error. By the way, I noticed that you set crossDomain to true, this other question is relevant to that option.

jQuery.ajax returns 400 Bad Request

This works fine:
jQuery('#my_get_related_keywords').click(function() {
if (jQuery('#my_keyword').val() == '') return false;
jQuery.getJSON("http://boss.yahooapis.com/ysearch/web/v1/"
+jQuery('#my_keyword').val()+"?"
+"appid=myAppID"
+"&lang=en"
+"&format=json"
+"&count=50"
+"&view=keyterms"
+"&callback=?",
function (data) {//do something}
This returns 400 Bad Request (Just a reformulation of the above jQuery using .ajax to support error handling).
jQuery('#my_get_related_keywords').click(function()
{
if (jQuery('#my_keyword').val() == '') return false;
jQuery('#my_loader').show();
jQuery.ajax(
{
url: "http://boss.yahooapis.com/ysearch/web/v1/"
+jQuery('#my_keyword').val()+"?"
+"appid=myAppID"
+"&lang=en"
+"&format=json"
+"&count=50"
+"&view=keyterms"
+"&callback=?",
success: function(data)
{//do something}
I think you just need to add 2 more options (contentType and dataType):
$('#my_get_related_keywords').click(function() {
$.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8", // this
dataType: "json", // and this
success: function (msg) {
//do something
},
error: function (errormessage) {
//do something else
}
});
}
Add this to your ajax call:
contentType: "application/json; charset=utf-8",
dataType: "json"
Late answer, but I figured it's worth keeping this updated. Expanding on Andrea Turri answer to reflect updated jQuery API and .success/.error deprecated methods.
As of jQuery 1.8.* the preferred way of doing this is to use .done() and .fail(). Jquery Docs
e.g.
$('#my_get_related_keywords').click(function() {
var ajaxRequest = $.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8",
dataType: "json"});
//When the request successfully finished, execute passed in function
ajaxRequest.done(function(msg){
//do something
});
//When the request failed, execute the passed in function
ajaxRequest.fail(function(jqXHR, status){
//do something else
});
});
Be sure and use 'get' or 'post' consistantly with your $.ajax call for example.
$.ajax({
type: 'get',
must be met with
app.get('/', function(req, res) {
===============
and for post
$.ajax({
type: 'post',
must be met with
app.post('/', function(req, res) {
I was getting the 400 Bad Request error, even after setting:
contentType: "application/json",
dataType: "json"
The issue was with the type of a property passed in the json object, for the data property in the ajax request object.
To figure out the issue, I added an error handler and then logged the error to the console. Console log will clearly show validation errors for the properties if any.
This was my initial code:
var data = {
"TestId": testId,
"PlayerId": parseInt(playerId),
"Result": result
};
var url = document.location.protocol + "//" + document.location.host + "/api/tests"
$.ajax({
url: url,
method: "POST",
contentType: "application/json",
data: JSON.stringify(data), // issue with a property type in the data object
dataType: "json",
error: function (e) {
console.log(e); // logging the error object to console
},
success: function () {
console.log('Success saving test result');
}
});
Now after making the request, I checked the console tab in the browser development tool.
It looked like this:
responseJSON.errors[0] clearly shows a validation error: The JSON value could not be converted to System.String. Path: $.TestId, which means I have to convert TestId to a string in the data object, before making the request.
Changing the data object creation like below fixed the issue for me:
var data = {
"TestId": String(testId), //converting testId to a string
"PlayerId": parseInt(playerId),
"Result": result
};
I assume other possible errors could also be identified by logging and inspecting the error object.
Your AJAX call is not completed with the following two params.
contentType: "application/json; charset=utf-8",
dataType: "json"
contentType is the type of data you're sending
dataType is what you're expecting back from the server
In addition try to use JSON.stringify() method. It is used to turn a javascript object into json string.

Resources