ajax loading indicator stopped in between - javascript

I am saving data on a save button click that calls ajax and passing json data to a controller method but when we save it loading starts and suddenly stop though the data is not saved.
It is not working I have tried it in all way but not working please help me on this.
<button type="button" id="saveDeleg" class="btn_reg_back btnmainsize btnautowidth btngrad btnrds btnbdr btnsavesize " aria-hidden="true" data-icon="">#Resources.Resource.Save</button>
$('#saveDeleg').click(function() {
var response = Validation();
if (!response) {
return false;
}
$("#overlay").show();
$('.loading').show();
if ($('#organName').val() == '') {
$('#validorganisation').show();
return false;
} else {
$('#validorganisation').hide();
}
//Contact name
var SubDelegation = $('#subdelegation').is(':checked');
var CopyNotification = $('#copynotification').is(':checked');
var ArrangementId = $("#ArrangementId").val();
var paramList = {
ArrangementId: ArrangementId,
ArrangementName: $('#arrangName').val(),
OrganisationName: $('#organName').val(),
OrganisationId: $('#OrganisationId').val(),
ContactName: $('#contactName').val(),
ContactId: $('#ContactId').val(),
SubDelegation: $('#subdelegation').is(':checked'),
CopyNotification: $('#copynotification').is(':checked'),
ContactType: $('#ContactType').val(),
SelectedTypeName: $("input[name$=SelectedType]:checked").val()
};
setTimeout(function() {
$.ajax({
async: false,
type: "POST",
url: '#Url.Action("SaveDelegation", "Structures")',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(paramList),
processdata: true,
success: function(result) {
//stopAnimation()
paramList = null;
if (result == 0) {
window.location.href = '../Structures/MyDelegationArrangement';
} else if (result == 1) {
window.location.href = '../Structures/CreateDelegation';
} else if (result == 2) {
window.location.href = '../Home/Error';
} else if (result == 3) {
window.location.href = '../Account/Login';
} else {
//validation message
alert('Error');
}
},
error: function() {},
complete: function() {
$("#overlay").hide();
$('.loading').hide();
}
});
}, 500);
});

The problem with the loading indicator is because you used async: false which locks up the UI. Remove that setting.
Also note that if the data is not being saved I would assume that your AJAX call is returning an error. If so, check the console to see the response code. It may also be worth putting some logic in the error callback function to give you some information on whats happened, as well as inform your users about what to do next.

Related

When submitting an ajax request, how can you "put the original request on hold" temporarily until a condition is met?

