$.when().done not working on blur event - javascript

I am trying to run a validation check and need to call the database and get result before I proceed, I am using ajax promise handler to wait for the response but for some reason it execution flow does not stop.
$("#attr").blur(function() {
var attrValue = $("#attr").val();
if (attr.length > 256) {
$("#Validation").text(" has a max of 256 characters");
$("#Validation").show();
$("#attr").focus();
} else {
if (attrValue.length > 0) {
$.when(check_attribute_name(attrValue)).done(function (data) {
if (data.result == false) {
$("#Validation").text("Another exists with this name. Try again!");
$("#Validation").show();
$("#attr").focus();
$("#unique").val("fasle");
} else {
$("#attrValidation").hide();
}
});
}
}
});
function check_attribute_name(attrValue) {
return $.ajax({
type: "Post",
url: "#Url.Action("Validation", "validator")",
data: { name: attrValue },
});
}

Related

function not run again if status === false

iam trying to run my function again if the status of my json false but its not working
$(document).ready(function(){
function checkIfCompleted(){
$('.btn').click( function(e) {
e.preventDefault();
var url = "https://localhost/check/1";
$.ajax({
url: url,
success: function(response) {
if(response.status === false){
checkIfCompleted();
}else{
alert(done);
}
},
});
});
}
checkIfCompleted();
});
You are adding click multiple times to the button, you are not rerunning the Ajax call
$(document).ready(function() {
function checkIfCompleted(cnt) {
var url = "https://localhost/check/1";
$.ajax({
url: url,
success: function(response) {
if (response.status === false) {
if (cnt >= 5) {
throw new Error('too many retries');
} else {
checkIfCompleted(++cnt);
}
} else {
alert(done);
}
},
});
}
$('.btn').click(function(e) {
e.preventDefault();
checkIfCompleted(0);
});
});

jquery stop form submisson on false condition

I am validating a duplicate value through ajax. if a duplicate is found then it alerts with an error but does not stop on submission.
$(function() {
$("#admno").on("keyup", function(e) {
e.preventDefault();
var oadmno = $("#oadmno").val();
var admno = $("#admno").val();
if (oadmno != admno) {
$.ajax({
type: "post",
url: "chkduplicateadmino.php",
data: $("#admno").serialize(),
success: function(data) {
if (data > 0) {
$("#admno")
.closest(".form-group")
.addClass("has-warning");
toastr.error("", "Duplicate admission no found", {
positionClass: "toast-bottom-right",
preventDuplicates: true
});
$("#admno").focus();
return false;
} else {
return true;
}
}
});
}
});
});

Only one alert for multiple execution in Ajax

