AJAX POST returns 404 Spring - javascript

I am trying to make a POST call using AJAX. Here's my controller:
#RequestMapping(method = RequestMethod.POST, value = "/submitsignup")
#ResponseBody
public String persistSignupData(#RequestBody SignupModel signupModel) {
signupDaoImpl.persistSignupData(signupModel);
return "success";
}
Javascript:
$(document).ready(function() {
$("#password2").keyup(checkPasswordMatch);
$('#signup-button').click(function() {
$.ajax({
type: "POST",
url: "/cinestop/submitsignup",
data: JSON.stringify(getFormDataJSON()),
contentType: "application/json",
dataType: "json"
});
});
});
When I make the call, a 404 is returned. I have been unable to debug this problem till now. What is it that I am doing wrong?

When I make the call, a 404 is returned.
Did you ensure that you put the correct url in your ajax part..?
HTTP error 404 usually means that the document that you'r requesting can't be loaded because it's
not existing
it is not readable
the mime type for the document is not defined (usually a problem of common webservers, i dont think that this matches on your specific setup)
Quote of relevant code
url: "/cinestop/submitsignup",
#RequestMapping(method = RequestMethod.POST, value = "/submitsignup")

Avoid stringifying the JSON, since your datatType expected is JSON.
$(document).ready(function() {
$("#password2").keyup(checkPasswordMatch);
$('#signup-button').click(function() {
$.ajax({
type: "POST",
url: "/cinestop/submitsignup",
data: getFormDataJSON(),
contentType: "application/json",
dataType: "json"
});
});
});

First try to debug the application step by step
From postman, curl or any other rest client try to hit a post call with the payload body as empty JSON.If this also return 404, then it is a server problem.If it succeeds or throw any java error then we know it is UI error.Also make sure to add content type header asĀ 'application/json'
This will help in isolating the issue and will help us in giving a quick resolution

Try to run this solution:
var settings = {
"url": "/cinestop/submitsignup",
"method": "POST",
"headers": {
"Content-Type": "application/json"
},
"data": getFormDataJSON()
}
$.ajax(settings).done(function (response) {
console.log(response);
});

Related

How to GET data from API

My API URL contains a payment transaction ID. I want to GET the data about this transaction from my API. The part that says console.log(response); is where I need to GET the data from the API. I will then fill this data into labels. How can I do this? I am using jQuery, ASP.NET, and C#. Thanks.
$.ajax(settings).done(function(response) {
console.log(response);
});
Adding 'success' and 'error' methods to the ajax call will help fetch the data and error codes.
Here is a working example:
$.ajax({
type: "GET",
contentType: "application/json",
url: "URL_WITH_TRANSACTION_ID",
headers: {
"Authorization": "auth-header-string"
},
success: function (output) {
console.log("Success: " + JSON.stringify(output))
},
error: function (e) {
console.log("ERROR : ", e.responseText)
}
})
Maybe native fetch is better choice? Just suggestion.
const { transaction_id } = await fetch(settings).then(r => r.json())
Tell the $.ajax function to expect a JSON response. Do this by adding "datatype": "json" to the settings object. This now means that the response you receive will be treated as JSON, meaning if it is a string with an object in it, it will turn the string into a workable object for you.
From the jQuery documentation:
dataType: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
function SubmitTransaction() {
// Card Card US Transaction Settings and Data
var settings = {
"url": "URL_WITH_TRANSACTION_ID",
"method": "GET",
"dataType": "json", // Add this line.
"headers": {
"X-Forte-Auth-Organization-Id": "ORGID",
"Authorization": "AUTHID",
"Content-Type": "application/json",
},
}
$.ajax(settings).done(function(response) {
console.log(response.transaction_id);
console.log(response.organization_id);
console.log(response.location_id);
console.log(response.status);
// etc..
});
}

javascript ajax POST issue