I am wanting to implement a recaptcha process that captures all ajax requests before they go through - the desired process would be as follows:
User completes an action which is going to cause an ajax request of some sort.
If the user has already completed the recaptcha process, the ajax request proceeds without further delay
If the user has not completed the recaptcha process, put the ajax request "on hold" temporarily until the recaptcha process is completed, then continue the ajax request.
I have got things to a state where I intercept the call, however I don't know how to put it on hold temporarily. Here's the relevant code:
<script>
var captchaValidated = null;
var currentRequests = [];
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (options.url != "/ValidateCaptcha") {
if (captchaValidated == null || captchaValidated == false) {
if (captchaValidated == null){
openRecaptcha();
} else {
verifyCaptcha(); //see async question in method
}
if (!captchaValidated) {
jqXHR.abort();
} else {
//let the original request proceed now - but how?!
}
}
}
});
function verifyCaptcha() {
var grecaptcha = $("g-recaptcha-response");
var encodedResponse;
if (grecaptcha != null) {
encodedResponse = grecaptcha.val();
$.ajax({
async: false, //set to false so that the calling method completes rather than async - what do you think?
headers: headers,
cache: false,
url: "/ValidateCaptcha",
type: 'POST',
contentType: 'application/json',
success: function (data) {
//parse the data - did we get back true?
captchaValidated = data;
},
error: function (raw, textStatus, errorThrown) { captchaValidated = null; alert("Validate ReCaptcha Error: " + JSON.stringify(raw)); },
data: JSON.stringify({ "encodedResponse": encodedResponse })
});
}
}
function invalidateCaptcha(){
captchaValidated = null;
}
function openRecaptcha() {
grecaptcha.render('recaptcha', {
'sitekey': "thekey",
'callback': verifyCaptcha,
'expired-callback': invalidateCaptcha,
'type': 'audio image'
});
$("#recaptchaModal").modal('show');
}
</script>
Any suggestions of how to proceed would be appreciated, thanks in advance!
Thank you #Loading and #guest271314 for your help in pointing me in the right direction that helped me get things figured out. I've pasted how I accomplished it below - perhaps it will be of help to someone else. Of course if anyone would like to weigh in on my implementation please do.
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCaptcha&render=explicit&hl=en" async defer></script>
<script>
var captchaValidated = null;
var currentRequests = [];
var captchaPrompted = false;
var captchaReady = false;
var resetCaptcha = false;
function onloadCaptcha() {
captchaReady = true;
captcha = grecaptcha.render('recaptcha', {
'sitekey': '<yoursitekey>',
'callback': verifyCaptcha,
'expired-callback': invalidateCaptcha,
'type': 'audio image'
});
}
var deferredCaptcha = null;
var promiseCaptcha = null;
var captcha = null;
function openRecaptcha() {
if (!captchaReady) {
setTimeout(openRecaptcha, 50);
}
if (captchaPrompted) {
return;
}
captchaPrompted = true;
var captchaTimer = setInterval(function () {
if (captchaValidated != null) {
if (captchaValidated) {
deferredCaptcha.resolve();
} else {
deferredCaptcha.reject();
captchaValidated = null;
}
}
}, 100);
if (resetCaptcha) {
captcha.reset();
}
deferredCaptcha = $.Deferred();
promiseCaptcha = deferredCaptcha.promise();
promiseCaptcha.done(function () {
//captcha was successful
clearInterval(captchaTimer);
//process the queue if there's items to go through
if (currentRequests.length > 0) {
for (var i = 0; i < currentRequests.length; i++) {
//re-request the item
$.ajax(currentRequests[i]);
}
}
});
promiseCaptcha.fail(function () {
//captcha failed
clearInterval(captchaTimer);
currentRequests = []; //clear the queue
});
$("#recaptchaModal").modal('show');
}
function verifyCaptcha() {
resetCaptcha = true;
var response = $("#g-recaptcha-response").val();
var encodedResponse;
// confirm its validity at the server end
$.ajax({
headers: headers,
cache: false,
url: "/ValidateCaptcha",
type: 'POST',
contentType: 'application/json',
success: function (data) {
captchaValidated = data;
if (!data) {
captchaPrompted = false;
}
},
error: function (raw, textStatus, errorThrown) { captchaValidated = false; captchaPrompted = false; alert("WTF Validate ReCaptcha Error?!: " + JSON.stringify(raw)); },
data: JSON.stringify({ "encodedResponse": response })
});
}
function invalidateCaptcha(){
deferredCaptcha.reject();
captchaValidated = null;
resetCaptcha = true;
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (settings.url == '/ValidateCaptcha' || captchaValidated) {
// we're validating the captcha server side now or it's already been validated - let it through
} else {
if (typeof settings.nested === 'undefined'){
settings.nested = true; //this flag is to determine whether it's already in the queue
currentRequests.push(settings); //add the request to the queue to be resubmitted
//prompt them with the captcha
openRecaptcha();
}
return false; // cancel this request
}
}
});
</script>
At $.ajaxPrefilter() use .then() chained to openCaptcha to call verifyCaptcha
if (captchaValidated == null){
openRecaptcha().then(verifyCaptcha);
}
at verifyCaptcha use .is() with parameter "*" to check if an element exists in document
if (grecaptcha.is("*")) {
at openRecaptcha(), if grecaptcha.render does not return asynchronous result return jQuery promise object using .promise(); else chain to grecaptcha.render and $("#recaptchaModal").modal('show'); using $.when()
return $("#recaptchaModal").modal('show').promise()
or
return $.when(grecaptcha.render(/* parameters */)
, $("#recaptchaModal").modal('show').promise())
Something like this? (pseudo-code)
verified = false;
$('#myButton').click(function(){
if (!verified) verify_by_captcha();
if (verified){
$.ajax(function(){
type: 'post',
url: 'path/to/ajax.php',
data: your_data
})
.done(function(recd){
//ajax completed, do what you need to do next
alert(recd);
});
}
});//end myButton.click

showing loader image with submition using ajax

$(document).ready(function(){
$('#registration_form').on('submit',function(e){
/// e.preventDefault();
$("#loading").show();
var email = $('#email').val();
var checkEmail = $("#email").val().indexOf('#');
var checkEmailDot = $("#email").val().indexOf('.');
if(email == ''){
$("#email").addClass('error');
error_flag = 1;
}
if(checkEmail<3 || checkEmailDot<9){
$("#email").addClass('error');
error_flag = 1;
}
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
// url: "<?=base_url('controller/register')?>",
type: "POST",
datatype: "JSON",
data: {email: email},
success: function(res){
var data = $.parseJSON(res);
var status = data.status;
var message = data.message;
if(status == 'true'){
// $('#myModal').modal('hide');
$('#message').html('');
$('#message').html(message);
$('#message').css('color',"green");
$("loading").hide();
}
else{
$('#message').html('');
$('#message').html(message);
$('#message').css('color',"red");
}
}
});
e.preventDefault();
});
});
how to use loader with ajax when message is success the load stop when message is or error loader is stop how to use loader image image in this stiuation. if submition is true loading hide if false loading also hide.
how to use loader with ajax when message is success the load stop when message is or error loader is stop how to use loader image image in this stiuation. if submition is true loading hide if false loading also hide.
You can use the always handler to do that.
Also note that, you should so the loader only if the ajax is sent, so in your case only after the validations are done it should be done.
$(document).ready(function() {
$('#registration_form').on('submit', function(e) {
/// e.preventDefault();
var email = $('#email').val();
var checkEmail = $("#email").val().indexOf('#');
var checkEmailDot = $("#email").val().indexOf('.');
if (email == '') {
$("#email").addClass('error');
error_flag = 1;
}
if (checkEmail < 3 || checkEmailDot < 9) {
$("#email").addClass('error');
error_flag = 1;
}
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
// url: "<?=base_url('controller/register')?>",
type: "POST",
datatype: "JSON",
data: {
email: email
},
beforeSend: function() {
//show it only if the request is sent
$("#loading").show();
},
success: function(res) {
var data = $.parseJSON(res);
var status = data.status;
var message = data.message;
if (status == 'true') {
// $('#myModal').modal('hide');
$('#message').html('');
$('#message').html(message);
$('#message').css('color', "green");
$("loading").hide();
} else {
$('#message').html('');
$('#message').html(message);
$('#message').css('color', "red");
}
}
}).always(function() {
//irrespective of success/error hide it
$("#loading").hide();
});
e.preventDefault();
});
});
Have a loading image like this:
<img src="loader.gif" id="loader" />
And in the script, before the AJAX call, show it:
$("#loader").fadeIn(); // You can also use `.show()`
$.ajax({
// all your AJAX stuff.
// Inside the success function.
success: function (res) {
// all other stuff.
// hide the image
$("#loader").fadeOut(); // You can also use `.hide()`
} // End success
}); // End AJAX
Solution to your Problem
You are missing # in your call:
$("loading").hide();
//-^ Add a # here.
Change it to:
$("#loading").hide();
I'd do it this way:
function loadsth(){
$('#load_dialog').show();
$.ajax({
method: "POST",
url: "?ajax=ajax_request",
data: { data:"test"},
success:function(data) {
$('#load_dialog').hide();
}
});
});
Try using jquery's ajax function beforeSend
$.ajax({
method: "POST",
url: "/url",
data: { data:"test"},
beforeSend: function() {
//SHOW YOUR LOADER
},
success:function(data) {
//HIDE YOUR LOADER
}
});
});
I hope this has given you some idea.
try this its work for u
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
type: 'POST',
beforeSend: function(){
$("#loaderDiv").show();
},
success: function(data) {
$('#output-json-inbox').jJsonViewer(data);
$("#loaderDiv").hide();
},
error: function() {
alert("error");
}
});

