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();
},
});
});
});
Related
I have a problem with bootbox.js modals. I wanted to use bootbox.dialog for pausing UI while Ajax is being executed and waiting for response. Everything works cool if I use dialog.modal('hide'); inside bootbox.alert with confirm (after clicking OK it hides dialog.modal), but I'd not like to confirm it every time. When I'm using dialog.modal('hide'); outside the bootbox.alert with confirm it doesn't hide dialog.modal... Where is the problem? Working code (hiding modal) is inside success and not working is inside error
var dialog = bootbox.dialog({
message: '<p class="text-center mb-0"><i class="fa fa-spin fa-cog"></i> Please wait while we do something...</p>',
closeButton: false
});
var checkboxId = "#" + $(this).attr('id');
var checked = $(this).is(":checked");
if (checked) {
$.ajax({
url: url,
type: "POST",
data: { estimatedCostId: #Model.EstimatedCostID },
success: function (data) {
if (!data.Success)
{
bootbox.alert(data.ErrorMessage, function () {
dialog.modal('hide');
});
$(checkboxId).prop('checked', !checked);
}
},
error: function (request, status, error) {
dialog.modal('hide');
bootbox.alert("Błąd serwera");
$(checkboxId).prop('checked', !checked);
}
});
}
Most likely, this is a timing issue. If your AJAX call is "too quick", the success/fail callbacks are being called before the bootbox.dialog function has resolved. So, this:
dialog.modal('hide');
winds up being called on an undefined object. I was running into a similar issue on a recent project, and solved it by putting the AJAX call into the shown.bs.modal event, like so:
var checkboxId = "#" + $(this).attr('id');
var checked = $(this).is(":checked");
var dialog = bootbox.dialog({
message: '<p class="text-center mb-0"><i class="fa fa-spin fa-cog"></i> Please wait while we do something...</p>',
closeButton: false
})
// this is the change
.on('shown.bs.modal', function(){
if (checked) {
$.ajax({
url: url,
type: "POST",
data: { estimatedCostId: #Model.EstimatedCostID },
success: function (data) {
if (!data.Success)
{
bootbox.alert(data.ErrorMessage, function () {
dialog.modal('hide');
});
$(checkboxId).prop('checked', !checked);
}
},
error: function (request, status, error) {
dialog.modal('hide');
bootbox.alert("Błąd serwera");
$(checkboxId).prop('checked', !checked);
}
});
}
});
You can use this also in a simple way
bootbox.hideAll();
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.
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.
I'm loading a from a server using ajax, but when I try to submit it, it is never submitted.. Here is the code:
$(document).ready(function() {
function successHandler (result) {
}
function errorHandler (error) {
}
$.ajax({url: "http://www.****.com/new",
dataType: 'html',
beforeSend: function() {
},
complete: function() {
},
success: function (result) {
$('#app-status-ul').hide();
ajax.parseJSONP(result);
},
error: function (request,error) {
alert('Network error has occurred please try again!');
}
});
var ajax = {
parseJSONP:function(data){
$('#movie-data').append(data);
$('#movie-data').listview('refresh');
var newTheme = 'b';
}
}
//HERE I TRY TO SUBMIT THE LOADED FORM
$("form").on('submit', function() {
alert( "Form submitted" );
});
});
As you can guess I expect an alert('Form submited') after submit it.
You have to use Jquery function submit() (http://api.jquery.com/submit/):
$("form").submit();
I am new to jquery and coding in general. This is what I am trying to do:
When a link is clicked, expand the #country_slide div
Show "loading" text
If ajax is successful, put the contents of an html file into the div
Otherwise alert an error and close the div
This is the code I now have:
http://jsfiddle.net/spadez/n9nVs/5/
window.onload = function () {
var a = document.getElementById("country_link");
a.onclick = function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend : function() {
$("#country_slide").show();
$("#country_slide").val('<p>Loading</p>')
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
$("#country_slide").hide();
},
complete : function() {
$('.loader').hide();
},
});
return false;
}
}
When the link is clicked, I never see the loading text in the box. Please can someone tell me where I have gone wrong here? Also if anyone can offer any words of advice about my first jquery script I would really appreciate it.
Your anchor's id is country, not country_link. So:
var a = document.getElementById("country");
or just use jQuery's id selector:
var a = $("#country");
or even better directly chain:
$(function() {
$('#country').click(function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend : function() {
$("#country_slide").show();
$("#country_slide").html('<p>Loading</p>')
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
$("#country_slide").hide();
},
complete : function() {
$('.loader').hide();
},
});
return false;
}
});
Notice that I have used the $(document).ready function instead of window.onload. Also I have replaced the onclick event subscription with jQuery's click function. If you are using jQuery it would be better to take full advantage of it.
Working jsFiddle Demo
You don't have any country_link element in your page.
Instead of using window.onload you can use DOM ready.
Attach click handler by jQuery with .on() method.
The .val() method is for <input />. For other elements, use .html() instead.
// DOM ready instead of window.onload
$(function () {
// attach click handler by jQuery instead of onclick
$('#country').on('click', function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend : function() {
$("#country_slide").show();
// val() method is for <input />
// use html() instead
$("#country_slide").html('<p>Loading</p>')
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
$("#country_slide").hide();
},
complete : function() {
$('.loader').hide();
},
});
return false;
});
});
References:
.html() - jQuery API Documentation
.on() - jQuery API Documentation
.val() - jQuery API Documentation
jQuery( callback ) - jQuery API Documentation
On the fiddle you have
<a href="#" id="country">
Where it should be:
<a href="#" id="country_link">
or change the JS to be
var a = document.getElementById("country");
Because there is no element with an ID country_link
document.getElementById() returns null if the element isn't found
document.getElementById('country').onclick = ...; //should work
In JavaScript, null is a special primitive and you cannot add properties to primitive types.
You have to add an element with id=country_link and the this code will work as NOX said. I have tried that in jsfiddle. try it using
$("#country").click(function(){
// your code goes here
})
that will works.
document.getElementById("country_link"); shall be replaced by document.getElementById("country"); as "country_link" is not the id of any <a> tag in the mark up.
If you are using jQuery library you may handle event like-
$(document).on("click","a",function(){
//ajax stuff
});
Updated Your jsfiddle Code. Just check. its going to failure method. In your workspace you should have the test.html returning the actual data. Thanks.
Don't use plain JS if you already have jQuery (it will be easier for you):
;$(document).ready(function(){
$(country_link).click(function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend : function() {
$(country_slide).show();
$(country_slide).val('<p>Loading</p>');
},
success: function (data, textStatus) {
$(country_slide).html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
$(country_slide).hide();
},
complete : function() {
$('.loader').hide();
},
});
return false;
});
});