I am a problem with simple javascript web page hosted on AWS S3 that makes a HTTP POST to AWS API Gateway using ajax.
I am able to make a call using curl with success:
curl -X POST -H "Content-Type: application/json" https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta --data #data.json
data.json file:
{ "imie": "jasiu",
"ocena": "6",
"opinia": "niezle"
}
My javascript code looks like this.
<html>
<body>
<title>Ankieta</title>
<h1>Wypelnik ankiete</h1>
<button type="button" onclick="uruchom()">JSON</button>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function uruchom() {
var resultDiv = $("#resultDivContainer");
var myData = {"imie": "Michal"};
$.ajax({
url: "https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta",
type: "POST",
data: JSON.stringify(myData),
crossDomain: true,
contentType: "application/json",
dataType: 'jsonp',
headers: {
"Access-Control-Allow-Origin": "*"
},
success: function () {
alert("ok");
},
error: function() {
alert("zonk");
}
});
};
</script>
</body>
</html>
This is the error I get from web debug:
GET https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta?callback=jQuery17203000220305941388_1546897907447&{%22imie%22:%22Michal%22}&_=1546897908872 net::ERR_ABORTED 400
It looks like there is problem with callback and in the URL is altered with my data from body. In my case I don't want to check whenever the callback is fine - want to simply POST data.
Thanks for any suggestions.
POST can't be used to send a JSONP request. JSONP doesn't actually use AJAX, it works by creating a <script> tag whose src is the URL. There's no way to send POST data this way, so the data is added as URL parameters.
If this API expects the JSON in POST data, you can't use dataType: 'jsonp'. You have to use dataType: 'json'. If the API doesn't allow CORS, you'll need to use a proxy on your server to make the actual request, you can't do it directly from the browser.
Dont stringify the data object. JQuery does this for you. Just pass object.
var myData = {"imie": "Michal"};
$.ajax({
url: "https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta",
type: "POST",
data: myData,
crossDomain: true,
contentType: "application/json",
dataType: 'jsonp',
headers: {
"Access-Control-Allow-Origin": "*"
},
success: function () {
alert("ok");
},
error: function() {
alert("zonk");
}
});
Thanks for suggestions and answers especially in CORS direction. I was sure my API GW has CORS enabled, but didn't check AWS Lambda that is behind it and found that I was not returning "Access-Control-Allow-Origin" header back to client.
exports.handler = function(event, context, callback) {
callback(null, {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*"
}
});
};
After applying this, I can send HTTP POST.

Ajax POST error (400 BAD REQUEST)

