Getting response from Servlet on Ajax call - javascript

I am doing a servlet call from my ajax . How i can get the response in my ajax function as a variable .
function myajaxcall(name) {
var url = "/myServlet?name="+name
$.ajax({
type: 'GET',
url: url,
success: function() {
console.log("Success");
// also i want to get response from header which i have set in my servlet class . and call a another javascript method
// call a another javascript method by passing the response from servlet .
}
});
}
The Servlet code is :
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String code=request.getParameter("name")+"Hi";
response.addHeader("code", code);
}
Now i want to use my "code" variable in ajax call so that i can send that to another javascript method ..
Thanks in advance .

As outlined in the jQuery documentation, the success setting for jQuery's $.ajax() function is a function, or array of functions, which has up to three parameters (and is subsequently passed three arguments when called after the AJAX request returns a successful response):
success
Type: Function( Anything data, String textStatus, jqXHR jqXHR )
As you can see, the third parameter is of type jqXHR, which has a getResponseHeader() function.
Something like this should work (though untested):
$.ajax({
type: 'GET',
url: url,
success: function(data, status, xhr) {
var code = xhr.getResponseHeader('code');
yourFunction(code);
console.log("Success");
}
});

Related

Using OnPost Page Handlers for AJAX Requests in Razor Pages

I have a JavaScript/jQuery function used to execute AJAX requests as part of a ASP.NET Core Razor Pages (Visual C#) project. The AJAX request calls an "OnGet" handler method in the PageModel (.cshtml.cs) of whichever page it gets called on.
AJAX request JS/jQuery:
function conditionalDropDown(parameters) {
//code to get handler method inputs in correct format
var pathname = window.location.pathname;
var handler = "?handler=ConditionalDropDown";
var actionpath = pathname + handler;
$.ajax({
dataType: 'json',
url: actionpath,
type: 'GET',
data: {
parameterName: parameterValue
},
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (data) {
//dealing with the data returned by the request
},
error: function () {
alert("AJAX Request Failed, Contact Support");
}
});
}
Handler Method in PageModel:
public JsonResult OnGetConditionalDropDown(parameters)
{
//call a function to get the return string
return new JsonResult(dropdownHTML);
}
I want to change my AJAX request such that it uses an "OnPost" handler method instead. I have tried changing type: 'GET' to type: 'POST' in the AJAX request function, and the name of the handler method from OnGetConditionalDropDown to OnPostConditionalDropDown but the request always fails.
I have #Html.AntiForgeryToken() added to the page (.cshtml) from which the AJAX request is sent, but I'm not sure it's in the right place. Currently, I have it inside the <form> tags of the form from which the AJAX requests are called.
I think I'm missing something in the way the request is set up, but I have no idea what it is. Any help is greatly appreciated.
Answering my own question...
AJAX Request - removed beforeSend function in request, replaced with: headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() }, in request initialisation.
AJAX Request - changed type: 'GET' to type: 'POST'
Handler Method - OnGet --> OnPost
Page .cshtml - removed #Html.AntiForgeryToken(), added method="post" to form from which AJAX request is made
Works perfectly now!

strange behavior of request methods while ajax request

I have such method in my controller
#Controller
#RequestMapping ("/admin/users")
public class AdminUserController {
..
#RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public #ResponseBody boolean deleteUser(#PathVariable("id") int id,
HttpServletResponse response) {
..
}
..
}
and this is ajax request
$.ajax({
url: '/admin/users/'+id,
type: 'delete',
success: function(data){
console.log(data);
},
error: function(e){
console.log(e);
}
});
When I send this request, it's fails and I get 405. When I looked at response header I saw this Allow:"GET".
Ok. I change in ajax request 'delete' to 'get' but then I get in response Allow:"DELETE" ..
What it can be?
I think that DELETE actions are not allowed by your server security configurations, and basically the header:
ALLOW: GET
is suggesting you to try a GET request instead, but since you specified
method = RequestMethod.DELETE
Spring in rejecting that GET invocation to the method.
you should change method = RequestMethod.DELETE to method = RequestMethod.GET
and issue an HTTP GET request.
Let me know if this helps.

Ajax .done() no data

I am using the following jquery to make an ajax call:
$.ajax({
url: "/projects/project/xGetProjectStatus",
type: "GET",
dataType: "json"})
.done( function(request){
alert(request.responseText);
var data = JSON.parse(request.responseText);
if(data.success){
//stuff here
}
})
The alert pop up always says that responseText is undefined. The page I am "get"ting is well formatted JSON and if I run these commands in the console one at a time everything works fine. What is wrong?
You're looking for responseText in the response, it won't be there. You'll find it instead on the jqXHR object itself (which is the third parameter passed to your done() function, and also returned by your whole $.ajax() call).
And because you have dataType: "json" the response is already a JSON parsed object.
Change this:
.done( function(request){
alert(request.responseText);
var data = JSON.parse(request.responseText);
if(data.success){
//stuff here
}
})
To just this:
.done( function(data){
if(data.success){
//stuff here
}
})
When you set the dataType in a jQuery.ajax call it will be returned as a parsed object. So your request object in .done is actually your parsed json string
If you don't want jQuery to automatically parse your JSON you can remove the datatype from the call.
$.ajax({
url: "/projects/project/xGetProjectStatus",
type: "GET"
}).done( function(request){
alert(request.responseText);
var data = JSON.parse(request.responseText);
if(data.success){
//stuff here
}
})
This is because the first parameter of the done function is not the XHR object but the contents of the responseText as an object already. jQuery handles all that for you and so there's no need to do any manual conversion.
the done function is called whenever the ajax call is successful anyways so no need to re-check it and the fail function is called when a response other than 200 is returned.

