POST method is ajax gives 400 (Bad Request) - ajax

This is my ajax
$('#saveButton').click(function(){
alert('savebutton');
$.ajax({
url: projectUrl+"updateDoctor",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
formdata = new FormData();
//self.doctor(new Doctor());
}
});
});
and this is requestmapping
#ResponseBody
#RequestMapping("updateDoctor")
public String updateDoctor(#RequestParam("doctormetada") String doctormetada,#RequestParam(value="image",required=false) MultipartFile image)
{
Doctor doctor=doctorServiceImpl.updateDoctor(doctormetada,image);
return doctor.getId().toString();
}
and this is my save button
<button class="btn btn-primary" id="saveButton"
>
<i class="icon-ok icon-white"></i> Save
</button>
when I am hitting the save button then I am getting the following error in browser console
POST http://localhost:8080/Mo/updateDoctor 400 (Bad Request)
Can any body please tell me what am I doing wrong?

Something in your Service is throwing an exception causing your controller to return a HTTP 400. Check that you are passing all the required data to your service layer in your doctormetada.
Check your application logs to see specifically where you are getting the exception thrown from.

Related

ModelView, Ajax and Json return

In my code, i have two RequestMapper in my Controller which is designed this way :
#Controller
#RequestMapping("/myHostel.html")
public class HostelController
{
#RequestMapping(method = RequestMethod.GET)
public ModelAndView getText()
{
// do some cool stuff but not the point here
}
#RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public String getMyUrl()
{
String myVariable;
return "{\"myUrl\": \""+myVariable+"\""}";
}
}
And my ajax code :
function openNewTab() {
$.ajax({
url : 'myHostel.html',
type: "POST",
dataType: "json",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
},
success : function(response){
console.log(response);
window.open(response.url, '_blank');
},
error: function(jqXHR, exception, errorThrown)
{
console.log(jqXHR.status);
console.log(exception);
console.log(errorThrown);
}
});
}
and my button is kinda like this :
<button tabindex="0" id="mySweetButton" class="btn btn-primary"
onclick="openNewTab();" >
Open a new tab
</button>
And what i get is :
200
parsererror
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
--
I've tried with putting a session variable in the model and a making a window.open(URL_IN_SESSION);
But if you reload the page, it's calling it again.
Making a c:remove on the variable when it's not used to cancel this problem but to no avail.
I have to get a variable from my ModelView after some previous call and open it in ajax (or javascript whatever as long as it works) to have my main page and my new tab with the custom URL.
If anyone has a idea on what i'm doing wrong ? (I need a custom URL made in my controller by previous GET call with user choices.)
Thank you for reading !
Solved by making just another GET requestMapping using no parameters and with value = ("/myHostel.html/getMyUrl.html")
One of the problem was the filters that only allowed .html url for the mapping.
The other was the JSON, just using :
#RequestMapping(method = RequestMethod.GET, value = "/getUrl.html")
public ResponseEntity<String> sendUrl()
{
return new ResponseEntity<>(getMyUrl(), HttpStatus.OK);
}
And parsing the return in ajax :
function openNewTab() {
$.ajax({
url : 'myHostel.html/getUrl.html',
type: 'GET',
dataType: 'text',
success : function(data){
window.open(data, '_blank');
}
});
}
And it solved the problem.

Ajax post gives 404 error in Spring

