I'm trying to make an Ajax call to my Spring MVC app using a Jquery Ajax. The app controllers are working fine but I can't get this Ajax test controller to work. The alert is triggered but the call to the controller is never made. I've also tried using load, get, post. None of them call the server. Which makes me think I'm doing something obviously wrong. If I put the URL directly on the browser address bar, the controller is called.
If someone can guide me in the right direction or tell me what I'm doing wrong, I'd be grateful.
JavaScript
<html>
<head>
<script type="text/javascript" src="jquery-1.8.1.min.js"> </script>
<script type="text/javascript">
function doAjax() {
alert("did it even get here?");
$.ajax({
url : "simpleRequestTest.do",
method: "GET",
success : function(response) {
$('#show').html(response);
}
});
}
</script>
</head>
<body>
<h1>Simple Test </h1>
Simple Test
<br />
<div id="show">...</div>
</body>
</html>
Controller
#RequestMapping("/simpleRequestTest")
public #ResponseBody String performSimple() {
return "Very Simple Test";
}
Can you check whether you use correct path for include the jquery-1.8.1.min.js.
I checked the code it's working file for me.
I think you are missing dataType in ajax call
try this
function doAjax() {
alert("did it even get here?");
$.ajax({
url : "simpleRequestTest.do",
method: "GET",
success : function(response) {
$('#show').html(response);
},
dataType: 'text'
});
}
Just change url : "simpleRequestTest.do", to url : "simpleRequestTest", and method: "GET", to type: "GET",
I think the method is removed in the jquery version 1.5 and latest
Related
Environment: IE7, jQuery 1.1 , Struts 1
Context: Making an ajax call to a Java method which, and the end, reloads the same jsp.
The steps are: jsp A -->request to java method-->doing some stuff-->ActionForward to jsp A, which is returned in the response.
Actually I'm doing this with a single request using location.href and it's working properly.
Now I need to handle multiple requests and conditions and the only way I thought was by using nested ajax calls with async:false, but that's not the point.
The problem is ajax does not reloads the jsp like location.href does.
This jsp is just a smaller part of the main jsp, so I'm not reloading the whole jsp. I guess I have to handle the response in some way, but how?
Call with location.href:
<script>
function myFunction(){
location.href = 'path/to/java/method=with_some_parameters';
}
</script>
Call with ajax:
<script>
function myFunction(){
jQuery.ajax({
url:'path/to/java/method=with_some_parameters'
async:false,
success:function(data){
//nested ajax
}
});
}
</script>
There is a similiar question:
Reload a page after jquery ajax call,
but it didn't help.
Another: How to manage a redirect request after a jQuery Ajax call, this looks better. I'm trying some things.
As I got the full html in the response ('data' in my case), It worked using
function myFunction(){
jQuery.ajax({
url:'path/to/java/method=with_some_parameters'
async:false,
success:function(data){
document.open();
document.write(data);
document.close();
//nested ajax
}
});
}
Source Replacing Entire Page Including Head Using Javascript
new to angularjs. I am sure i am missing something.
I am unable to render the response send by server on jsp page if i hit server with angularjs's $http directive.
angularcode
// Read button Handler
$scope.readAll=function(){
readTable($scope.clnfamilyArray);
//send data to server
testAddItem=function(){
$http({
'url' : 'http://localhost:9090/QuantumM/orbital/sendstatement/',
'method' : 'POST',
'headers': {'Content-Type' : 'application/json'},
'data' : $scope.clnfamilyArray
}).success(function(data){
console.log(data);
})
}//end of function
testAddItem();
}////end of readAll
spring code
#RequestMapping(value = "/sendstatement/", method = RequestMethod.POST)
public ModelAndView welcome(#RequestBody String map) {
ModelAndView model = new ModelAndView();
// BL
model.addObject("name",hTable.toHtml());
model.setViewName("test");
return model;
}
test.jsp
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<h1>Gradle - Spring MVC Hello World</h1>
<h2>Hello ${name}</h2>
</body>
</html>
Instead of rendering test.jsp. I am landing on the same page. But on console I can see the expected output..
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<h1>Gradle - Spring MVC Hello World</h1>
<h2>Hello <table border=1><tr><td colspan=2>s</td></tr><tr><td colspan=1>f</td><td colspan=1>d</td></tr></table></h2>
</body>
</html>
Is there anything which I am missing ???
I wanted to landed on test.jsp not on my current calling page...
You are missing something, as you guessed. The purpose of the $http call is to fetch the results of an HTTP call and provide it to your AngularJS application's model. It is not meant to redirect you to a new page on another server.
The reason you see the page output in the console is due to the .success() portion of the http call:
$http({
'url' : 'http://localhost:9090/QuantumM/orbital/sendstatement/',
'method' : 'POST',
'headers': {'Content-Type' : 'application/json'},
'data' : $scope.clnfamilyArray
}).success(function(data){ // The data is passed here when received
console.log(data);
})
It's an async call handled by a promise. So your app makes the http call, and then goes on its merry way. When the data from that http call is available, it is passed to your .success() call and then you log it to the console. Here's a Plunk demo I did showing how promises work in serial and parallel so you can see some of their benefit.
This is not the Angular way. What you should be doing for a single-page-app in AngularJS is fetch the DATA from the server, not a rendered page, and then display it to the user with AngularJS views.
Instead of having your SpringMVC app render the view, have it pass the model back as JSON data. That way, you will be able to easily show it to the user in your AngularJS view.
My guess is that if you took your example and had it return JSON, it would return something like:
{
"name": "Bob"
}
Then you would change the .success() call to do something like this:
.success(function(data) {
$scope.name = data.name;
})
And in your view, you would show it with:
<p>Hi {{name}}</p>
Hope this helps.
I am trying to make a login page in java J2EE. Actually, I succed in making a jsp page, called login.jsp, an ActionSupport class called LoginAction. In my jsp I've created some text area, password area and submit, allowing me to send informations entered in those areas and get them in my action. This works fine.
My problem is that I don't succed in using another function than execute. In my action I have several other functions and I can't call them in my ajax function :
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
$(function() {
$('#submit').click(function() {
var login=$("#login").val();
var password=$("#password").val();
$.ajax({
type: 'POST',
url: 'login.action/test', // -> here it fails.............
data: { login: login, password: password },
success: function() {
alert('YEAH'); },
error: function() {
alert('Request failed'); }
});
});
});
</script>
What should I put in url area, if I want for example to call test function in my LoginAction class? (I've done a test.jsp page, it doesn't change anything...)
OK I found the answer. So here it is :
It's called "dynamic method invocation" (with wildcard method), and you can find the doc here :
http://struts.apache.org/release/2.0.x/docs/action-configuration.html#ActionConfiguration-WildcardMethod
It is very important to use last struts2 release to avoid critical security bugs while using wildcard method - see https://struts.apache.org/release/2.3.x/docs/s2-015.html for details.
use "function nametest()" instead of "function()"
i have some.jsp file which also contains javascript/jquery. i need to do below check in javascript part of some.jsp file.based on the condition i need to display a message/ forward the request to servlet which in turn servlet forwards to other.jsp.
I wrote below code:
<script type="text/javascript">
$(document).ready(function() {
var isInIframe = (parent !== window);
if (!isInIframe) {
$.ajax({
type: "GET",
url: "./screenInitializer",
success: function() {},
error: function(ob,errStr) {
alert("Failed. Try Again.","error");
}
});
}else{
$("#accessDenied").text('Access Denied');
}
});
</script>
I can call a servlet using jquery ajax. forward request to jsp is not working.it is displaying a blank page instead of other.jsp. forwards request to other.jsp as below.
//Keeps some values using request.setAttribute() then forward the request
request.getRequestDispatcher("/WEB-INF/other.jsp").forward(request, response);
Basically i dont want any response from ajax call. it just need to call the servlet which in turn servlet forwards to the jsp and displays other.jsp.all My jsps are in WEB-INF folder. Am i doing anything wrong?
Thanks!
I am having a problem. I have a form submit that uses jQuery JSONP to make a call BACK to my servlet. This code is embedded in another domain, hence the usage.
Here is my form submit AJAX:
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js' type='text/javascript'></script>
<script language='Javascript' type='text/javascript'>
$(\"#form1\").submit(function(event) {
event.preventDefault();
var $form = $(this),
choice2 = $form.find( 'input[name=\"personChoice\"]' ).val(),
url = $form.attr( 'action' ),
$.ajax({
data: {choice:choice2},
url: url,
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'updatePage'
});
});
function updatePage(renderHTML) {
alert(renderHTML);
}
</script>
I can confirm in my Java servlet that the request.getParameter("callback") is populated with updatePage. What I need to do is send back a response in JSONP format within the Java Servlet. How does one do that? I have something really simple like this at the moment:
Java Servlet code:
response.setContentType("text/javascript");
PrintWriter out = response.getWriter();
String renderHTML = "{ renderHTML = 'Successful'}";
out.println(renderHTML);
I also tried JSON content type response, the alert in my javascript updatePage doesn't get called.
What is the trick with Java servlet's and response back on a jsonpCallback???
A JSONP response must be wrapped inside a function call which is specified in request with callback.
Something like
callback({ renderHTML = 'Successful'});
This should usually be taken care at a filter.
The jsonpCallback property is not what you think it is. It's a string (or a function returning a string) which jquery will use as part of the request URL. You can set it to false if you don't need that functionality. See the docs
You should use the 'success' property to set the response handler.
Something like this:
$.ajax({
data: {choice:choice2},
url: url,
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: false,
error: function(xhr, status, error) {
alert("error");
},
success: updatePage
});
Also, the best content-type to use for JSONP is application/javascript.
Hope that helps.