Page not loading after Postback event completes - ASP.Net

I have a Javascript function on a button click with a POST to a WebMethod. After getting the response back; which is a redirect URL, the code goes to the IsPostBack event of the redirected page but that page never loads. I have written redirects all over the place but somehow this one just stays on the page it is called from.
jQuery.ajax({
type: "POST",
url: "MyProfile.aspx/UpdateProfile_Clicked",
async: false,
data: parms,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d != '') {
alert("Your profile has been updated.");
// response.d = "SubmitRequest.aspx"
var data = response.d;
if (data.indexOf("aspx", 0) > -1) {
redirect(data);
}
}
return false;
},
error: function (httpRequest, textStatus, errorThrown) {
LogAjaxErrorToServer(httpRequest, textStatus, errorThrown, parms, "UpdateProfile_Clicked");
}
});
function redirect(url) {
if (url == "") { return false; }
var indx = window.location.pathname.lastIndexOf('/', 0);
if (indx < 0) { indx = 0; }
var local = window.location.pathname.substr(0, indx);
local += "/" + url;
location.href = local;
return false;
}
So the code does go to the (!IsPostBack) for SubmitRequest.aspx but stays on the Profile.aspx. What am I missing? Thank you in advance for helping me
May

javascript mutually exclusive CheckBox issue

