Page not loading after Postback event completes - ASP.Net - javascript

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

Related

Showing or hiding div not working with async false ajax calls

I have some functions that make some ajax calls.In order to execute everything the way is needed, these requests must by set with async: false.Everything is ok with the ajax call. My problem is that I need a div (a simple css loader) to be shown before send the request and hide after it, but it is not showing.This is my function:
$("#btn1").on('click', function(){
// Apparently it does not executes this
$('.container-loader').show();
//execute the function and handle the callback
doSomeStuff(function(c){
if(!c.ok){
showModalWarning();
$('#text').append('<li>'+c.msg+'</li>');
}
else{
toastr.success('Everything is ok');
doOtherStuff($("#select").val());
}
});
var modal = document.getElementById('Modal1');
modal.style.display = "none";
return false;
});
My doSomeStuff() function that makes the requests:
function doSomeStuff(callback){
//...
for (var i = 0; i < ids.length; i++) {
var Id = ids[i][0];
var ch = ids[i][1];
var tp = 2;
var url = 'http://domain.com.br:8080/datasnap/rest/TSM/Fun/' + tp + '/' + $("#select").val() + '/' + ch;
$.ajax({
cache: "false",
async: false, //it needs to by with async false
dataType: 'json',
type: 'get',
url: url,
success: function(data) {
if (!data)
toastr.error('error' );
},
error: function(jqXHR, textStatus, errorThrown) {
toastr.error("some problem");
}
});
}
callback({ok: true});
}
Any idea on how can I handle this? I am really new with async stuff.
Solved this by removing async and changing the mthod in my server to receive an array as a parameter. The final script:
$("#btn1").on('click', function(){
//$('.container-loader').show();
//execute the function and handle the callback
doSomeStuff(function(c){
if(!c.ok){
showModalWarning();
$('#text').append('<li>'+c.msg+'</li>');
}
else{
toastr.success('Everything is ok');
doOtherStuff($("#select").val());
}
});
});
My doSomeStuff() function that makes the requests:
function doSomeStuff(callback){
//...
var tp = 2;
var url = 'http://domain.com.br:8080/datasnap/rest/TSM/Fun/' + tp + '/' + $("#select").val() + '/' + encodeURIComponent(JSON.stringify(jsonArray));
$.ajax({
cache: "false",
//async: false, //it needs to by with async false
dataType: 'json',
type: 'get',
url: url,
success: function(data) {
if (!data)
callback({ok: false});
},
error: function(jqXHR, textStatus, errorThrown) {
toastr.error("some problem");
}, complete: function(){ //hide the loader after complete
$('.container-loader').hide();
var modal = document.getElementById('Modal1');
modal.style.display = "none";
}
});
}

ajax loading indicator stopped in between

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.

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");
}
});

make an ajax call in the very first page in JQM

I am trying to show a popup in my first page if a php post returns a json file with data.
I tried with:
$(document).on("pageinit", '#home', function() {
ajax call even with async:false,...
And after that, I fill up the element with some list elements if json has data:
if(userLastPush == 1){
var getPushXdays = '{"day":"4"}';
$.ajax({
type: "POST",
url: urlServer+"getPushXDays.php",
data: getPushXdays,
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
//console.log(response);
html = '';
if(response.message != "empty"){
jQuery.each(response, function(category, val) {
if(val.id_Event == 0){
html +='<li>' + val.message + '</li>';
}else{
html +='<li>' + val.message + '</li>';
}
});
}
$(".popupPush").append(html).listview('refresh');
if(checkPushing == 0){
$("#checkpush").trigger("click");
}
},
error: function(xhr, status, message) {}
});
}
But it just works sometimes. Others, ajax never ends or never shows data. I tried by using a function instead and function is called but no return from ajax. Is there a way to make this getting all data before page is load?

ajax post error: internal error 500 on post method

I am running the script below whe a timer has run out of time, the post was working fine when i started passing the data through that is need for the final information is saved. that when got an internal error.
JavaScript ajax call
var selectedval;
if (document.getElementById('RadioButtonList1_0').checked == true) {
selectedval = document.getElementById('RadioButtonList1_0').value
}
else if (document.getElementById('RadioButtonList1_1').checked == true) {
selectedval = document.getElementById('RadioButtonList1_1').value
}
else if (document.getElementById('RadioButtonList1_1').checked == true) {
selectedval = document.getElementById('RadioButtonList1_1').value
}
else if (document.getElementById('RadioButtonList1_2').checked == true) {
selectedval = document.getElementById('RadioButtonList1_2').value
}
else if (document.getElementById('RadioButtonList1_3').checked == true) {
selectedval = document.getElementById('RadioButtonList1_3').value
}
else {
selectedval = '';
}
var qustNo = document.getElementById('ltlQuestNos').innerHTML;
`enter code here` $.ajax({
type: "GET",
data: '{questNo:'+ qustNo.trim().toString()+',selectedoption:'+ selectedval.toString()+'}',
contentType: "application/json; charset=utf-8",
url: "prTest.aspx/timeFinished",
dataType: "json",
success: function (result) {
// this displays the information so that the page can be re-directed to the results page.
window.location = result.d;
}
Vb.net code.
<WebMethod()>
Public Shared Function timeFinished(questNo As String, selectedoption As String) As String
Dim objExam As New examClass()
If selectedoption = "-1" Then
'lblWarning.Visible = True
'lblWarning.Text = "Please answer Question!"
Else
' lblMessage.Text = "Navigation = " & Request.Form("textNav")
objExam.answerQuestion(HttpContext.Current.Session("examid"), questNo, selectedoption, "00:00:00")
' lblWarning.Visible = False
'close connection
objExam.Dispose()
End If
objExam.finishTest(Convert.ToInt32(HttpContext.Current.Session("examid").ToString()))
objExam.Dispose()
' HttpContext.Current.Response.Redirect("ChapterTestSummary.aspx", true);
Dim url As String = "testsummary.aspx"
Return url
End Function
I think the problem is with data part in ajax. Because, if you are building the data as string by yourself, key and value should enclosed in double quotes. Otherwise make it as an object and use JSON.stringify() method to make it as string.
$.ajax({
type: "GET",
data: JSON.stringify({
questNo: qustNo.trim(),
selectedoption: selectedval
}),
contentType: "application/json; charset=utf-8",
url: "prTest.aspx/timeFinished",
dataType: "json",
success: function(result) {
// this displays the information so that the page can be re-directed to the results page.
window.location = result.d;
}
});

Categories

Resources