Prevent Bootstrap Modal from showing using ajax error - javascript

I was wondering if there is a way to prevent the Modal from showing up when an ajax call returns an error. I've seen a few posts here already that use
e.stopPropagation();
but I couldn't manage to make that work. My ajax call looks as follow
$.ajax({
url: url,
data: data,
dataType: 'json',
cache: false,
type: "POST",
error: function (e) {
//show error message
$('#alertdone').removeClass('hidden');
},
//if ajax call is successful populate form fields and hide error message
success: function (data) {
//hides the error message
$('#alertdone').addClass('hidden');
}
});
Thanks

I am assuming that you need to hide (don't show) the modal if the AJAX calls fails (since there's a difference between ajax call failing and returning error from server side).
For that you need to remove your data-attribute from HTML and do something like this:
$.ajax({
url: url,
data: data,
dataType: 'json',
cache: false,
type: "POST",
error: function (e) {
$('#alertdone').removeClass('hidden');
$("modal_selector").modal('hide');
},
//if ajax call is successful populate form fields and hide error message
success: function (data) {
$('#alertdone').addClass('hidden');
$("modal_selector").modal('show');
}
});

If you want to hide/ show modal depending on condition use modal()
$.ajax({
url: url,
data: data,
dataType: 'json',
cache: false,
type: "POST",
error: function (e) {
//show error message
$('#alertdone').removeClass('hidden');
$("Your_modal_id").modal('hide');
},
//if ajax call is successful populate form fields and hide error message
success: function (data) {
//hides the error message
$('#alertdone').addClass('hidden');
$("Your_modal_id").modal('show');
}
});

Related

Ajax: conflict in client between two functions

For a university homework, I have to create a little e-commerce website.
After the login, the user is redirected to the homepage. In this homepage, the client will recive a JSON object from the server (containing some product to be loaded) to generate the DOM of the homepage dynamically.
Note: I must use AJAX and JSON
I have this client.js file:
$(document).ready(function() {
// AJAX request on submit
$("#login_form").submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "submit.php",
data: {
Email: document.getElementById('login_email').value, // Email in the form
Password: document.getElementById('login_password').value // // Password in the form
},
cache: false,
success: function(){
window.location.href = "home.php"; // load the home.php page in the default folder
}
});
});
});
$(document).ready(function() {
// AJAX request to open a channel between php and client
function (e) {
e.preventDefault();
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
var data = JSON.parse(data);
alert(data); // debug
showProducts(data);
});
});
});
});
function showProducts(data){
alert(data);
// Insert object into the page DOM
}
I don't know why, but I can't access after the login if the second Ajax request (the AJAX request to open a channel between php and client) is not commented, and I don't know why, because the code seems right... Any suggestion?
after login action you need to set to cookie token in response
success: function(response){
console.log(response)
// then set to cookie response.token
window.location.href = "home.php";
}
after set token to cookie, you need to send this token to next ajax request url: "queries.php",
You need to wrap your anonymous function in parenthesis and add () at the end if you want to execute it:
(function (e) {
// I don't know why you need this:
e.preventDefault();
// etc.
})();
You should also check the contents of that function as you seem to have too many closing parentheses and you don't need to parse the returned value if you set the dataType to json.
In the end I think this is about all you need for that function:
(function () {
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
console.log(data); // debug
showProducts(data);
}
});
})();
or just:
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
console.log(data); // debug
showProducts(data);
}
});
To get it directly on page load.

ajax request sometime fails due to ERR_CONNECTION_RESET but not always

I am submitting a form using ajax. Form is consist of some textboxes, textareas etc (string data) and a file as well. I am sending the form as javascript FormData().
The problem is that the Ajax request sometimes failed but not always.
e.g. I tried to upload bigger files in zip, it was uploaded successfully five times but on the sixth attempt it got failed due to an error i got in the console "ERR_CONNECTION_RESET"
How to overcome this that it never happens. Thanks
Ajax Request using FormData():
var formData = new FormData();
formData.append("consider all my data here from form",data);
$.ajax({
url : 'abc.com/controller/function&token='+token,
type: 'post',
data: formData,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
$("#loader").show();
},
complete: function () {
$("#loader").hide();
},
success: function(json){
$("#loader").hide();
console.log(json);
},
error: function(error){
console.log(error);
alert("Something went wrong while updating chapter info. Please, refresh and try again.");
}
});

Loader not disappearing after AJAX result is received

