I am using jsp and jquery...and struts.I have a problem understanding the redirect to login page for ajax request.I tried to see request on browser on XHR tab and it gives me 302 status code in header.I am not able to comprehend how do i redirect.
My approach
1)The application has a function which checks if the user is signed in or not and has function to redirect to login url.
2)Else do some other processing.
How do I come back to same page after login.Is there any way?.....Also for redirecting on server side i am using Response.redirect()...Can someone explain how to catch response from server?...
function buttonpress(param1,param2)
{
$.ajax({
type:"GET",
data:{
X:param1,
Y:param2,
},
url:"/application",
success:function()
{
alert("success message");
}
error:function()
{
alert("error message")
}
});
}
Use the data parameter passed to the ajax success() callback. If a 302 was issued, the target URL would be available at data.redirect.
function buttonpress(param1,param2)
{
$.ajax({
type: "GET",
data: {
X:param1,
Y:param2,
},
url: "/application",
success: function(data, status)
{
if (data.redirect) {
window.location.href = data.redirect;
} else {
alert("success message");
}
},
error:function()
{
alert("error message")
}
});
}
you can try this
function buttonpress(param1,param2)
{
$.ajax({
type: "GET",
data: {
X:param1,
Y:param2,
},
url: "/application",
success: function(data)
{
var flag = data.trim();
if (flag) {
// success code
} else {
window.location.href = '/logout.do';
}
}
});
}
Related
In the following postman pre request script, I need to call multiple requests before I make an actual postman request.
Firstly, it will call session API to retrieve the session id
After session id is success only, then I need to call customer signon to make the user logged in.
So I did the following changes in my postman prerequest script but some how the LocalSessionId in the customer signon request is undefined.
const sessionRequestData = {
url: "http://myurl.com/session",
method: 'POST',
header: { 'content-type': 'application/json' },
body: {
mode: 'raw',
raw: JSON.stringify({
"device": {
"id": "web",
"type": "WEB"
}
}
};
pm.sendRequest(sessionRequestData, function (err, res) {
var jsonData = res.json();
if (err) {
console.log("mailman: error retrieving session id"+err);
}
else {
console.log("mailman: retrieved session data succesfully"+ jsonData.session.id);
pm.variables.set("LocalSessionId", jsonData.security.session.id);
}
});
const customerSignonRequestData = {
url: "http://myurl.com/CustomerSignOn",
method: 'POST',
header: { 'content-type': 'application/json' },
body: {
mode: 'raw',
raw: JSON.stringify( "customerRequest": {
"identities": {
"identity": [
{
"data": "sessionId",
"value": `${pm.variables.get("LocalSessionId")}`
}
]
}
});
pm.sendRequest(customerSignonRequestData, function(err, res){
console.log("customer sign on request "+ JSON.stringify(customerSignonRequestData.body.raw))
var jsonData = res.json();
if (err) {
console.log("mailman: unable to signon"+err);
} else {
console.log("mailman: login successful"+ JSON.stringify(jsonData))
}
});
Can anyone suggest how can I make sure that the customer signon is called after the session is retrieved only.
I am trying to call a controller from jquery.Here every thing works fine,but in ajax it shows error alert. What is going wrong.
$.ajax({
type: 'POST',
url:'<%=request.getContextPath()%>/billing',
data: ({caseId: caseId, noteID : noteID}),
cache: false,
success: function(data){
alert("Success");
},
error: function(xhr, textStatus, error){
alert("Error occured.");
}
});
My controller
#RequestMapping(value = "/billing", method = RequestMethod.POST)
public String Billing(#RequestParam Long caseId,
#RequestParam Long noteID, HttpServletRequest request) throws Exception {
try{
----Some data base updation---
logger.debug("success ");
return "success";
} catch (Exception e) {
logger.error(e,e);
throw e;
}}
Please help me in this.
//you have to left content type to send the server side ,please define content type..
$.ajax({
type: "POST",
url: '#Url.Action("PerTGradeMastEdit", "Master")',
data: "{'Request':'" + request + "'}",
contentType: "application/json; charset=utf-8",
success: function (response) {
if (response != null) {
var strResponse = response;
var ProgramData = strResponse.split("/");
// response = ProgramData[0];programId
$('#txtPerGrade').val(ProgramData[0]);
$('#txtDesc').val(ProgramData[1]);
}
},
failure: function (msg) {
alert(msg);
window.location.href = '#Url.Action("INDEX", "AUTHORIZE")';
}
});`enter code here`
I have the restful webservices call from the Jquery ajax and getting the response in json object.
Jquery HTML:
$.ajax({
url: "mcrs/object/api/Lighting",
type: "POST",
traditional: true,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
async: "false",
data:JSON.stringify(postdata),
success: function (ResData) {
},
error: function (error, data) {
console.log(error);
}
});
}
});
And writing the response object for the restful webservices in java
#POST
#Path("api/{subsystem}")
#Produces("application/json")
public Response changeStatus(#PathParam("subsystem") String subsystem,
/*#FormParam("result")*/ String result) {
}
I got the response below and which is correct
changeStatus:88 - Reponse OutboundJaxrsResponse{status=200, reason=OK, hasEntity=true, closed=false, buffered=false}
Depending upon the reponse need to update the status whether the value is on/off in the label tag.
str = ' Status : ' + '' + onoffStat + '';
How can I achieve this in ajax and want to have the refreshing the div tag for every 2 seconds.
Please help me.
You will have to use Javascript polling. Try out something like this:
function ajaxPoll(){
$.ajax({
url: "mcrs/object/api/Lighting",
type: "POST",
traditional: true,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
async: "false",
data:JSON.stringify(postdata),
success: function (ResData) {
tag.str = 'Status : ' + '' + ResData.status + '';
},
error: function (error, data) {
console.log(error);
}
});
}
});
}
setInterval(ajaxPoll, 2000);
Hope you sort it out :)
I am trying to connect a Java REST service to a ExtJs JSONP request but even though the java method executes I haven't been able to get a response test. This is what I am trying:
Java Code:
#Path("/hello")
public class Hello {
#GET
#Produces("text/javascript") // have also tried application/json
public String sayJsonHello(#QueryParam("_dc") String dcIdentifier, #QueryParam("callback") String callback) {
System.out.println(callback);
callback += "({\"success\":true, \"msj\":" + "\"" + "Exitoooo!" + "\" });";
System.out.println(callback);
return callback;
}
}
ExtJs code:
Ext.data.JsonP.request({
url: "http://10.1.50.66:7001/Simulador/webresources/hello",
params: {
},
callback: function (response) {
console.log(response); //true
console.log(response.result); //undefined
console.log(response.responseText); //undefined
console.log(response.success); // undefined
if (response.success === true) {
Ext.Msg.alert('Link Shortened', response.msj, Ext.emptyFn);
} else { // entering here :( why ?
Ext.Msg.alert('Error', response.msj, Ext.emptyFn);
}
}
});
response is printting true, everything else undefined :(
callback looks like this Ext.data.JsonP.callback1({"success":true, "msj":"exito"})
Any ideas what could be wrong?
Ok this worked out for me:
Ext.data.JsonP.request({
url: "http://10.1.50.66:7001/Simulador/webresources/hello",
callbackKey: 'callback1',
params: {
},
success : function(response) {
console.log("Spiffing, everything worked");
// success property
console.log(response.success);
// result property
console.log(response.result);
console.log(response.msj);
},
failure: function(response) {
console.log(response);
Ext.Msg.alert('Error', 'Please try again.', Ext.emptyFn);
}
});
I am using jsp, jquery, and struts. I have a problem understanding the redirect to login page for ajax request. I tried to see request on browser on XHR tab and it gives me 302 status code in header. I am not able to comprehend how do I redirect.
My approach
The application has a function which checks if the user is signed in or not and has function to redirect to login url.
Else do some other processing.
How do I come back to same page after login? Is there any way? Also for redirecting on server side I am using Response.redirect(). When I debug the code and response comes on client side the error function in ajax function is executed not success function. Can someone explain how to catch response from server?
function buttonpress(param1,param2){
$.ajax({
type:"GET",
data:{
X:param1,
Y:param2,
},
url:"/application",
success:function(){
alert("success message");
}
error:function(){
alert("error message")
}
});
}
success:function(){
//current page URL
var ref = document.URL;
location.href = '/login/?ref=' + ref;
}
You can use variable "ref" to come back the same page
Note that when you use ajax to call server and receive a redirect response. The browser will not redirect, but will automatically retrieve the content at redirected location and your success function will end up being passed the content from the redirected location. For ajax request, you should not respond with a redirect if the user is not signed in, you should return a 401 Unauthorized instead and the browser will handle this in your callback. Here are the steps:
Check if the user is signed in or not
If the user is not signed in, check the headers for X-Requested-With: XMLHttpRequest (this indicates an ajax request)
If found and not authenticated, respond with 401 (for ajax requests) else respond with 302 (for not ajax requests).
And your ajax callback could check if there is a 401 response, set location.href to your login page. You could have something like returnUrl query string parameter in your login page, if there is you could set it to your current page to redirect to this page after login. Sample code on client side:
$.ajax({
type:"GET",
data:{
X:param1,
Y:param2,
},
url:"/application",
success:function()
{
alert("success message");
},
error:function()
{
alert("error message")
},
statusCode: {
401: function() {
location.href = '/login/?returnUrl=' + document.URL;
}
});
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('#MsgDel').show(false);
jQuery("#MsgDel").dialog({
bgiframe: true, autoOpen: false, height: 150, modal: true, width: 300,
buttons: {
"OK": function () {
$(this).dialog("close");
--To Reload Page Again After Success Function
window.location.href = "DispatchInstructionList.aspx";
}
},
close: function () {
}
});
});
</script>
jQuery(document).ready(function () {
jQuery('#dialog').show(false);
jQuery('#MsgDel').show(false);
jQuery("#dialog").dialog({
bgiframe: true, autoOpen: false, height: 250, modal: true, width: 250,
buttons: {
"Delete": function () {
var txtValue = $("#<%=txtid.ClientID %>").val();
var txtrea = $("#<%=txtreason.ClientID %>").val();
if (txtrea == '') {
}
else {
Delete(txtValue, txtrea);
$(this).dialog("close");
}
},
"Cancel": function () {
$(this).dialog("close");
}
},
close: function () {
$('#txtreason').val("");
}
});
});
</script>