retrieve data send from post ajax req - java

I need to send large amount of string in a ajax post request to server. If i add it the end of the url, i can get using request.getParameter() method in the server.
But i can't append large string in the url.So i want to send using the method send() of XMLHttpRequest instead of appending it to url.
But i couldn't retrieve the same using request.getParameter() in server.
How to retrieve data send from ajax request in j2ee server?
Please guide me.

If you have an ajax intensive webapp, I would suggest using a javascript library (such as jquery) to handle ajax. In jQuery, you could do this as :
$.post("your_url.php", { param1: "value1", param2: "value2" } );

Regardless of whether you are or arent using AJAX, there are limits to the actual length of the Url which changes browser to browser.
It will be better POST all your data. Below is the code to do the same using AJAX:
var http = new XMLHttpRequest(); // Get the correct http object depending on browser
var url = "YOUR_URL.php";
var params = "param1=value1&param2=value2";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() { // Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
Hope this helps.

Related

Ajax: '+' Symbol becomes '' when submitting the form using ajax to the spring controller [duplicate]

I have session key that is a JavaScript variable which I got from a REST API call. I need to call my Java code in a servlet and pass that key as a parameter. What JavaScript function can I use to do that?
Several ways:
Use window.location to fire a GET request. Caveat is that it"s synchronous (so the client will see the current page being changed).
window.location = "http://example.com/servlet?key=" + encodeURIComponent(key);
Note the importance of built-in encodeURIComponent() function to encode the request parameters before passing it.
Use form.submit() to fire a GET or POST request. The caveat is also that it"s synchronous.
document.formname.key.value = key;
document.formname.submit();
With
<form name="formname" action="servlet" method="post">
<input type="hidden" name="key">
</form>
Alternatively you can also only set the hidden field of an existing form and just wait until the user submits it.
Use XMLHttpRequest#send() to fire an asynchronous request in the background (also known as Ajax). Below example will invoke servlet"s doGet().
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://example.com/servlet?key=" + encodeURIComponent(key));
xhr.send(null);
Below example will invoke servlet"s doPost().
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://example.com/servlet");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("key=" + encodeURIComponent(key));
Use jQuery to send a crossbrowser compatible Ajax request (above xhr code works in real browsers only, for MSIE compatibility, you"ll need to add some clutter ;) ).
$.get("http://example.com/servlet", { "key": key });
$.post("http://example.com/servlet", { "key": key });
Note that jQuery already transparently encodes the request parameters all by itself, so you don"t need encodeURIComponent() here.
Either way, the key will be just available by request.getParameter("key") in the servlet.
See also:
How to use Servlets and Ajax?
Access Java / Servlet / JSP / JSTL / EL variables in JavaScript
No JavaScript function per se, but browsers usually* provide an XMLHttpRequest object and you can go through that.
Libraries such as YUI and jQuery provide helper functions to simplify its usage.
* for a value of "usually" that includes pretty much any browser that supports JavaScript and was released since Netscape 4 died
When sending POST add header
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
The code looks like
Client:
function executeRequest(req) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.getElementById("response").value = xhttp.responseText;
}
};
xhttp.open("POST", "execute/cardbrowser", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("lorem=ipsum&name=binny");
}
Server:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(req.getParameter("lorem"));
}

How to display data of MYSQL in java with using of AJAX

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

Jquery AJAX Result data retrieve back to client side in velocity template

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

How to call a URL with params and get back response in servlet?

I have a situation where a intermediate servlet needs to be introduced which will handle requests from existing project and redirect the manipulated response to either existing project or the new one. This servlet will act as an interface to login into the new project from some other application.
So currently I use the following code to get back response in jsp as an xml.
var jqxhr =$.post("http://abhishek:15070/abc/login.action",
{ emailaddress: "ars#gmail.com",
projectid: "123" },
function(xml)
{
if($(xml).find('isSuccess').text()=="true")
{
sessiontoken=$(xml).find('sessiontoken').text();
setCookie("abcsessionid", sessiontoken , 1);
setCookie("abcusername",e_add,1);
}
}
)
.error(function() {
if(jqxhr.responseText == 'INVALID_SESSION') {
alert("Your Session has been timed out");
window.location.replace("http://abhishek:15070/abc/index.html");
}else {
alert( jqxhr.responseText);
}
});
xml content
<Response>
<sessiontoken>334465683124</sessiontoken>
<isSuccess>true</isSuccess>
</Response>
but now I want the same thing to be done using servlet, is it possible?
String emailid=(String) request.getParameter("emailaddress");
String projectid=(String) request.getParameter("projectid");
Update
I just came up with something.
Is it possible to return back a html page with form (from servlet), whose on body load it will submit a form and on submission of this form it will receive the response xml which will get processed.
Use java.net.URLConnection or Apache HttpComponents Client. Then, parse the returned HTTP response with a XML tool like as JAXB or something.
Kickoff example:
String emailaddress = request.getParameter("emailaddress");
String projectid = request.getParameter("projectid");
String charset = "UTF-8";
String query = String.format("emailaddress=%s&projectid=%s",
URLEncoder.encode(emailaddress, charset),
URLEncoder.encode(projectid, charset));
URLConnection connection = new URL("http://abhishek:15070/abc/login.action").openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
try {
connection.getOutputStream().write(query.getBytes(charset));
}
finally {
connection.getOutputStream().close();
}
InputStream response = connection.getInputStream();
// ...
See also:
Using java.net.URLConnection to fire and handle HTTP requests
HttpClient tutorial and examples
Actually, what you probably want is not an intermediate servlet at all. What you probably want is called a servlet filter and writing one is not particularly hard. I've written one in the past and I just started on a new one yesterday.
An article like this one or this one lays out pretty simply how you can use a servlet filter to intercept calls to specific URLs and then redirect or reject from there. If the incoming URL matches the pattern for the filter, it will get a shot at the request and response and it can then make a choice whether or not to pass it on to the next filter in line.
I don't know if all third party security solutions do it like this, but at least CAS seemed to be implemented that way.

How to send and receive an ajax request with jQuery?

I am new to jQuery and am having trouble following the documentation. I have a variable in JavaScript (that I already obtained from an html form) that I would like to send using AJAX to the server. I want to the server to do whatever it needs to do with that value and then reply with either "success" or "failure" (I know how to do the backend part). How do I send the request and then receive the reply with jQuery?
To send the request you use the $.post or $.get function (or the $.ajax function if you want loads of control)
$.post('example.com/script', {
'param1':somaVar
}, function(data){
alert(data); //data is whatever the server returned
});
For both $.get and $.post the argument order is like this: (url, [data], [callback], [type]). Url is the url to which the request is done, data is the data with which the request is send, callback is a function that is executed when the request is complete. Type is the type of data the server will return (jQuery usually finds this out on itself) possibles are "xml", "html", "script", "json", "jsonp", or "text"

Categories