Change ajax data on retry - javascript

Is there a way to change the supplied data on an ajax retry? I want to make the first call with user="auth" passed in the data params , if it fails then change the user to "ANON" and retry the call this new data param. The user shows up as undefined with the way I have it set up below.
$.ajax({
url : proxyurl,
type : 'GET',
dataType : 'xml',
user : "auth",
tryCount : 0,
retryMax : 2,
data : {'apireq': apiurl+"?user="+this.user},
success : function(data){
},
error: function(xhr,textStatus,errorThrown){
if (textStatus == 'parsererror') {
this.user = "ANON";
this.tryCount++;
if (this.tryCount <= this.retryMax) {
$.ajax(this) //try the call again
return;
}
return;
}
}
});

We were able to reach the following solution:
error: function(xhr,textStatus,errorThrown){
if (textStatus == 'parsererror') {
this.user = "ANON";
this.data = {'apireq': apiurl + "?user=" + this.user };
this.tryCount++;
if(this.tryCount <= this.retryMax) {
$.ajax(this); //try the call again
return;
}
return;
}
}

Related

AJAX Callback Not Showing Success Message - ASP.NET MVC C#

I have some AJAX code in my JavaScript which is not showing any success or failure alert.
function AttemptHouseViewingAppointment(house) {
var imgOfHouse = $(house).attr("value");
$.ajax({
type: "POST",
url: '#Url.Action("AttemptHouseViewingAppointment", "Viewing")',
dataType: "json",
data: ({
userId: #Model.UserId,
appointmentKey: '#Model.Key',
chosenHouse: imgOfHouse
}),
success: function (data) {
alert(data);
if (data.success) {
alert(data.message);
} else { alert(data.Message) }
},
error: function (xhr) {
alert(xhr.responseText);
}
});
};
The above function is called when I click an image on the screen. This part works fine as I have set a breakpoint on my ASP controller and I can see the relevant action being called. C# code below:
public ActionResult AttemptHouseViewingAppointment(int userId, string appointmentKey, int chosenHouse)
{
string selecteHouseName = $"./house-code-icons/{chosenHouse}.png";
var house =
_ctx.houses.Where(x => x.HouseID == userId && x.Icon == chosenHouse)
.FirstOrDefault() ?? null;
if(house != null)
{
var member = _ctx.User.FirstOrDefault(x => x.Id.Equals(userId));
_ctx.Appointments.Add(new ViewingModel
{
House = chosenHouse,
UserId = userId
});
_ctx.SaveChanges();
return Json(new { success = true, message = "Appointment Confirmed!" });
}
else
{
return Json(new { success = false, message = "Sorry, a booking has already been made!" });
}
}
Even though, the return Json lines are being hit and returned to the page, there is no alert popup on my page to let user know if success or not. Please let me know if any questions.
Thanks
Add the done function to the end of Ajax
$.ajax({
.
.
.
}).done(function( response ) {
alert(response);
...
});

ajax can't going into success method