I am making an ajax call to the controller from jsp overlay page. The controller is invoked, but the browser throws a 404 error page. I want the control to be on the overlay page
jsp page snippet:
<s:form action="expressEOI" class="form-horizontal" method="POST"
enctype="multipart/form-data" modelAttribute="expressEOIBean">
<div class="form-group"></div>
........
<button class="btn btn-info" name="eoiSavebtn" id="eoiSavebtn">Please
Save </button>
$(document).ready(function() {
.....
$('#eoiSavebtn').attr('onClick','javascript:saveEOI("'+contextPath+'","'+ applicationId+'")');
ajax call:
$.ajax({
type : "POST",
url : window.location.protocol + "//"+ window.location.host + contextPath+ "/saveEOI",
cache : false,
data: {'applicationId' : applicationId},
success : function(e) { alert("success"); },
error : function(e) { }
});
controller:
#RequestMapping(value = "/saveEOI", method = RequestMethod.POST)
public String saveEOI(HttpSession session, HttpServletResponse response,
HttpServletRequest request) {
if (logger.isDebugEnabled()) {
logger.debug("ExpressEOIController :: Save EOI() : Start");
}
.....
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 issue. Also make sure to add content type header as 'application/json'
This will help in isolating the issue 

Image upload with jquery

I am trying to upload an image file from a partial view using AJAX but it is returning a Bad Request(400) error. I have searched SO answers but it is not working. Here is my script :
$("#prodImgUpload").change(function() {
var formData = new FormData();
formData.append("file", $("#prodImgUpload")[0].files[0]);
console.log(formData.get("file"));
addAntiForgeryToken(formData);
$.ajax({
type: "POST",
url: "#Url.Action("UploadImage","Product",new{area="admin"})",
data: formData,
processData: false,
contentType: false,
cache: false,
async: false,
success: function(result) {
alert("Image uploaded successfully");
},
error: function(jqXHR, textStatus, errorMessage) {
alert(errorMessage);
}
});
And here is the HTML :
<div class="upload-button">
<div class="label">Upload image</div>
<input asp-for="FileToUpload" id="prodImgUpload" name="FileToUpload"
type="file" accept="image/jpeg, image/png, image/jpg, image/bmp" />
</div>
It never reaches the controller. And remember it is in partial view.
Here's my controller's action :
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult UploadImage(IFormFile file)
{
if (file == null)
return Json(new { success = false, message = "No file uploaded" });
//do something with file.
}
You're not including the antiforgery token with the AJAX request. Reference the documentation for how to handle AJAX request with antiforgery tokens. Essentially, you need to add a header to your AJAX request:
$.ajax({
...
headers: {
"RequestVerificationToken": $('#RequestVerificationToken').val()
},
The value comes from a hidden input added via:
#inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
#functions{
public string GetAntiXsrfRequestToken()
{
return Xsrf.GetAndStoreTokens(Context).RequestToken;
}
}
<input type="hidden" id="RequestVerificationToken"
name="RequestVerificationToken" value="#GetAntiXsrfRequestToken()">

$.ajax POST prompting authentication dialog

I am trying to call a WebMethod using AJAX POST but the browser keeps opening an 'authentication dialog'. I've not encountered this problem before using similar code detailed below.
In my search.aspx file I have the following:
HTML
<a href="javascript: ExpandChild('div4');" runat="server"> <img alt="Students" id="imgdiv4" src="images/arrow-right-b.png" />
</a>
JS
function ExpandChild(input)
{
//somethings are done here
LoadStudentData();
}
function LoadStudentData()
{
$.ajax({
type: "POST",
url: 'webmethods.aspx/TestCall',
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: 'json',
success: function (data) {
alert("ajax called");
},
error: function (result) {
alert("An unknown error occurred, please try again: " + result.responseText);
}
});
}
In my webmethods.aspx file I have the following:
[WebMethod()]
public static string TestCall()
{
return "it worked";
}
I know the code gets the to the LoadStudentData method but I have no idea why it is then opening an authentication dialog. Both the search.aspx page and the webmethods.aspx page are in the root of my project
I am using Visual Studio 2015 and this problem occurs in Chrome and Firefox when run on my local machine. When debugging the code it never gets to the TestCall method.
Any help much apprecciated.
Following this article
http://www.aspforums.net/Threads/105222/Error-SystemInvalidOperationException-Authentication-failed/
In the App_start/RouteConfig.cs I changed
settings.AutoRedirectMode = RedirectMode.Permanent;
To
settings.AutoRedirectMode = RedirectMode.Off;
Then the ajax post worked fine.

Error while sending List<String> in multipart request

I am trying to send a multipart request to a controller service which looks like following
#RequestMapping(value="/uploadFile", method=RequestMethod.POST)
public void uploadApk(#RequestPart("fileName") String fileName,
#RequestPart("md5") String md5,
#RequestPart("userList") List<String> userList,
#RequestPart("file") MultipartFile file){
...
...
}
The ajax request for calling the above function is
var formData = new FormData();
formData.append("fileName",imgfileList[0].name);
formData.append("md5",md5);
formData.append("userList",userList);
formData.append("file", imgfileList[0]);
$.ajax({
url: urlPost,
type: "POST",
data: formData,
dataType: "json",
processData: false,
enctype:'multipart/form-data',
headers: {'Content-Type': undefined},
success: function(data)
{
alert("File Uploaded!");
}
});
I have tried to follow this link
But i am getting the following error.
{"timestamp":1434485164651,"status":415,"error":"Unsupported Media Type","exception":"org.springframework.web.HttpMediaTypeNotSupportedException","message":"Content type 'application/octet-stream' not supported","path":"/uploadFile"}
I tried to debug the error and found that the error was coming only for "#RequestPart("userList") List userList". That is the error appears only while sending an array of strings.
How do I solve the problem ?

Resources