I have a radio button that displays a list of records in a telerik grid. When the radio button is checked, it displays complete and incomplete records. However, the user wants a way of displaying only complete or incomplete records. I added two mutually exclusive checkboxes. The user can either check the complete or incomplete checkbox to display the data. It works fine on my local, but it does not work well on the server. The first time, the user has to click the checkbox two or three times before it can keeps the state. In addition, if complete is checked and the user checked incomplete next, the checkmark will go back to complete. The user has to do it a second times. What I am doing wrong here?
Here is the html for the checkbox
#Html.CheckBox("complete", SessionWrapper.currentEncounter.complete, new { id = "chkComplete", onclick = "chkInCompleteOption(1);this.form.submit();" }) <strong>Complete</strong>
#Html.CheckBox("Incomplete", SessionWrapper.currentEncounter.incomple, new { id = "chkInComplete", onclick = "chkInCompleteOption(2);this.form.submit();" }) <strong>Incomplete</strong>
//Here is the javascript
var completeCheck = '#SessionWrapper.currentEncounter.complete';
var inCompleteCheck = '#SessionWrapper.currentEncounter.incomplete';
function chkInCompleteOption(e) {
if (e == 1) {
var cc = $('#chkComplete').is(':checked');
var data = { "complete": cc, "inComplete": false };
var url = '#Url.Action("CompletedOption", "Orders")';
$.ajax({
url: url,
type: 'post',
dataType: 'text',
data: data,
success: function (data) {
testComplete();
return true;
},
error: function (error) {
alert("An error has occured.");
return false;
}
});
}
else if (e == 2) {
var inc = $('#chkInComplete').is(':checked')
var data = { "complete": false, "inComplete": inc };
var url = '#Url.Action("CompletedOption", "Orders")';
$.ajax({
url: url,
type: 'post',
dataType: 'text',
data: data,
success: function (data) {
testInComplete();
return true;
// $('#chkComplete').removeAttr("checked", "checked");
// $('#chkInComplete').attr("checked", "checked");
},
error: function (error) {
alert("An error has occured.");
return false;
}
});
}
}
function testInComplete() {
if (inCompleteCheck == true) {
inCompleteCheck = $('#chkInComplete').attr("checked", "checked");
document.getElementById('chkInComplete').checked = true;
} else {
$('#chkInComplete').removeAttr("checked");
}
}
function testComplete() {
if (inCompleteCheck == true) {
completed = $('#chkComplete').attr("checked", "checked");
document.getElementById('chkComplete').checked == true;
} else {
$('#chkComplete').removeAttr("checked");
}
}
//Setting the mutually exclusive value on the server side
public bool CompletedOption(bool complete, bool inComplete)
if (inComplete == true && complete == true)
{
return false;
}
if (complete == true)
{
SessionWrapper.currentEncounter.complete = true;
}
else if (SessionWrapper.currentEncounter.complete == true && (complete == null || inComplete == null))
{
SessionWrapper.currentEncounter.complete = true;
}
else
{
SessionWrapper.currentEncounter.complete = false;
}
if (inComplete == true)
{
SessionWrapper.currentEncounter.incomplete = true;
}
else if (SessionWrapper.currentEncounter.incomplete == true && (complete == null || inComplete == null))
{
SessionWrapper.currentEncounter.incomplete = true;
}
else
{
SessionWrapper.currentEncounter.incomplete = false;
}
return true;
}
I found the issue. The server side was being updated properly; however, the ajax was returning an error message every time it executed. The method on the server side was returning a Boolean when a string was expected. I've also set async and cache to false. I ran the application again, and it works.
//Change Method Signature from boolean to string
public string CompletedOption(bool complete, bool inComplete)
{
return "true";
}
ajax post
$.ajax({
url: url,
type: 'post',
dataType: 'text',
async: false, //Added
cache: false, //Added
data: data,
success: function (data) {
return data;
},
error: function (error) {
alert("An error has occured.");
return false;
}
});

