How to send call to JSP from AJAX? - ajax

This servlet code,here 1st i want to send return message(if message!=null) to the Ajax for alert and 2nd one if message==null i want to call another jsp with pass the list to this jsp.
if(message!=null){
response.setContentType("text/plain");
response.getWriter().write(message);
}else{
JSONObject jobj = new JSONObject();
String urlToRedirect = "SearchEmployee.jsp";
jobj.put("url",urlToRedirect );
response.getWriter().write(jobj.toString());
}
Here i cant understand how to call this jsp url in else part
$.ajax({
type:"POST",
url:'../SearchEmployeeServlet',
data:$('#DisplayEmployeeListForm').serialize(),//$('form').serialize();
success:function(msg){
if(msg!=""){
alert(msg);
window.location.reload(true);
}else{
....here i want to call 2nd jsp
}
}
});

You could just forward the request server-side, to avoid needing the client to make a second request:
request.getRequestDispatcher("SearchEmployee.jsp").forward(request, response);
Or alternatively, you could send an HTTP redirect response, so the client should handle the redirection to the second request automatically:
response.sendRedirect(response.encodeRedirectUrl("SearchEmployee.jsp"));
Note that how you handle this in the JavaScript depends on the datatype you expect to receive from SearchEmployee.jsp. For example, if it is XML and you have set the response content-type to text/xml jQuery will parse it and pass you an XML DOM object to your success function:
success:function(msg) {
if (msg instanceof XMLDocument) {
// handle list
} else {
alert(msg);
window.location.reload(true);
}
}
If you're expecting HTML, this may be returned as a string, so you could test to see if your returned string starts with some HTML. For example, if your HTML will always start with a <ul> tag:
success:function(msg) {
if (msg.startsWith("<ul>")) { // note you may need to do msg = $.trim(msg) first
// handle list
} else {
alert(msg);
window.location.reload(true);
}
}
If you don't want to auto-forward as suggested above and you'd rather stick with your current approach, there are a few things you'll need to change.
Using if(msg!="") in your success function is bad as that will return true as long as the server does not return an empty response (so in both cases you'll get an alert).
The first thing to do is to add a content-type header to your servlet code to indicate you're returning JSON in the second case:
response.setContentType("application/json");
response.getWriter().write(jobj.toString());
Now when jQuery handles the response, it will attempt to parse it as JSON before calling the success function. As such, you can now test in your success function whether the argument jQuery has given you is an object or a string:
success:function(msg){
if (typeof msg === "object") {
// you got the JSON response
$.ajax({
url: msg.url,
// etc...
});
} else {
// you got the plain text response
alert(msg);
window.location.reload(true);
}
}

Just make the ajax request in else part as you did above.
$.ajax({url: "jsp url", success: function(result){
}});
Find more information here

Related

How can I save a response of HTTP GET Request in variable?

Here is my API code
#GetMapping("/api/test")
public String test() {
return "hello";
}
Then I will send request to this API by using ajax.
function test() {
$.ajax({
type: "GET",
url: "/api/test",
success: function(response) {
}
})
}
I want to save the value of ajax call response (In this case "hello") in variable. Please let me know how to do it.
Several ways of doing it !
As far as only a String message is concerned you can just store it like below
`var myResponse=response;`
Alternatively, you can also access values if response is an object (JSON reponse I mean)
for e.g. `var resp=response.message; //Assuming message is a key in response JSON`
For testing, use alert(response) or console.log(response) to see how your response is coming and manipulate accordingly !
Feel free to refer this link for detailed Ajax walkthrough https://www.tutorialspoint.com/jquery/jquery-ajax.htm
Hope these helps!

Filter to detect if Response::json was sent

I have a filter. I want this filter to act only if the page is displaying HTML and NOT if it's json or any other format
App::after(function($request, $response)
{
if( $request->getMethod() == 'GET' && $request->getRequestFormat() == 'html' ) {
// do something!
}
});
In my Controller functions I return json data:
return Response::json($data);
However, $request->getRequestFormat() is still equal to 'html' and it shouldn't be.
I know that I can set the format to be 'json' like this:
Request::setRequestFormat('json');
return Response::json($data);
But it seems redundant. If I'm returning a Response::json it should know that it's json and not HTML. How can I detect that it's a Response::json?
The requestFormat is something that isn't set automatically - you either provide it programattically via setRequestFormat or by including a POST/GET parameter _format.
If you want to check if a request is JSON you can do $request->isJson(), but it looks more to me like you're trying to check if the response is JSON? In which case you can do $response instanceof Illuminate\Http\JsonResponse or $response->headers->get('Content-Type') == 'application/json'
This is not a json at all, it's HTML which contains some string inside a div. Remove the div and just pass the json using:
return Response::json($data);
Then in the client side, using jQuery parse the json data and create a div and append the data inside div, for example, in your success callback try something like this:
success(response) {
// Parse the json if not parsed by jQuery
var obj = $.parseJSON(response);
if(obj.success) {
$('<div/>', {id:"query-log"}).append(obj.data).appendTo('body');
}
}
This may not accurate with your json data but hope you got the idea, in short, just pass the json data to the client side and manipulate it in the browser using jQuery.
Update: The better approach would be to provide the dataType when making the request using something like tgis:
$.ajax({
dataType: "json",
url: url,
data: data,
success: function( data ) {
}
});
Also you may use this:
$.getJSON( "url", function( data ) {
// ...
});
So a request header will be sent to the server and you may check if the request is expecting a json response using this:
if($request->wantsJson()) {
//
}
This is the method in the request class:
/**
* Determine if the current request is asking for JSON in return.
*
* #return bool
*/
public function wantsJson()
{
$acceptable = $this->getAcceptableContentTypes();
return isset($acceptable[0]) && $acceptable[0] == 'application/json';
}
App::after(function($request, $response)
{
if( $request->getMethod() == 'GET' && $request->getRequestFormat() == 'html' ) {
// Test if response is JSON (PHP 5.3+ needed for this)
json_decode($response);
if ( json_last_error() != JSON_ERROR_NONE ) {
// Do something
}
}
});

Asynchronously populate Sammy.Storage cache

I'm having difficulty accessing requestJSON on a jQuery $.ajax object outside of the success callback. If I do:
var ajax_request = $.ajax({
dataType: 'json',
contentType: 'application/json'
});
console.log(ajax_request.responseJSON);
// this results in `undefined`
How can I access the responseJSON without adding a .success() callback? If I inspect ajax_request in Firebug, I can see the responseJSON property, and the data I expect, but I can't access it via:
ajax_request.responseJSON
More specifically, I'm building an SPA using Sammy and Knockout. In some routes, I need to be able to get JSON from cache, and if it doesn't exist, get the value from a service call and then set it into cache:
var cached_json = storage.fetch('cached_json', function() {
// make service call
return $.getJSON(url);
});
event_context.render('template.tpl', {'json': cached_json}).appendTo('#my-target');
But, of course, calling storage.fetch doesn't cause the rest of the code to pause until $.getJSON is complete. This is the part I can't quite figure out how to structure.
here's how i would implement it
responseJSON = "";
$.get("myurl.php",function(jdata){
responseJSON = jdata;
},"json");
i like to see the ajax method at a glace, but in your case you can do the same by
....
success : function(jdata){ responseJSON = jdata; }
....
PS: i believe that initializing the blank responseJSON is not required since any variable without var is in global scope, but it would help for clarity
I ended up solving this by creating a deferred object that gets or creates the value I need:
function get_or_create_cache(storage, key, service_endpoint) {
return $.Deferred(function(deferred) {
var c = storage.get(key);
if (c === null || c === undefined) {
$.when(jsonp_service_request(service_endpoint)).done(function(json) {
storage.set(key, json);
deferred.resolve(json);
});
}
else {
deferred.resolve(c);
}
}).promise();
}
In this function, storage refers to a Sammy.Storage instance. jsonp_service_request is a local function that returns a jsonp response, taking into account the location.hostname for local development, where I'm pointing to local.json files, or a remote environment, where I'm calling into an actual API. jsonp_service_request returns an $.ajax function.
Then in my Sammy route, I can do:
this.get('#/', function(event_context) {
$.when(get_or_create_cache(storage, 'my-cache-key', 'service-endpoint'))
.then(function(json) {
event_context.render('my-template.template', {'value-name': json})
.appendTo('#my-target');
});
});

AJAX call in expressJS

I can't seem to get the AJAX call correct. There have been other QA that deal with the $.ajax() function but I'm trying to solve this with $.post().
When the form button is clicked the javascript at the head is executed, which includes a $.post(). The url /login is routed through and passed to loginPost function. There a response is determined and sent back to the javascript (right?). Instead, webpage renders the response (pass || fail).
Why isn't the response from the AJAX call being sent back to get processed?
This is a simple example that I am working with to get me better acquainted to how AJAX in expressJS and jQuery work. Any Help is greatly appreciated!
--views/login.jade
script(src='/_js/jquery-1.8.2.min.js')
script
$(document).ready(function(req, res) {
$('#login').submit(function() {
var formData = $(this).serialize();
console.log(formData);
$.post('/login', formdata, processData).error('ouch');
function processData(data, status) {
console.log(status);
console.log(data);
if (data == 'pass') {
$('#content').html('<p>You have successfully loggin in!</p>');
} else {
if (! $('#fail').length) {
$('#formFrame').prepend('<p id="fail">Incorrect login information. Please try again)</p>');
}
}
} //end processData
}); //end submit
}); //end ready
div.main
h1= title
div#formFrame
form(id='login', action='/login', method='POST')
p
label(for='username') Username:
input(id='username', type='text', name='username')
p
label(for='password') Password:
input(id='password', type='password', name='password')
p
input(id='button', type='submit', name='button', value='Submit')
--routes/index.js
app.post('/login', loginPost);
--routes/loginPost
module.exports.loginPost = function(req, res) {
var password = 'admin'
, username = 'user'
, data = req.body;
if (data.username == username && data.password == password) {
res.send('pass');
} else {
res.send('fail');
}
};
You still have to stop the <form> from submitting via its default action, which can be done with event.preventDefault():
$('#login').submit(function(evt) {
evt.preventDefault();
// ...
});
Otherwise, the <form> will redirect the page to its action (or back to the current address if no action was given), interrupting the $.post request.

response.responseText adds previous responseText (node.js, prototype)

This is my node.js function that uses res.write:
function: ping(){
res.write(JSON.stringify({"datatype":"ping"}));
setTimeout(ping, 30000);
}
This is the client, request written in prototype:
this.pushconnection = new Ajax.Request(pushserveraddress, {
method: 'get',
evalJSON: 'false',
onInteractive: this.pushconnectionInteractive.bind(this)
});
}
pushconnectionInteractive: function(response) {
}
The problem is that response.responseText will grow with every res.write that comes through.
Example:
1st ping() received: response.responseText = {"datatype":"ping"}
2nd ping() received: response.responseText = {"datatype":"ping"}{"datatype":"ping"}
3rd ping() received: response.responseText = {"datatype":"ping"}{"datatype":"ping"}{"datatype":"ping"}
I'm not sure if node.js is re-sending the data, or if prototype is storing the data. What I need to do is have response.responseText = the last data sent without using res.end();
You're probably calling this.pushconnection more than once.
If you instantiate this.pushconnection as it's own Ajax Object and continue to use the same ajax object then your response will grow.
Try this instead:
this.pushconnection = function (pushserveraddress) {
return new Ajax.Request(pushserveraddress, {
method: 'get',
evalJSON: 'false',
onInteractive: this.pushconnectionInteractive.bind(this)
});
}
Then you can call this by saying:
var ajax = this.pushconnection("example.com");
every response add to previous one, to get last object sent if u use that php function :
(1st add headers)
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('connection: keep-alive');
(2 send data)
function send_message($data_array) {
echo json_encode($data_array).PHP_EOL;
ob_flush();
flush();
}
in your js (Prototype): to get last response
new Ajax.Request(sUrl, {
onInteractive:function(xhr){
var lastString = xhr.responseText.split("\n");
var lastObjectSent = lastString[lastString.length-2].evalJSON();
if(lastObjectSent.bValid){
if(parseInt(lastObjectSent.bValid,10) === 1){
this.status="finished";
loadPage('done.php');
}else{
setNotification(oResult.sText,"Failure",5000);
}
}else if(lastObjectSent.progress){
$('duplicatePassDates').down('.bar').setStyle('width:'+lastObjectSent.progress+'px');
}
},
onSuccess:function(xhr){
if(this.status!=="finished"){
this.onInteractive(xhr);
}
},

Resources