and thank you in advance for helping me.
I'm trying to make a POST where I pass the TOKEN in the URL and I want to pass another param too so I can save the info in the DB. I have this:
$("#btnAddCompany").click(function(e) {
var token = "123";
var companyValue = document.getElementById("companyValue").value;
var obj ={CompanyId: 4 ,Name: companyValue }
var postData = JSON.stringify(obj);
console.log(postData);
$.ajax({
type: "POST", //REQUEST TYPE
dataType: "json", //RESPONSE TYPE
contentType: "application/json",
data: postData,
url: "http://banametric.ddns.net/BanaMetricWebServices/BanaSov_WS.svc/CompanySave/"+token,
success: function(data) {
toastr.success("Lidl Adicionado!");
},
error: function(err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
}).always(function(jqXHR, textStatus) {
if (textStatus != "success") {
alert("Error: " + jqXHR.statusText);
}
})
});
But I'm getting an 400 error (Bad Request) so I assume that I'm making something wrong, but I don't find out what. The error trace is this:
AJAX error in request: { "readyState": 4, "responseText": "\r\n
The server encountered an error processing the request. The
exception message is 'The incoming message has an unexpected message
format 'Raw'. The expected message formats for the operation are
'Xml', 'Json'. This can be because a WebContentTypeMapper has not been
configured on the binding. See server logs for more
details. The exception stack trace is: \r\n at
System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message
message, Object[] parameters)\r\n at
It's error because of
The expected message formats for the operation are 'Xml', 'Json'.
So you can pass contentType in your ajax call
$.ajax({
....,
contentType: "application/json"
})
I am not sure, but it depends on what server wants to read from you.
Server does not want to read raw bytes, it wants xml or json
Try to add headers like
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
in $.ajax() function
You need to set the content type header in your request to inform the server you're sending the data as JSON.
The error message is telling you that the server does not understand the content you're sending it - you have to give it a hint that the data is in a particular format, especially because, again as mentioned in the error message, it allows you to submit in more than one different format (JSON or XML in this case).
Adding
contentType: "application/json"
to the options in your $.ajax call should resolve the issue.
P.S. We can't see the signature of your controller method but it's possible you may also need to give your parameter a name within the JSON, e.g. something like data: JSON.stringify({ "companyValue": postData }); , but there's not enough info in your question to say for certain what the correct structure should be.
$("body").on("submit", ".example_form", function() {
$.ajax({
url: 'http://example.com/{ROUTE_URL}',
data: new FormData(this),
processData: false,
contentType: false,
/* OR contentType: "application/json; charset=utf-8"*/
type: 'POST',
dataType: "json",
success: function(data) {
console.log(data);
}
});
});
Instead of this
var postData = JSON.stringify(companyValue);
why don't you try this:
var obj ={token :token ,companyValue:companyValue }
And then make use of the json stringify function
var postData = JSON.stringify(obj);
After that in ajax call only change the url:
url: "http://webservice/CompanySave/"

When sending jQuery post to MVC controller getting 404 error

I'm sending from view using jQuery to MVC post action
function DoSomething(passedId) {
$.ajax({
method: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
//
});
}
And inside MyController
[HttpPost]
public ActionResult SomeAction(int id)
{
...
}
In Firebug console I'm getting 404 error.
You didn't said which version of jquery you are using. Please check jquery version and in case that this version is < 1.9.0 you should instead of
method: "POST"
use
type: "POST"
this is an alias for method, and according to jquery official documentation you should use type if you're using versions of jQuery prior to 1.9.0.
function DoSomething(passedId) {
$.ajax({
type: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
...
});
}
Tested above code and it works (each request enter inside mvc controller http post SomeAction action).
In the RFC 2616 the code 404 indicates that the server has not found anything matching the Request-URI.
So you need to look at your URL parameter.
Try the MVC conventional call using :
url: '#Url.Action("SomeAction", "MyController")',
To resolve the 404 issue:
There are a few options to resolve this. You controller/action cannot be find the way it is describe.
-If you are in a view that is in the controller for which the action your are trying to call is located, then:
url: 'SomeAction',
-If you are trying to call an action from another controller, OtherController, for example, then:
url: 'Other/SomeAction',
-To add to another answer, if you are calling your ajax inside the view (and NOT in a javascript file) then you can also use (for a controller called SomeController):
url: '#Url.Action("SomeAction", "Some")',
Additional Items Of Note:
You do not specify a content type for json (contentType indicates what you are sending):
contentType: "application/json; charset=utf-8",
I can't tell, based on your action if you are expecting 'text' or something else. However, unless expecting 'json', I would remove the data part.
You need to stringify your data
JSON.stringify(data: { id: passedId}),
In the end, I would expect it to look something like:
function DoSomething(passedId) {
var url = "SomeAction"; //if action is in OtherController then: "Other/SomeAction"
$.ajax({
method: "POST",
url: url,
data: JSON.stringify({ id: passedId}),
contentType: "application/json; charset=utf-8"
}).done(function (data) {
//
});
}
The slash at the beginning of this designates an absolute path, not a relative one.
/MyController/SomeAction/
You should include a URL or relative path.. maybe
'MyController/SomeAction/ajax.php'
or the full URL
'http://example.com/myajaxcontroller/someaction/ajax.php'
or stolen from the other guys answer
url: '#Url.Action("SomeAction", "MyController")',
To address others on here, I don't think the datatype is the
problem... OP says "I'm getting 404 error."
contentType is the type of data you're sending, so
application/json; charset=utf-8 is a common one, as is
application/x-www-form-urlencoded; charset=UTF-8, which is the
default.
dataType is what you're expecting back from the server: json, html,
text, etc. jQuery will use this to figure out how to populate the success function's parameter.
Write the code this way:
function DoSomething(passedId) {
$.ajax({
url: 'yourController/SomeAction',
type: 'POST',
data: { id: passedId},
dataType: 'json',
error: function (ex) {alert(ex.responseText)},
success: function (data)
{
if (data.Results != null) {
//use the return values
});
}
}
});
}
and the controller
public JsonResult SomeAction(int id)
{
try
{
return Json(new { Results = "Text To return or send some object or an list, etc"}, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
throw;
}
}
Finally, check that the controller has its respective view. :)
and and the library of "jQuery" updated.
just in case.
use the following ajax call
var datum = { id: passedId };
$.ajax({
url: url, // your url
type: 'POST',
data: JSON.stringify(datum),
contentType: 'application/json; charset=utf-8',
beforeSend: function () {
},
complete: function () {
},
success: function (user, status, XHR) {
},
error: function (req, status, error) {
}
});
UpDated
public ActionResult SomeAction(int id){} should accept string parameter instead of int

POST request ajax jquery error

I am trying to run post request to parse json format data into the page. An example query is:
$("#click").click(function () {
$.ajax({
type: "POST",
url: "http://ut-pc-236:9000/kanye/flow/search",
contentType: "application/json;charset=UTF-8",
data: {
"fromDate":"2011-01-01",
"toDate":"2011-03-16T14:35:00Z",
"limitTotalFlows":1000,
"operator":"AND",
"keyValues":[ "J0419:E", "J0410:AMPY", "J1043:BEDFORD" ]
},
success: function (data) {
console.log(data);
}
});
});
but it gives an error - bad request (400). I guess it should be some syntax error since the get method works ok. If anyone can help I would really appreciate it. Thanks
You're not sending a valid json object as you claim to be doing with the contentType.
JSON.stringify your data:
data: JSON.stringify({
"fromDate":"2011-01-01",
"toDate":"2011-03-16T14:35:00Z",
"limitTotalFlows":1000,
"operator":"AND",
"keyValues":[ "J0419:E", "J0410:AMPY", "J1043:BEDFORD" ]
}),

Categories

Resources