my javascript code will not proceed to delete my data from jqGrid

just want to ask regarding my javascript code. I have a function that will delete and edit a data in my jqgrid. But everytime i run my code, it will not delete and edit if I dont put an alert in some portion of the code. Why is it happening? How can i make my program run without the alert?
Below is my delete function:
function woodSpeDelData(){
var selected = $("#tblWoodSpe").jqGrid('getGridParam', 'selrow');
var woodID='';
var woodDesc='';
var codeFlag = 0;
var par_ams = {
"SessionID": $.cookie("SessionID"),
"dataType": "data"
};
//this part here will get the id of the data since my id was hidden in my jqgrid
$.ajax({
type: 'GET',
url: 'processjson.php?' + $.param({path:'getData/woodSpecie',json:JSON.stringify(par_ams)}),
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$.each(data['result']['main']['rowdata'], function(rowIndex, rowDataValue) {
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
var fldName = data['result']['main']['metadata']['fields'][columnIndex].name;
if (fldName == 'wood_specie_id'){
woodID = rowArrayValue;
}
if (fldName == 'wood_specie_desc'){
woodDesc = rowArrayValue;
alert($('#editWoodSpeDesc').val() +' '+ woodDesc); //program will not delete without this
if(selected == woodDesc){
codeFlag =1;
alert(woodID); //program will not delete without this
};
}
});
if (codeFlag == 1){
return false;
}
});
if (codeFlag == 1){
return false;
}
}
}
});
alert('program will not proceed without this alert');
if (codeFlag == 1) {
var datas = {
"SessionID": $.cookie("SessionID"),
"operation": "delete",
"wood_specie_id": woodID
};
alert(woodID);
alert(JSON.stringify(datas));
$.ajax({
type: 'GET',
url: 'processjson.php?' + $.param({path:'delete/woodSpecie',json:JSON.stringify(datas)}),
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$('#tblWoodSpe').trigger('reloadGrid');
}
}
});
}
}
EDIT
My main purpose of putting an alert was just to know if my code really get the right ID of the description, and if would really go the flow of my code... But then i realized that it really wont work with it.

Categories

Resources