I have just created an AJAX request in velocity template and able to get request at .java file as below: (java file is extended for "JiraWebActionSupport" as webwork module).
var url = "PlanIssuesAction!IssuesPlanning.jspa";
jQuery.post(url,myJSONObject,function(result) {
alert('success');
})
.done(function() { alert("in done"); })
.fail(function() { alert("error"); })
.always(function() { alert("finished"); });
On the server side, in doIssuesPlanning method, able to get call and insert the posted data.
public String doIssuesPlanning() {
System.out.println("Success executed result appear"); //i want this value to be //retrieval at client side but it's not working. unable to receive at ajax response.
return getRedirect("PlanIssuesAction!default.jspa");
//return "result is success" //also tried instead of getRedirect ,used direct response //return but not worked, it capture at error in ajax response at client side.
}
Now I need to return the result data to the client side back at jquery "Result" parameter.
How can I achieve this? Currently, in "Result" object shows all HTML text and nothing else.
(i have set object above through - "System.out.println and expect to be retrieved at client side but not working).
Can you please let me know , what is wrong here.
Thank you.
Webwork jspa URLs return HTML since that is their purpose. Most AJAX calls would be to a REST resource that returns JSON. I'd define a new REST resource for this. More information at https://developer.atlassian.com/display/DOCS/Developing+a+REST+Service+Plugin
Related
I have one table in mysql which has three field with data inserted. there are three fields in it which are as below.
i want to display this data on a web browser with using ajax in java.
i search on a net and find this below code are most useful
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/ajax_demo","root","");
PreparedStatement ps=con.prepareStatement("select * from ajax");
what are other things i have to implement for displaying output.
You need to do a AJAX request, the main code body for an ajax request is the following
request.onreadystatechange=handleResponse;
request.open(typeReq, url, true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
request.send(queryString);
typeReq is the type of the request: POST or GET.
url: the destination url address.
queryString: the set of data which you want to send.
handleResponse is a function to hanled the response. For example:
function handleResponse () {
if (request.readyState = 4) {
if (request.status = 200) {
var response = request.responseText;
//code to handle response
} else {
//code to handle errors
}
}
Now, you can use an API like prototype or jquery, it's easier.
I hope this information helps you.
Good Luck
is it possible to call java method within a javascript function? Let me explain my problem:
I am working with JSP (have to) and I have a JavaScript form validator which is checking whether a entered value is allowed. It depends on whether there already is such an entry in my MySQL DB. The Script looks like the following:
<script type="text/javascript">
<% DbConnection db = new DbConnection(); %>
function validateForm()
{
var x=document.forms["form"]["name"].value;
if (<%= db.validateName("%> x <%=") %>)
{
alert("Themenname bereits vergeben.");
return false;
}
}
</script>
So what I have to do is passing the entered value (javascript parameter) to my java method (db.validateName) in order to receive a boolean value.
Any idea how to solve this? Java runs server-side whereas JS runs on the client-side, right? Unfortunately I have no clue on how else I could validate from mySQL db.
Thanks in advance! :)
You need send to the server your validation, with AJAX, you can use a Servlet or another JSP validation that receives the validation input and response with validation result/message to the client.
render your html -> fire the event to validate -> send to the servlet/jsp in to server side -> validate into server -> response to the cliente -> in the client receive the server response -> in the client side render the validation menssage -> process form
You have to use AJAX.
You can have a look at DWR also if you want, here is the link http://directwebremoting.org/dwr/index.html
I am studying on the Spring MVC showcase example dowlodable from the STS dashboard.
In this time I am studying on the Converters section of this example and I have some question for you.
To start, in my view I have the following two links:
<li>
<a id="writeJsonAccept" class="writeJsonLink" href="<c:url value="/messageconverters/json" />">Write JSON via Accept=application/json</a>
</li>
<li>
<a id="writeJsonExt" class="writeJsonLink" href="<c:url value="messageconverters/json" />">Write JSON via ".json"</a>
</li>
The first link generate an HTTP Request towards the URL: messageconverters/json
The second link generate an HTTP Request towards the URL: /messageconverters/json.json (differently from the first URL this one end with .json extension
Ok, both these links have class="writeJsonLink" and related to the click event of these links the following JQuery callback function is called:
$("a.writeJsonLink").click(function() {
var link = $(this);
$.ajax({
url: this.href,
beforeSend: function(req) {
if (!this.url.match(/\.json$/)) {
req.setRequestHeader("Accept", "application/json");
}
},
success: function(json) {
MvcUtil.showSuccessResponse(JSON.stringify(json), link);
},
error: function(xhr) {
MvcUtil.showErrorResponse(xhr.responseText, link);
}});
return false;
});
This function only execute an AJAX call and wait for an HTTP Response passing its content to an handler that will show the output in the view...ok...
Before sending the request, the function check if the URL don't end with .json extension
If this request don't end with .json extension the following header is added to my HTTP Request:
Accept = application/json
From what I know the Accept Header say which specific mediatype is considerable acceptable for the HTTP Response, in this case say that the only acceptable media type is a JavaScript object having JSON format, ok...
This Request is handled from the following method of my controller class that return a valorized object that will be converted in JSON forma using Jaxb2RootElementHttpMessageConverter
#RequestMapping(value="/json", method=RequestMethod.GET)
public ResponseEntity<JavaBean> writeJson() {
// Oggetto che rappresenta gli HTTP Header dell'HTTP Response
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
return new ResponseEntity<JavaBean>(new JavaBean("bar", "apple"), headers , HttpStatus.OK);
// return new JavaBean("bar", "apple");
}
Now, my question is about the differences from the two links.
The first one don't end with .json extension, so the Accept header is added and it is setted on application/json sayng that the browsers expects to receive a JSON object
The second one end with .json extension, so the Jquery method don't set the Accept Header
But, this thing what mean? that when an URL end with .json the Accept header is automatically setted? Or more generally, when I have an URL that end with some kind extension (for example like .xml) the relative Accept header is automatically setted?
Or simply in this second case, don't set the Accept Header mean don't handle the media type that I can recive in the body of the HTTP Response?
Ok, your english is not-so-hot, so let me try to help you the best I can.
In my understanding, which may very well be wrong, is that you want to know if the browser will set the Accept: header to be json when the URL ends in json? I do not believe this is the case. I may be greatly mistaken on this, but you can test this by using something like Firebug or Chrome's Developer Tools, or if you like IE get Fiddler, and see exactly what headers get sent from the browser.
Now, if you are asking if Spring will magically put the headers there, then again I think the answer is "no". The HTTP headers on the request come from the browser, and although you could put in a Servlet Filter or something to set the request filters, I think this would be dangerous to assume all browsers handle these request headers the same way.
No, if the question is "how are my requests all getting to my Controller's writeJson() method?", then the answer has nothing to do with the "Accept" header at all. Your method is matching on any URI pattern that ends in /json, and in both cases your URL ends in /json. If you want to filter on things that have an "Accept" header of JSON, then I think you want to do something like this:
#RequestMapping(value="/someUriPattern", headers = {"Accept=application/json"})
Please understand I typed the above from memory, so you may need to tweak it a tad.
Let's say I need to upload files to a server programmatically using uploading a file programmatically can a server whatever php java or asp.net return me a value when using POST request method instead of GET ?
If not how can I ask the server which files have been uploaded correctly or that uploads have finished ?
I mean if the server is ANOTHER server than mine I can't see how to get the response so can you give some sample code or refer to some urls.
It can, same way as GET requests e.g. server can answer with JSON format string response which will include uploaded files or it can return full html page, whatever you need.
E.g. if you want to send some data to server using POST method and you want to alert it you can do something like this (jQuery):
$.ajax({
type: "POST",
url: "http://localhost/testing.php",
data: { name: "John Doe" } // sample data sent to server
}).done(function( msg ) {
alert( "Response data: " + msg );
});
Generally it shouldn't matter if it was GET or POST, response is returned from server, the only thing you need to do is catch it and perform actions based on response content.
I use jQuery and AJAX to load content from links and forms into a content div. In addition I use the Address plugin to enable the back button and refresh. On the server side I use Java and Spring MVC.
Since I'm using jQuery Address and AJAX the only page that is directly loaded is "index.html". Everything else is loaded into a content div, and what page to load is specified in the hash, ie. "index.html#/users/add.html" will load "users/add.html".
Now, "users/add.html" contains a form for creating a new user. When the form is submitted and everything went OK, the controller redirects to "users/index.html". The problem is that jQuery Address doesn't know about the redirect, so the url will remain "index.html#/users/add.html". And this is a problem when you refresh the page and then get sent back to the form, instead of the index page.
Is there a way to fix this problem?
Thanks,
Stian
Take a look at the new Form Sample. It's very basic but will be probably usable.
http://www.asual.com/jquery/address/samples/form/
In your case you won't be able to use $('form').address() function because you will want to change the address after the server response comes back.
You can use a data.redirect property to detect potential response redirects:
How to manage a redirect request after a jQuery Ajax call
I realize my description of the problem wasn't the best, apologies for that.
I reformulated the problem in another question, got no answers but I found a solution myself. :)
AJAX - Get response URL after redirect
First I init my form like that :
$('FORM').submit(function () {
shareData = $(this).serializeArray();
$.address.value($(this).attr('action'));
})
after I have in my change method something like that :
$.address.change(function(event) {
if (event.path != '/' && event.parameters.layout_to_use != undefined) {
// if no json, load don't do a post request
shareData = _arrayToJson(shareData);;
$('#areatoreload')
.html('<span style="background-color:red;">loading...</span>')
.load('myscript.php', shareData, function() {});
}
return false;
});
And i manage my link in the same way. I hope it can help you. shareData is not a very good way, but i don't find something else for the moment. this code is not tested, I just extract some part of my own code.