I have the following js code:
$("#add_station").on('click', function () {
$(this).closest('form').submit(function () {
alert("working!");
$.ajax({
url: advoke.base_url + "/new-vendor-user/station/ajax",
method: 'post',
processData: false,
contentType: false,
cache: false,
dataType: 'json',
data: new FormData(this),
beforeSend: function () {
$('.info').hide().find('ul').empty();
$('.success_message').hide().find('ul').empty();
$('.db_error').hide().find('ul').empty();
},
success: function (data) {
if (!data.success) {
$.each(data.error, function (index, val) {
$('.info').find('ul').append('<li>' + val + '</li>');
});
$('.info').slideDown();
setTimeout(function () {
$(".info").hide();
}, 5000);
} else {
$('.success_message').slideDown();
$('#add_station').remove();
$("#station").append(data.new_station);
setTimeout(function () {
$(".success_message").hide();
}, 5000);
} //success
},
error: function () {
//db error
$('.db_error').append('<li>Something went wrong, please try again!</li>');
$('.db_error').slideDown();
//Hide error message after 5 seconds
setTimeout(function () {
$(".db_error").hide();
}, 5000);
} //error
});
});
return false;
});
When I click the button with the id add_station it alerts on click function after $($this).closest('form').submit(function(){...) it doesn't work as you can see I've put an alert 'works' after submit function.I get no errors on the console and I can't figure what the problem is. Also, the button that is clicked is inside a form.
I need to use $($this).closest('form').submit(function(){...) inside because after ajax success a new form will be generated with add station button that will use this code.
You should block the default submit trigger by using
e.preventDefault();
$(this).closest('form').submit(function (e) {
e.preventDefault();
<!--rest of the code-->
})
add a separately submit handler
$("#add_station").on('click', function () {
$(this).closest('form').submit();
});
$("form").on("submit", function (e) {
e.preventDefault();
alert("working!");
$.ajax({
url: advoke.base_url + "/new-vendor-user/station/ajax",
method: 'post',
processData: false,
contentType: false,
cache: false,
dataType: 'json',
data: new FormData(this),
beforeSend: function () {
$('.info').hide().find('ul').empty();
$('.success_message').hide().find('ul').empty();
$('.db_error').hide().find('ul').empty();
},
success: function (data) {
if (!data.success) {
$.each(data.error, function (index, val) {
$('.info').find('ul').append('<li>' + val + '</li>');
});
$('.info').slideDown();
setTimeout(function () {
$(".info").hide();
}, 5000);
} else {
$('.success_message').slideDown();
$('#add_station').remove();
$("#station").append(data.new_station);
setTimeout(function () {
$(".success_message").hide();
}, 5000);
} //success
},
error: function () {
//db error
$('.db_error').append('<li>Something went wrong, please try again!</li>');
$('.db_error').slideDown();
//Hide error message after 5 seconds
setTimeout(function () {
$(".db_error").hide();
}, 5000);
} //error
});
});
after ajax success a new form will be generated with add station
button that will use this code
If you generate a new button you have to bind the click again after it is placed to the dom.
Related
I have 1 POST ajax and 1 GET ajax, and I have this:
$(document).ready(function () {
$(document).ajaxStart(function () {
$("#div28").show();
});
$(document).ajaxStop(function () {
$("#div28").hide();
});
});
It is for showing the LoadingGif, at this point it is showing for both Ajax requests, so what should I do to make the LoadingGif show only when the POST type ajax is working?
EDIT:
Here are my ajax functions:
$(document).ready(function () {
$.ajax({
contentType: "application/json; charset=utf-8",
type: 'GET',
url: 'api/Appointments/',
dataType: 'json',
success: function (result) {
if ((result.AppTime = "9:00") && (result.AppWithYritys = "Laakkonen")) {
document.getElementById("A9").style.background = "red";
}
else {
alert("error1");
}
},
error: function (error) {
alert("error");
},
});
});
and the POST ajax:
var request = $.ajax({
type: "POST",
data: JSON.stringify(app),
url: "/api/Appointments",
contentType: "application/json",
dataType: "html"
});
request.done(function (data) {
if (data != -1) {
alert("You Have successfully made an appointment");
location.assign("http://tid.fi");
}
else {
alert("There has been an error!");
}
});
request.fail(function (gr) {
location.assign("http://google.com");
});
};
POST ajax is in a custom function which is trigger on a button-click. Just an info.
using ajaxSend and ajaxComplete you can see what the "type" of request is
However, you'll need to keep a count of active requests too - possibly not required for your simple page - but it's good to have
$(document).ready(function () {
var started = 0;
$(document).ajaxSend(function (event, jqXHR, settings) {
if (settings.type == 'POST') {
if(!(started++)) { // only need to show on the first simultaneous POST
$("#div28").show();
}
}
});
$(document).ajaxComplete(function (event, jqXHR, settings) {
if (settings.type == 'POST') {
if(!(--started)) { // only hide once all simultaneous POST have completed
$("#div28").hide();
}
}
});
});
Solution without counters
$(document).ready(function () {
$(document).ajaxSend(function (event, jqXHR, settings) {
if (settings.type == 'POST') {
$("#div28").show();
}
});
$(document).ajaxStop(function () {
$("#div28").hide();
});
});
This will show on POST, and hide once all ajax has stopped - a little less obvious, but it's probably just as valid a solution
I think the easiest option is to create a tiny functions that you can use:
function showLoading(isLoading){
if(isLoading){
$("#div28").show();
}
else{
$("#div28").hide();
}
};
Then use as documented here Ajax events
just use the function either using the global events for your specific post or call the function directly on the beforeSend and complete event hooks.
As title, I tried load data from ajax to zabuto calendar, but seem it's not working, ref of zabuto calendar http://zabuto.com/dev/calendar/examples/show_data.html. And i want to use this function load data when click nav prev month or next month. (use two action action and action_nav). This is snipped code
<script>
$(document).ready(function () {
function load_data() {
var list = '';
$.ajax({
type: "POST",
url: "../BUS/WebService.asmx/LOAD_DATA",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
list = $.parseJSON(data.d);
console.log(list);
}
});
return list;
}
function myNavFunction(id) {
//code in here
}
function myDateFunction(id) {
//code in here
}
$("#my_calendar").zabuto_calendar({
data: load_data(),
action: function () {
return myDateFunction(this.id);
},
action_nav: function () {
return myNavFunction(this.id);
}
});
});
</script>
When i test this, data not show, the data from ajax as
{ "date": "2016-06-01", "title": 2, "badge": true },{ "date": "2016-06-04", "title": 1, "badge": true },{ "date": "2016-06-10", "title": 1, "badge": true }
Thank you so much.
Try the following: you need to place the calendar function in the success function of the ajax call because ajax is asynchronous
$(document).ready(function () {
function load_data() {
$.ajax({
type: "POST",
url: "../BUS/WebService.asmx/LOAD_DATA",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
var list = $.parseJSON(data.d);
$("#my_calendar").zabuto_calendar({
data: list;
});
},
error: function (data) {
console.log(data.d);
}
});
}
load_data();
});
I solved the issue by the code as below. It works well in window's browser but not in a mobile browser.
function initZabuto(id, events, month){
$('#zabuto_parent').empty().append("<div id='"+id+"'></div>");
$("#"+id).zabuto_calendar({
year:moment(month).format("YYYY"),
month:moment(month).format("MM"),
language:"cn",
data: events,
action: function () {
zabutoDayClick(this.id);
},
action_nav: function () {
zabutoMonthChange(this.id);
}
});
}
This is the code I used to refresh Zabuto calendar after a modal. The problem with other options is that upon refresh, Zabuto would create a new batch of modals appended to the current body. This solutions clears all those "old" modals and opens room for the new. Key area is the success section of the modal update ajax.
$(document).ready(function () {
$("#date-popover").popover({html: true, trigger: "manual"});
$("#date-popover").hide();
$("#date-popover").click(function (e) {
$(this).hide();
});
load_calendar();
});
function load_calendar() {
$("#my-calendar").zabuto_calendar({
show_next: 1,
action: function () {
return myDateFunction(this.id, false);
},
ajax: {
url: "calendar-info.php",
modal: true
},
});
}
function myDateFunction(id, fromModal) {
$("#date-popover").hide();
if (fromModal) {
$("#" + id + "_modal").modal("hide");
var date = $("#" + id).data("date");
var optradio = $("#" + id + "_modal").find("input[name='optradio']:checked").val();
$.ajax("calendar-update.php?status="+optradio+"&date="+date, {
success: function(data) {
$(".modal").remove();
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
$("#my-calendar").empty();
load_calendar();
},
error: function() {
alert("Problem!");
}
});
}
var hasEvent = $("#" + id).data("hasEvent");
if (hasEvent && !fromModal) {
return false;
}
return true;
}
I found lots os posts with the solution to my problem, but no one works to me...
I tried like:
<div class="ibox-content">
<div id="carregando" class="text-center" style="display:none">
<img src="~/Imagens/logo.png" />
</div>
<div id="container" style="height: 460px; margin: 0 auto"></div>
</div>
My JS is called on a button clink who calls a funcion like bellow:
$("#atualiza").click(function () {
$(document).ajaxStart(function () {
$("#carregando").show();
});
$.ajax({
url: '/Portaria/AtendOperador',
dataType: "json",
type: "GET",
data: { 'data1': data1, 'data2': data2, 'evento': evento, 'cuc': cuc, 'conta': conta },
async: false,
cache: false,
delay: 15,
success: function (data) {
var Categories = new Array();
var Series = new Array();
for (var i in data) {
Categories.push(data[i].Operador);
Series.push(data[i].Fechados);
}
var CategArray = JSON.parse(JSON.stringify(Categories));
atendOperador(CategArray, Series);
$(document).ajaxStop(function () {
$("#carregando").hide();
});
},
error: function (xhr) {
alert('error');
$(document).ajaxStop(function () {
$("#carregando").hide();
});
}
});
});
function atendOperador(CategArray, Series) {
var chart2 = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'bar'
}
});
}
Even I put the code:
$( document ).ajaxStart(function() {
$( "#carregando" ).show();
});
The image appear only after ajax finishing. Using the two blocks, show and Hide, the image not appear, so, i tried to remove the hide block and i could see that the problem is: Show and Hide happens together when ajax is loaded like:
I cliked on button and noting happened like: http://prntscr.com/ars97n
And after few seconds, Ajax load data and show icon and data together: http://prntscr.com/ars9xq
Try $("#carregando").hide(); instead of $(document).ajaxStop(function ()$("#carregando").hide();});
edit: ajaxStart and ajaxEnd are event handlers. I think they should be registered outside of the click function. Something like this:
$(document).ready(function(){
$(document).ajaxStart(function () {
$("#carregando").show();
});
$(document).ajaxStop(function () {
$("#carregando").hide();
});
$("#atualiza").click(function () {
/* all your code here except for the ajaxStart/ajaxStop portion */
});
});
As Karl stated, the best way to do it is without using ajaxStart/ajaxStop event handlers, or even better, without using jQuery at all.
document.querySelector('.get-data').addEventListener('click', function() {
document.querySelector('.display-data').textContent = null;
document.querySelector('.loading').style.display = 'block';
var request = new XMLHttpRequest();
request.open('GET', 'http://jsonplaceholder.typicode.com/photos', true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
var data = JSON.parse(this.response);
document.querySelector('.loading').style.display = 'none';
document.querySelector('.display-data').textContent = JSON.stringify(data[0]);
} else {
// We reached our target server, but it returned an error
document.querySelector('.loading').style.display = 'none';
}
};
request.onerror = function() {
// There was a connection error of some sort
document.querySelector('.loading').style.display = 'none';
};
request.send();
});
<button class="get-data">Get Data</button>
<div class="loading" style="display: none">
<img src="https://upload.wikimedia.org/wikipedia/commons/2/28/InternetSlowdown_Day.gif" width="50px">
</div>
<div class="display-data"></div>
Finally! I found the problem here! All ways I tried before works now, with this modification I did.
Just:
$("#carregando").show();
Or:
$(document).ajaxStart(function () {
$("#carregando").show();
});
$(document).ajaxStop(function () {
$("#carregando").hide();
});
Or:
beforeSend: function() {
$("#carregando").show();
},
complete: function() {
$("#carregando").hide();
},
All my problem were here: http://prntscr.com/asbxbk!!!
So, I commented that async and works!!!
$("#atualiza").click(function () {
$(document).ajaxStart(function () {
$("#carregando").show();
});
$(document).ajaxStop(function () {
$("#carregando").hide();
});
$.ajax({
url: '/Portaria/AtendOperador',
dataType: "json",
type: "GET",
data: { 'data1': data1, 'data2': data2, 'evento': evento, 'cuc': cuc, 'conta': conta },
//async: false, COMMENTED!!!
success: function (data) {
var Categories = new Array();
var Series = new Array();
for (var i in data) {
Categories.push(data[i].Operador);
Series.push(data[i].Fechados);
}
var CategArray = JSON.parse(JSON.stringify(Categories));
atendOperador(CategArray, Series);
},
error: function (xhr) {
alert('error');
}
});
});
Karl's answer is correct if you want to show the same git for all ajax request on the page
But if you want to do it for this particular AJAX the follow this
$("#atualiza").click(function () {
$.ajax({
beforeSend: function() { $("#carregando").show(); }, //It will show the gif just before sending the request
url: '/Portaria/AtendOperador',
dataType: "json",
type: "GET",
data: { 'data1': data1, 'data2': data2, 'evento': evento, 'cuc': cuc, 'conta': conta },
async: false,
cache: false,
delay: 15,
success: function (data) {
var Categories = new Array();
var Series = new Array();
for (var i in data) {
Categories.push(data[i].Operador);
Series.push(data[i].Fechados);
}
var CategArray = JSON.parse(JSON.stringify(Categories));
atendOperador(CategArray, Series);
$("#carregando").hide(); //this will hide the gif in case of AJAX success
},
error: function (xhr) {
alert('error');
$("#carregando").hide(); //this will hide the gif in case of AJAX failure
}
});
});
Hope this will help you
I have two pieces of code, first of all I have my code which toggles open a div with an included close button:
http://jsfiddle.net/spadez/uhEgG/27/
$(document).ready(function () {
$('#country').click(function () {
$("#country_slide").slideToggle();
});
$('#close').click(function (e) {
e.preventDefault();
$('#country_slide').slideToggle();
});
});
Then I also have my Ajax code which is designed to fire when the div has been opened:
$(function () {
$('#country_link').on('click', function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend: function () {
$('.loader').show();
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
// $("#country_slide").hide('fast');
// alert('request failed');
},
complete: function () {
$('.loader').hide();
},
});
return false;
});
});
What I am stuck with now is, how do I make the ajax only execute when the div is being opened? Because I am working with a toggle and close button it seems difficult to work out what the click is doing, whether it is opening it or closing it.
I guess my options are to have some kind of flag or alternatively have some "if" code, so if class is equal to .hidden then do not execute. I haven't been able to integrate either of these solutions and I am unsure if either of them is the proper way to achieve this.
Include the check as part of your slide function:
$("#country_slide").slideToggle(function() {
if ($(this).is(":visible")) {
alert("im visible!");
}
});
Demo: http://jsfiddle.net/tymeJV/uhEgG/28/
if($("#country_slide").is(":visible"))
//call ajax
This code adds data to the element, to check if it's already loaded next time you click on it.
Currently I am not able to test it, so it may contain errors.
$(function () {
$('#country_link').on('click', function (e) {
// Prevent from following the link, if there is some sort of error in
// the code before 'return false' it would still follow the link.
e.preventDefault();
// Get $link because 'this' is something else in the ajax request.
var $link = $(this);
// Exit if the data is loaded already
if ($link.data('loaded') === true)
return false;
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend: function () {
$('.loader').show();
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
// If successful, bind 'loaded' in the data
$link.data('loaded', true)
},
error: function (xhr, textStatus, errorThrown) {
// $("#country_slide").hide('fast');
// alert('request failed');
},
complete: function () {
$('.loader').hide();
},
});
});
});
I got the delay to work when you click on the buttons but I cant get the loading gif to display during the delay.
Thanks
function () {
$('.sectionThreeTab:not(.tabActive)').click(function () {
$('ajax-loader.gif').bind('ajaxStart', function () {
$(this).show();
}).bind('ajaxStop', function () {
$(this).hide();
});
$('.tabActive').removeClass('.tabActive');
$(this).addClass('tabActive');
var lesson = $(this).attr('lesson');
var self = $(this);
setTimeout(function () {
$.ajax({
type: "GET",
url: 'lessons/' + lesson + '.htm',
datatype: "json",
success: function (data) {
$('#sectionTabContent').append(data);
}
})
}, 3000);
return false;
});
}
You can try this instead of what you have:
Delete this part:
$('ajax-loader.gif').bind('ajaxStart', function () {
$(this).show();
}).bind('ajaxStop', function () {
$(this).hide();
});
And change the setTimeout to this:
setTimeout(function () {
$("#loading").show();
$.ajax({
type: "GET",
url: 'lessons/' + lesson + '.htm',
datatype: "json",
success: function (data) {
$('#sectionTabContent').append(data);
},
complete: function() {
$("#loading").hide();
}
})
}, 3000);
Please also post your html so we can see if everything else is in order.
Edit:
<div id="loading" class="grayBackground withBorder10" style="display:none">
<img alt="Loading..." src="img/ajax-loader.gif" />
</div>
I believe your targeting the loading image incorrectly, try:
$('#ajaxLoader').bind('ajaxStart', function () {
$(this).show();
}).bind('ajaxStop', function () {
$(this).hide();
});
Where your loading image has an Id #ajaxLoader (replace to suit your HTML).