here is controller:
#ResponseBody
#PostMapping("/signup")
public String signUp(HttpServletRequest request) {
try {
log.info("-------signup page");
String username = request.getParameter(Constant.PARAMETER_USERNAME);
if (userDetailService.findByUsername(username)!=null) {
log.error("----------username is exist!!");
return Constant.MESS_EXIST_USER;
}
log.info("----------username is not exist!!");
User user = new User();
user.setUsername(username);
user.setPassword(passwordEncoder.encode(request.getParameter(Constant.PARAMETER_PASSWORD)));
user.setEmail(request.getParameter(Constant.PARAMETER_EMAIL));
user.setPhonenumber(request.getParameter(Constant.PARAMETER_PHONE)) ;
user.setAddress(request.getParameter(Constant.PARAMETER_ADDRESS));
user.setFullname(request.getParameter(Constant.PARAMETER_FULLNAME));
String status = userService.save(user);
log.info(status );
return status;// return "success" or "fail"
}
}catch (Exception e) {
log.error("sign up has been error: ",e);
return Constant.MESS_FAIL; // "fail"
}
}
and js:
var data = $('form#form1').serialize();
$.ajax({
url: '/signup',
data: data,
type: "POST",
datatype : "text",
success: function(data){
console.log(data);
if(data == "success"){
alert("signup success!");
window.location.href = "/index";
}else if(data=="existUser"){
alert("username is exist!");
window.location.href = "/index";
}
else if(data=="fail"){
alert("signup fail!");
window.location.href = "/index";
}
}
});
}
log of save(user) is success but ajax not alert("signup success!"), it show error page. When I debug in js and java, ajax worked and show alert("signup success!"). I try search in google but it can't run. Anyone help me :(
EDIT
I try use datatype = 'text' and not dublicate save(user). When I run it then seem it not going into success function but when i debug in js then my program is running normally :(

How can I display alert only once in javascript?

My case like this :
if(window.location.pathname == '/shop/payment/checkout' || window.location.pathname == '/shop/detail' || window.location.pathname == '/shop') {
alert('Your data has been removed')
localStorage.removeItem("cartCache")
var _token = $('input[name="_token"]').val();
$.ajax({
type: 'POST',
url: baseUrl+'/shop/delete-cache',
data: {_token: _token},
success: function(response){
if(response.success==1)
window.location = "/shop";
},
error: function(request, status, error) {
console.log('error')
}
});
}
If the url accessed meets the condition of if then it will delete session by ajax and redirect to the url /shop
My problem is if redirect to url /shop, it will check again and display alert message again. So on and on
I want if the alert message appears and reload to the url /shop, it does not check anymore and displays the alert message
How can I do it?
EDIT:
After the answer given, I wrapped my code like this:
if (localStorage.getItem("cartCache") !== null) {
...
}
else {
alert('Your data has been removed')
localStorage.removeItem("cartCache")
var _token = $('input[name="_token"]').val();
$.ajax({
type: 'POST',
url: baseUrl+'/shop/delete-cache',
data: {_token: _token},
success: function(response){
if(response.success==1)
window.location = "/shop";
},
error: function(request, status, error) {
console.log('error')
}
});
}
}
It does not work as intended.
Before removing, you could first check if the local storage data is still there. Put this before the alert:
if (localStorage.getItem("cartCache") === null) return;
... assuming this code is within a function. But you get the idea. Or you can combine it with the if you already have (a bit improved):
if(['/shop/payment/checkout', '/shop/detail', '/shop'].includes(window.location.pathname)
&& localStorage.getItem("cartCache") !== null) {
// ...etc.

Ajax success function not working in jquery mobile

I am trying to validate a basic login form with username and password fields. I need to validate username and password from check.php ajax page. There is no problem in ajax request and response. I am getting proper response from ajax page. But Ajax success function is not working properly.
ajaxrequest.html
$(document).on('pagebeforeshow', '#login', function(){
$(document).on('click', '#submit', function() {
if($('#username').val().length > 0 && $('#password').val().length > 0){
$.ajax({
url : 'serverurl/check.php',
data: {action : 'login', formData : $('#check-user').serialize()},
type: 'post',
beforeSend: function() {
$.mobile.loading(true);
alert("beforesend");
},
complete: function() {
$.mobile.loading(false);
alert("complete");
},
success: function (result) {
console.log("Ajax response");
res = JSON.stringify(result);
if(res.status == "success"){
resultObject.formSubmitionResult = res.uname;
localStorage["login_details"] = window.JSON.stringify(result);
$.mobile.changePage("#second");
}else{
$.mobile.changePage("#login");
alert("incorrect login");
}
},
error: function (request,error) {
alert('Network error has occurred please try again!');
}
});
} else {
alert('Fill all fields');
}
return false;
});
});
Here i have added my ajax page. This page only validates posted username and password. Finally it returns json object. What am i doing wrong?
serverurl/check.php
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
if(isset($_POST['formData']) && isset($_POST['action']) && $_POST['action'] == 'login'){
parse_str($_POST['formData'],$searchArray);
$uname = "arun";
$pwd = "welcome";
$resultArray = array();
if($uname == $searchArray['username'] && $pwd == $searchArray['password'])
{
$resultArray['uname'] = $searchArray['username'];
$resultArray['pwd'] = $searchArray['password'];
$resultArray['status'] = 'success';
}else{
$resultArray['status'] = 'failed';
}
echo json_encode($resultArray);
}
Your code should be
success: function (result) {
console.log("Ajax response");
//don't do this
//res = JSON.stringify(result);
if(result.status == "success"){
resultObject.formSubmitionResult = result.uname;
localStorage["login_details"] = window.JSON.stringify(result);
$.mobile.changePage("#second");
}else{
$.mobile.changePage("#login");
alert("incorrect login");
}
After JSON.stringify you are accessing like stringJson.status this will not work. it mast have "parsed" "json object" not stringify.
Don't need to convert your JSON to String.
$(document).on('pagebeforeshow', '#login', function(){
$(document).on('click', '#submit', function() {
if($('#username').val().length > 0 && $('#password').val().length > 0){
$.ajax({
url : 'serverurl/check.php',
data: {action : 'login', formData : $('#check-user').serialize()},
type: 'post',
beforeSend: function() {
$.mobile.loading(true);
alert("beforesend");
},
complete: function() {
$.mobile.loading(false);
alert("complete");
},
success: function (result) {
console.log("Ajax response");
//Don't need to converting JSON to String
//res = JSON.stringify(result);
//directly use result
if(result.status == "success"){
resultObject.formSubmitionResult = result.uname;
localStorage["login_details"] = window.JSON.stringify(result);
$.mobile.changePage("#second");
}else{
$.mobile.changePage("#login");
alert("incorrect login");
}
},
error: function (request,error) {
alert('Network error has occurred please try again!');
}
});
} else {
alert('Fill all fields');
}
return false;
});
});
Your AJAX call is perfect but datatype is not declared in ajax
Try with jSON OR JSONP. You will get success.
$.ajax({
url : 'serverurl/check.php',
type: 'post',
dataType: "json", OR "jsonp",
async: false,
data: {action : 'login', formData : $('#check-user').serialize()},
beforeSend: function() {
$.mobile.loading(true);
alert("beforesend");
},
complete: function() {
$.mobile.loading(false);
alert("complete");
},
success: function (result) {
console.log("Ajax response");
alert(JSON.stringify(result)); // Check response in alert then parse according to that
res = JSON.stringify(result);
if(res.status == "success"){
resultObject.formSubmitionResult = res.uname;
localStorage["login_details"] = window.JSON.stringify(result);
$.mobile.changePage("#second");
}else{
$.mobile.changePage("#login");
alert("incorrect login");
}
},
error: function (request,error) {
alert('Network error has occurred please try again!');
}
});
Under some circumstances your server might not return the response correctly. Have you tried to handle the actual response code (e.g. if your server returns 200) like this:
$.ajax({
url : 'serverurl/check.php',
data: {action : 'login', formData : $('#check-user').serialize()},
type: 'post',
....
statusCode: {
200: function (response) {
// do your stuff here
}
}
});

Want to pass in returned data to my custom callback within jQuery's $.post()

Basically I'm creating my own callback and passing it into my method called _ajaxCall().
_ajaxCall() takes the following parameters:
data = an object containing the user submitted data to be POSTed to my server
postURL = the url to post to
callback = a function expression to be called upon successful return of data from the server.
Here is the _ajaxCall() method:
_ajaxCall: function (data, postURL, callback) {
$.post(postURL, {
data : data
}, 'json').done(function (returned) {
switch(returned.success) {
case true:
typeof callback === 'function' && callback(returned);
break;
}
}).fail(function (xhr, textStatus, errorThrown) {
if (status !== 200) {
window.location = document.URL;
}
});
}
commentUpdate : function(self) {
var postURL = '/submission/comment/' + self.attributes.commentId;
var data = {
action: self.attributes.action,
commentId : self.attributes.commentId,
comment: self.attributes.comment
};
var callback = function(returned) {
if (returned.success === true) {
// do something in here
} else {
// do other crap here
}
};
this._ajaxCall(data, postURL, callback);
}
But it's not passing returned to my custom callback() method. Why?

Categories

Resources