I have page that displays data through AJAX, till the time the result is being fetched I wish to display a loader and as soon as the result is fetched I want that the loader should disappear. Below is part of the code where I am trying to display the loader
var onSubmit = function(e)
{
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$("#walkaway").hide();
$("#submitamt").hide();
$("#xtrabutton").hide();
LodingAnimate();
$.ajax(
{
type: 'post',
url: 'test2.php',
dataType: 'json',
data: {txt: txtbox,hidden: hiddenTxt},
cache: false,
success: function(returndata)
{
$('#first').html(returndata[0]);
$('#second').html(returndata[0]);
$('#third').html(returndata[0]);
},
error: function()
{
console.error('Failed to process ajax !');
}
});
function LodingAnimate()
{
$("#maillist").html('<img src="img/ajax-loader.gif" /> Please Wait Loading...');
}
};
On click of a button the above AJAX is executed, after the click the loader runs but even after I get the reply(in console) the loader keeps on running, but in actual it should have disappeared.
You should hide/remove the loader manually after ajax call completes, add Jquery Complete call back and add the code to remove the loader in it.
Jquery Complete - This call back will execute after success and error call back executed.
$.ajax(
{
type: 'post',
url: 'test2.php',
dataType: 'json',
data: {txt: txtbox,hidden: hiddenTxt},
cache: false,
success: function(returndata)
{
//Success code
},
error: function()
{
//error code
},
complete:function()
{
//This block will execute after success/error executes.
//Make the loader div empty
$("#maillist").empty();
}
});

Having Issue in showing dialog box inside ajax success bracket

I have a problem in my ajax script it wont show the dialog box after ajax success if i put datatype: 'json' and if I remove the dataType: 'json' the dialog shows pop after ajax success.
my script only shows my dialogbox if i remove the dataType.
$('#OppaForm').ajaxSubmit({
type: "POST",
url: "Oppa/view/editOther.php",
data: $('#OppaForm').serialize(),
cache: false,
success: function (response) {
$("#dialog-confirm-updateOther").dialog("open");
}
});
And I have an ajax script that shows the dialog box even the dataType is pressent.
$('#OppaForm').ajaxSubmit({
type: "POST",
url: "Oppa/view/photo.php",
dataType: "JSON",
data: $('#OppaForm').serialize(),
cache: false,
success: function (response) {
if (Number(response) == 1)
{
$("#dialog-confirm-changedImage").dialog("open");
$('#imageInput').replaceWith($('#imageInput').val('').clone(true));
}
}
});
if (Number(response) == 1)
this line will cause problem , beacuse response will not be 1 in case you need data type json
you can not compare like this
you will need to iterate through your json contents

Show a loading div during ajax post

I have a mobile app using mostly JQuery Mobile. I have an ajax function using POST and I can't seem to get anything to effect the UI when I fire the click event. I tried setting
$('#cover').show();
as the very first thing in the function then I do some basic things like document.getElementById('user') etc to set some variables and check input, but as long as the ajax function is there it won't show the div or even the spinner from JQ Mobile. Unless I debug and step through the code then the spinner and div show up fine. I tried setTimeout and putting it in the beforeSend area of the ajax call. Everything works fine otherwise. It seemed to work a little better with GET I'm not sure if that has anything to do with it or not.
$.ajax({
cache: false,
type: "POST",
async: false,
url: urlString,
data: jsonstring,
contentType: "application/json",
dataType: "json",
success: function (data) {
JSONobj = JSON.parse(data);
},
beforeSend: function(xhr){
//console.log('BeforeSend');
},
complete: function (xhr) {
//console.log('Complete');
},
error: function (xhr, status, error) {
console.log(error);
}
});
You could use the Ajax Global handlers to handle this:
$(document).
.ajaxStart(function(){
$('#cover').show();
})
.ajaxStop(function(){
$('#cover').hide();
});
This way you don't have to worry about showing/hiding the overlay on individual Ajax calls.
Try this
$("#someButton").click(function(e){
e.preventDefault() //if you want to prevent default action
$('#cover').fadeIn(100,function(){
$.ajax({
url: "someurl",
data: "Somedata",
contentType: "application/json",
dataType: "json",
},
success: function (data) {
JSONobj = JSON.parse(data);
$('#cover').fadeOut(100);
},
complete: function (xhr) {
$('#cover').fadeOut(100);
}
});
});
});

Categories