How to call code-behind method from 'success' in ajax callback?

How to modify below code to use 'success' to call testMethod() in code-behind ?
I need to wait for return value from testMesthod() and process it.
$.ajax( {
url : 'myPage.aspx/testMethod',
type : "POST",
contentType : "application/json; charset=utf-8",
data : "{'name':'" + aNb + "'}",
dataType : "json"
}).done(function() {
alert("ok");
}).fail(function() {
alert("not ok");
});
Above code does not work because somehow latest JQuery version (1.10.1) gets overwritten by 1.3.2.
Thank you
You would need to pass the callback function to the function that wraps your $(ajax).
function getData(ajaxQuery, callBack){
var ajaxHREF = 'your url';
$.ajax({
url: ajaxHREF,
type: "post",
data: ajaxQuery,
beforeSend: function ( xhr ) {
xhr.overrideMimeType("application/json");
},
success: function(response, textStatus, jqXHR){
var jsonData = $.parseJSON(response);
callBack (jsonData);
},
However, a much better way of doing this is the global success event. It is better because you have all of the properties of the call available to you to enable dynamic processing of the results. Create the global success event inline = $(document).ajaxSuccess this gets called for all jquery ajax success events so you need to differentiate which calls apply to your specific handler (to each global handler).
$(document).ajaxSuccess(function(event, xhr, settings) {
var query = settings.data;
var mimeType = settings.mimeType;
if (query.match(/ameaningfulvalueforthishandler/)){
if(mimeType.match(/application\/json/)){
var jsonData = $.parseJSON(xhr.responseText);
}
}
}
Thank for replies, but I still do not see how callbacl can help me.
I need to call webmethod in code-behind: testMethod()
Ajax call does it, url = "myPage.aspx/testMethod" will 'call' webmethod testMethod(),
but it's asynchronous and returns quickly into 'success' section of ajax call.
But, I need to Wait for testMethod() to finish processing, retrieve result returned by testMethod() and process it.
Asynchronous ajax will return us into 'success' without waiting for testMethod() to finish,
and we will not get any data in response.
So, how callback helps me to achieve it?
function getData(ajaxQuery, callBack){
var ajaxHREF = "myPage.aspx/testMethod";
$.ajax({
url: ajaxHREF,
type: "post",
data: ajaxQuery,
beforeSend: function ( xhr ) {
xhr.overrideMimeType("application/json");
},
success: function(response, textStatus, jqXHR){
var jsonData = $.parseJSON(response);
callBack (jsonData);
});
Thank you
#Karen Slon - If I understand the question correctly, I think you need to conceptually separate the client side from the server side. The callback in .success/.done or global ajaxSuccess event enable your web page to initiate the request and keep on processing while the server side is processing your request 'myPage.aspx/testMethod'. When it completes successfully it returns to the success event. Now if testMethod does not return anything then you will find yourself in the success event event without a result. But you cannot get there unless web method testMethod has completed successfully and returned control. The .done event in your example only has alert("ok");. What makes you believe that the web method testMethod is not complete when the .done event occurs?
Look at these posts for better examples:
jQuery.ajax handling continue responses: "success:" vs ".done"?
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
http://api.jquery.com/category/deferred-object/

JSON object returned but not accessible via $.ajax()

I have an ASP.NET MVC Web API that I am calling from an $.ajax() method. The correct JSON is returned from my API, but the object is not accessible. The error received in my console when trying to log the value for "Name" is:
Uncaught TypeError: Cannot read property 'Name' of undefined
JSON:
[{"id":2,"Name":"thom","Picture":"thom.jpg","About":"I'm a guy. This is my profile. Now quit staring and get out of here.","Location":"London"}]
jQuery:
$.ajax({
cache:false,
type: 'GET',
dataType: 'json',
url: 'http://localhost:3235/Users/searchUsers?callback=?&searchString=' + searchString,
complete: function (data) {
console.log(data[0].Name);
}
});
Any help would be appreciated. Thanks!
I think you mean to use the success function. The complete function doesn't take data as a parameter.
From the docs:
completeType: Function( jqXHR jqXHR, String textStatus )A function
to be called when the request finishes (after success and error
callbacks are executed). The function gets passed two arguments: The
jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string
categorizing the status of the request ("success", "notmodified",
"error", "timeout", "abort", or "parsererror").
The method's first parameter is not the received data. You can get it though the jqXHR object but I don't think you really need to use this option. Use success instead:
success Type: Function( PlainObject data, String textStatus, jqXHR jqXHR ) A function to be called if the request
succeeds. The function gets passed three arguments: The data returned
from the server, formatted according to the dataType parameter; a
string describing the status; and the jqXHR (in jQuery 1.4.x,
XMLHttpRequest) object.
ya complete fires after the service call is being made and it does not contain data from the service response..
use
$.ajax({
url:'ur url',
type:'GET'
success:function(data){
// way to acces ur object code goes here
console.log(data[0].Name);
},
error:function(){
// Error handling
}
});
happy coding

Categories

Resources