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
Related
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.
I am using ajax post with parameters to spring mvc controller,data is binding well but not returning into success.Response is going to another page.
I am calling ajax from a modal and success message need to be returned into same modal.
Following is my ajax call,
$.post({
url : 'saveEmployee',
data : $('form[name=employeeForm]').serialize(),
processData: false,
success: function (resp) {
alert("hello");
},
failure: function (resp) {
alert("hello1");
}
})
Following is my controller code,
#RequestMapping(value="/saveEmployee", method = RequestMethod.POST)
#ResponseBody
public void Insert(ModelMap model, Principal principal,HttpSession session,#ModelAttribute #Valid Profile profile,
BindingResult result) {
System.out.println("profilec "+profile.getRashi());
}
Data is getting binded well but, empty page is returned as response, success response need to be returned to same modal.
I was working on PayU Payment gateway integration in Spring MVC where i was supposed to use the jars of already implemented java classes. In order to do that i created a controller class where i call the required methods of the included jars. Now when i am making the ajax request it is showing me the following error:
Failed to load
http://localhost:8081/ABHI/payupg/payReqHDFC/600/SAU/Robert/robert#gmail.com/9876543210?{}:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
My Ajax request is as follows:
<html>
<head>
<script type="text/javascript" src="C:/Users/myFolder/Desktop/code_testing/jquery.js"></script>
<script type="text/javascript">
function test(){
var testData = {}
//var testData = {"userName":"robert","password":"Test#12345"}
var URL= "http://localhost:8081/ABHI/payupg/payReqHDFC/600/SAU/Robert/robert#gmail.com/9876543210";
$.ajax({
url : URL,
async :false,
type : 'GET',
dataType : 'json',
data: JSON.stringify(testData),
contentType : 'application/json',
mimeType : 'application/json',
crossDomain : true,
success : function(data) {
console.log(JSON.stringify(data,null,4));
alert(data);
},
error : function(data, status, er) {
console.log(JSON.stringify(data,null,4));
console.log("Errors : "); //+data.responseJSON.errorMessage
}
});
}
</script>
</head>
<body>
<button onClick="test()"> Click me </button>
</body>
</html>
My PayUController.java is:
#Controller
#RequestMapping(value = "/payupg")
public class PayuController {
#Autowired
HdfcController hdfcController;
#RequestMapping(value = { "/payReqHDFC/{amount}/{productInfo}/{firstname}/{email}/{phone}" },
method = {org.springframework.web.bind.annotation.RequestMethod.GET })
public String paymentGateway(Model model, #PathVariable String amount, #PathVariable String productinfo,
#PathVariable String firstname, #PathVariable String email, #PathVariable String phone) throws Exception {
System.out.println("inside controller");
String str=hdfcController.payReqHDFCGateway(model,null,amount,productinfo,firstname,email,phone,null,null,null,null,null,null,null,null,null);
System.out.println("End of inside controller");
// return "hdfcPayReq";
// return PGConstants.HDFC_PAY_REQ_PAGE;
return str;
}
}
For more clarification i would like to say you can avoid the CROS-Origin issue.
In this Payment gateway almost 15 parameters are the there to be sent out of which 5-6 are mandatory. I am sending those only and rest i am setting null.
I'm making an ajax post call on click of a button as below. But on success, the page is again submitted to the form-post url on the jsp page. I'm not sure why this is happening and how I can prevent the same.
Ajax call:
var urlsub = window.location.protocol + "//"+ window.location.host + contextPath+ "/saveEOI";
$.ajax({
type : "POST",
url : urlsub,
cache : false,
async: false,
data: {'applicationId' : applicationId
},
success : function(data) {
alert("success");
},
error : function(e) {
console.log(e);
}
});
The success alert is successfully shown, but after that another post request is generated for the jsp page form action...which causes a 405 error. I want to stop the execution after success.
<s:form action="expressEOI" class="form-horizontal" name= "EOI" id="EOI"
enctype="multipart/form-data" modelAttribute="expressEOIBean">
Request if anybody can help me out..where I am going wrong.
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.