I am working rails application.i need to get status of the each selected device.I am able to achieve this but after executing i am putting alert "Successfully created execution record".For every mac selection it is showing alert message.I need to give one alert in end of execution.I am calling display_result in call_endpoint method.Since it is an Ajax call,it is giving alert for every execution.i don't how to limit to single alert for this.
function display_result() {
$('#http_status').html("");
$('#http_status').append(result["response"].status);
if (result["response"].status == "404") {
console.log("HTTP 404");
$('#response_div').addClass("bs-callout-warning");
} else if (result["response"].status == "520") {
console.log("HTTP 502");
$('#response_div').addClass("bs-callout-danger");
} else {
console.log("HTTP 200");
$('#response_div').addClass("bs-callout-success");
if (result["response"].status == "200") {
// $('.loader').show();
$('#cover-spin').show();
$.ajax({
method: "GET",
dataType: "text",
url: "create_execution",
data: {
http_status: result["response"].status,
mac_address: mac,
},
success: function (execution_record_id) {
$('#cover-spin').hide();
alert('Successfully created execution record");
}
});
}
function call_endpoint() {
var values = new Array();
webpa = $('#Device-PA').is(":visible");
rpil = $('#Device-SN').is(":visible");
groupselect = $('#Group-Select').is(":visible");
parameter_name = $('#tr_object').val();
if (webpa) {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
} else {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
}
serialnumber = $('#pa_serialnumber').val();
oid = $('#sn_serialnumber').val();
protocol = {
pa: pa,
sn: sn,
}
if (pa) {
for (var i = 0; i < m; i++) {
(function () {
var macAdd = values[i];
$.ajax({
method: "GET",
url: "get_object",
dataType: "json",
data: {
parameter: parameter_name,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
NProgress.done();
console.log("result for webpa");
display_result();
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
})();
}
}
Below is changed code..
Copy below code as it is.
function display_result(total,current) {
$('#http_status').html("");
$('#http_status').append(result["response"].status);
if (result["response"].status == "404") {
console.log("HTTP 404");
$('#response_div').addClass("bs-callout-warning");
} else if (result["response"].status == "520") {
console.log("HTTP 502");
$('#response_div').addClass("bs-callout-danger");
} else {
console.log("HTTP 200");
$('#response_div').addClass("bs-callout-success");
if (result["response"].status == "200") {
// $('.loader').show();
$('#cover-spin').show();
$.ajax({
method: "GET",
dataType: "text",
url: "create_execution",
data: {
http_status: result["response"].status,
mac_address: mac,
},
success: function (execution_record_id) {
$('#cover-spin').hide();
if(total == current)
{
alert('Successfully created execution record");
}
}
});
}
}
}
function call_endpoint() {
var values = new Array();
webpa = $('#Device-PA').is(":visible");
rpil = $('#Device-SN').is(":visible");
groupselect = $('#Group-Select').is(":visible");
parameter_name = $('#tr_object').val();
if (webpa) {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
} else {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
}
serialnumber = $('#pa_serialnumber').val();
oid = $('#sn_serialnumber').val();
protocol = {
pa: pa,
sn: sn,
}
if (pa) {
for (var i = 1; i <= m; i++) {
(function () {
var macAdd = values[i];
$.ajax({
method: "GET",
url: "get_object",
dataType: "json",
data: {
parameter: parameter_name,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
NProgress.done();
console.log("result for webpa");
display_result(m,i);
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
})();
}
}
}
result and mac is not defined in display_result function. result appears intended to be the resulting value of jQuery promise object returned from $.ajax(). Am not certain what mac is indented to be.
You can substitute $.when() and $.map() for for loop, return a jQuery promise object from call_endpoint(), include error handling, chain .then() to call_endpoint() call to execute alert() once.
function call_endpoint() {
return $.when.apply($, $.map(values, function(macAdd) {
return $.ajax().then(display_result)
}))
}
callEnpoint()
.then(function() {
alert('Successfully created execution record');
}, function(jqxhr, textStatus, errorThrown) {
console.error(errorThrown)
});
function display_result(reuslt) {
..
if (if (result["response"].status == "200")) {
return $.ajax() // remove `alert()` from `success`
}
return;
}

setTimeout for search

I have this function, that make request to server to have data.
Here is a code of it
export default class StatusChecker {
constructor() {
if (gon.search && gon.search.searched) {
this.final_load();
} else {
this.make_request(this);
}
}
private make_request(context: StatusChecker) {
let myrequest;
myrequest = $.ajax({
url: "/search/status",
type: "GET",
context: context,
data: {
search_id: gon.search["id"]
},
success: this.handle_response,
error: this.handle_response_error
});
var t= setTimeout(function(){ myrequest.abort();}, 30000);
}
private handle_response(data): void {
if (data == "ready") {
this.request_itineraries();
} else {
setTimeout(() => this.make_request(this), 500);
}
}
private handle_response_error(): void {
$("#step_1_ajax_error").fancybox({
afterClose() {
return Helpers.navigate("/");
}
});
}
private request_itineraries(): void {
$.ajax({
url: "/search/itineraries",
type: "GET",
context: this,
data: {
search_id: gon.search["id"]
},
success: this.handle_request_itineraries
});
}
private handle_request_itineraries(data): void {
if (data.html.indexOf("step_1_search_error") > 0) {
Track.log_event("Show error screen", data.html);
$.fancybox.open($("#step_1_search_error"), {
afterClose() {
if (
gon.links !== null &&
gon.links.last_search !== null
) {
return Helpers.navigate(gon.links.last_search);
} else {
return Helpers.navigate("/");
}
}
});
} else {
// Update gon!
gon = data.gon;
$(".step_1_body").html(data.html);
$("#searching").hide();
$(".search_box_overlay").hide();
$(".search_box_overlay_top").hide();
this.final_load();
}
}
private final_load(): void {
if (gon.debug_enabled) {
ItinerariesResult.load_debug();
}
Filter.load();
Banners.load();
ItinerariesResult.load();
setTimeout(() => State.hide_searchfield(), 100);
}
}
But I faced this problem
Problem is if for some reason the state on the server side never change, then it will search forever. so it needs to give up at some point.
So I thought about this
It could be a simple setTimeout of 30 seconds added when search started. If it trigger after 30 seconds then it should expect something went wrong and show error message. If state changes then remove setTimeout again.
UPDATE
Making this var t= setTimeout(function(){ myrequest.abort();}, 30000);
Will not fixing issue, because
The problem is when the server always gives the same result over and over. Then you are stuck
How can I implement it in my code?
Set a name for ajax request and use .abort() when needed:
var shouldRepeat=true;
var myrequest;
private make_request(context: StatusChecker) {
myrequest= $.ajax({
url: "/search/status",
type: "GET",
context: context,
data: {
search_id: gon.search["id"]
},
success: this.handle_response,
error: this.handle_response_error
});
var t= setTimeout(function(){
myrequest.abort();
shoudlRepeat=false;},30000);
}
private handle_response(data): void {
if (data == "ready") {
this.request_itineraries();
} else {
if (shouldRepeat){
setTimeout(() => this.make_request(this), 500);
}
}
}
Edit: I also added a global boolean shouldRepeat which is initially true but when the 30 seconds timeout reached, it becomes false and prevents the execution of make_request(this) anymore.
private make_request(context: StatusChecker) {
// place timeout call here;
var timeout_flag = false;
window.setTimeout( function(){
timeout_flag = true;
}, 30000 );
$.ajax({
url: "/search/status",
type: "GET",
context: context,
data: {
search_id: gon.search["id"]
},
success: this.handle_response, // check for timeout
error: this.handle_response_error // check for timeout
});
}
[EDIT]
try this:
var max_requests = 5;
var requests = 0;
private handle_response(data): void {
if (data == "ready") {
requests = 0;
this.request_itineraries();
} else {
if( requests < max_requests ){
requests++;
setTimeout(() => this.make_request(this), 500);
}
}
}

How do I throw an error message within AJAX?

For some reason I can't throw an error message to say whether or not an email exists inside of my user table. I understand that because AJAX is async I can't use try and catch error messages inside the complete function. But I tried splitting it into functions and it still doesn't work.
Try, Catch Function (I do call this else where in my code)
try {
// Check fields are not empty
if (!firstName || !lastName || !aquinasEmail || !sPassword || !sCPassword || !Gender) {
throw "One or more field(s) have been left empty.";
}
// Check the email format is '#aquinas.ac.uk'
if(!emailCheck.test(aquinasEmail)) {
throw "The email address you entered has an incorrect email prefix. ";
}
// Check there are not any numbers in the First or Last name
if (!regx.test(firstName) || !regx.test(lastName)) {
throw "First Name or Last Name is invalid.";
}
// Check the confirmation password is the same as the first password
if (sPassword != sCPassword) {
throw "The two passwords you've entered are different.";
}
if(duplicatedEmail()) {
throw "Sadly, your desired email is taken. If you have forgotten your password please, Click Here";
}
} catch(err) {
if (!error) {
$('body').prepend("<div class=\"error alert\">"+err+"</div>");
$('.signupInput.sPassword').val('');
$('.signupInput.sCPassword').val('');
setTimeout(function() {
$('.error.alert').fadeOut('1000', function() {$('.error.alert').remove();});
}, 2600);
}
event.preventDefault();
}
AJAX Function:
function duplicatedEmail() {
// Use AJAX function to do verification checks which can not be done via jQuery.
$.ajax({
type: "POST",
url: "/login/ajaxfunc/verifyReg.php",
dataType: "JSON",
async: false,
data: $('.signupForm').serialize(),
success: function(data) {
if (data.emailTaken == true) {
return true;
} else {
return false;
}
}
});
}
verifyReg.php
<?php
header('Content-Type: application/json', true);
$error = array();
require_once '../global.php';
$_POST['aquinas-email'] = "aq142647#aquinas.ac.uk";
// Check if an email already exists.
$checkEmails = $db->query("SELECT * FROM users WHERE aquinasEmail = '{$_POST['aquinas-email']}'");
if ($db->num($checkEmails) > 0) {
$error['emailTaken'] = true;
} else {
$error['emailTaken'] = false;
}
echo json_encode($error);
?>
to handle the error with jquery ajax function add error callback like this
function duplicatedEmail() {
// Use AJAX function to do verification checks which can not be done via jQuery.
$.ajax({
type: "POST",
url: "/login/ajaxfunc/verifyReg.php",
dataType: "JSON",
async: false,
data: $('.signupForm').serialize(),
success: function(data) {
if (data.emailTaken == true) {
return true;
} else {
return false;
}
},
error: function() {
//Your Error Message
console.log("error received from server");
}
});
}
to throw an exception in your PHP:
throw new Exception("Something bad happened");
Looking at your AJAX Function, and these two answers here and here, you need to make a small change to how you are returning the synchronous result:-
function duplicatedEmail() {
var result;
$.ajax({
type: "POST",
url: "/login/ajaxfunc/verifyReg.php",
dataType: "JSON",
async: false,
data: $('.signupForm').serialize(),
success: function(data) {
result = data.emailTaken;
}
});
return result;
}
use ajax error function..
function duplicatedEmail() {
// Use AJAX function to do verification checks which can not be done via jQuery.
$.ajax({
type: "POST",
url: "/login/ajaxfunc/verifyReg.php",
dataType: "JSON",
async: false,
data: $('.signupForm').serialize(),
success: function(data) {
if (data.emailTaken == true) {
return true;
} else {
return false;
}
},
error: function (result) {
alert("Error with AJAX callback"); //your message
}
});
}

Categories

Resources