Disable javascript function on successful ajax request - javascript

To be specific, I want to disable a function from executing on successful ajax request. I do not know whether that's possible or if any workaround is there. Have a look at what I do:
<script>
$(document).ready(function() {
function load(){
...
...
}
});
$.ajax({
...
success: function(option){
disable load function // I want this functionality somehow
}
});
</script>
Can someone help? I need this because load function is a scrolling function which loads products on scrolling to end & on ajax request another file uses the same, so somehow I need this function disabled. Any help will be appreciated.
EDIT
I want this function working on first time page load but with a successful ajax request I want this function be stopped. I'm putting the whole code for you to get the clear idea.
<script>
$(document).ready(function() {
var track_load = 0;
var loading = false;
var total_groups = <?php echo $total_groups; ?>;
var cat_id= <?php echo $cat_id; ?>;
$('.autoload').load("xyz.php", {'group_no':track_load, 'cat_id':cat_id}, function() {track_load++;});
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height())
{
if(track_load <= total_groups && loading==false)
{
loading = true; //prevent further ajax loading
$('.animation_image').show();
$.post('xyz.php',{'group_no': track_load, 'cat_id':cat_id}, function(data){
$(".autoload").append(data);
$('.animation_image').hide();
track_load++;
loading = false;
}).fail(function(xhr, ajaxOptions, thrownError) {
$('.animation_image').hide();
loading = false;
});
}
}
});
});
</script>
<script>
$(document).ready(function(){
$('#subcat').change(function(){
var val=$(this).val();
$(this).value= val;
$('#furcat').show();
if(val=='A'){
$('#furcat').html("<option selected='true' disabled='disabled'>Choose Further Category</option><option>B</option><option>C</option>");
var sub_cat=41;
}
$('.autoload').empty();
$('.animation_image').show();
$.ajax({
type: "POST",
url: "abc.php",
data: {sub_cat:sub_cat},
success: function(option){
$('.autoload').replaceWith(option);
$('.animation_image').hide();
}
});
});
});
</script>
And as I need the same scrolling function in upcoming data, I'm involving another php file which uses the same code as this & to remove double ajax request I need to disable this function.

You can create flag which you can set to 'true' on Document Ready and then set it to 'false' after successful ajax call.
<script>
var flag=true;
$(document).ready(function() {
flag = true;
function load(){
if(flag){
...
...
}
}
});
$.ajax({
...
success: function(option){
flag=false;
}
});
</script>

you can simply add the logic of flag variable. which will make sure that your load method will not execute after ajax success.
<script>
$(document).ready(function() {
var flag=false;
function load(){
if(!flag){
...
...
}
}
});
$.ajax({
...
success: function(option){
flag=true;
}
});
</script>
hope this helps you

You don't need any if-statements and additional variables.
Look at this code:
var load = function () {
...
};
$( document ).ready(function() {
$.ajax({
...
success: function () {
//"delete" the `load` function
load = '';
}
});
});
The load function is stored into a variable and when the ajax request was successful, that variable is cleared.

Related

javascript wait until data is loaded

I have the following function
<script src='jquery-3.1.1.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
function loaddata() {
var div = $('#div');
$.get('load_data.php', function(data) {
div.html(data);
$('body, html').scrollTop(div[0].scrollHeight);
});
}
loaddata();
setInterval(loaddata, 1000);
});
window.addEventListener('scroll', function(){
if(($(window).scrollTop() < 1) )
{
$.ajax({url: 'load_extra_data.php,
cache: false,
success: function(html){ $('#div').prepend(html);
$(document).scrollTop(position);
}})
}
})
</script>
the problem is related to the function
window.addEventListener('scroll', function(){
The function load_extra_data.php provides the data that has to be added to the div.
I need to wait until the data from load_extra_data.php is fetched before scrolling a second time.
How can the problem be solved ?
Keep a flag to tell you whether you have data loading, and don't ask for more data while the flag is set. Roughly:
var loading = false; // The flag, initially false
window.addEventListener('scroll', function(){
if (!loading && $(window).scrollTop() < 1) {
// ^^^^^^^^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− Checking the flag
loading = true; // Setting the flag
$.ajax({
url: 'load_extra_data.php',
cache: false,
success: function(html){
$('#div').prepend(html);
$(document).scrollTop(position);
},
complete: function() { // Clearing the flag when
loading = false; // the request ends (whether
} // it succeeds or fails)
});
}
});
(I've only used ES5 and earlier features in that, since your code didn't show signs having ES2015+ items in it. But in 2020, I'd certainly be writing to ES2015+ and transpiling if I really had to support obsolete environments that didn't support it.)
You could use the callback function .done() of $.ajax(). Which will be executed after the data has loaded.
$.ajax({url: 'load_extra_data.php',
cache: false,
success: function(html){ $('#div').prepend(html);
$(document).scrollTop(position);
}}).done(function() {
// Executed after $.ajax fetch is done
})

How to respect client side validation when making an ajax call

I wanted to make an ajax call, and then wait for the response from ajax call (Stop form submission till then) and then post the form based on the ajax response that I get. This question is based on Make ajax call and then submit form. So, after putting below script, everything works fine, but I lose the client side validation. Can I make an ajax call and still respect the Client Side validation?
#section scripts {
<script>
var canSubmit = false;
$('form').submit(function (e) {
if (!canSubmit) {
e.preventDefault();
var data = $('form').serialize();
var url = $(this).data('url');
$.ajax({
url: url,
type: 'POST',
data: data,
success: function (response) {
if (response.hasPreviousRequest) {
if (confirm("You've already applied for this job. Apply again?")) {
canSubmit = true;
$('form').submit();
}
}
else {
canSubmit = true;
$('form').submit();
}
},
error: function () {
alert("error");
}
});
}
});
</script>
}
P.S: Kindly note that as soon I as remove the ajax call Client side validation starts working fine. Can some one please explain me this behaviour?
You need to call the .valid() method on the form element (and if not, then cancel the ajax call)
$('form').submit(function (e) {
if (!$(this).valid()) {
return // exit
}
if (!canSubmit) {
....

How to press a button after successful Ajax?

When Ajax call is successful, user gets redirected to main page:
$('#button_1').on('click', function () {
//code
$.ajax({
method: "POST",
url: "/somewhere",
data: {
//code
}
}).done(function () {
location.href = "/";
});
});
After getting redirected, I want to automatically click another button, which opens a modal. I tried inside done function different methods:
.done(function () {
location.href = "/";
$('#button_2').click(); // doesn't work
});
.done(function () {
location.href = "/";
setTimeout(function ()
$('#button_2').click(); // doesn't execute
}, 2000);
});
.done(function () {
location.href = "/";
$(document).ready( function () {
// executes but user is immediately redirected to main page
$('#button_2').click();
});
});
I also tried outside Ajax, in the function that Ajax call is in, but had the same results.
How can I click the button programmatically after the Ajax call?
You need to add that logic in the target (main) page.
Once you redirect, the current page is not longer the active one and all logic is removed.
You could add some parameter to the URL in order to know when you are there due to redirection, something like:
location.href="/?redirect=1"
and then check that parameter
The lines of code next to
location.href = "/";
will not be executed because the browser is navigating to another page.
So you should put your logic in the / page (#button_2 should be in that page).
You're currently trying to execute code after a redirect which isn't possible directly because the code after location.href = "/" will never be reached. Once you redirect you've have a fresh page with a clear state.
Your current function can still look like this:
$('#button_1').on('click', function () {
$.ajax({
method: "POST",
url: "/somewhere",
data: {
//code
}
}).done(function () {
location.href = "/?modal-open=1";
});
});
As you can see I've added a query parameter to the redirect so we know we were redirected with the intention to open the modal.
For your Root Page (/) you will need a script like this:
$(document).ready( function () {
// check the URL for the modal-open parameter we've just added.
if(location.search.indexOf('modal-open=1')>=0) {
$('#button_2').click();
}
});
This will check if the parameter is in the URL and trigger the click.
First of all when you redirect a new page you can not access DOM because the page is reloaded. You can send a parameter for do that.
$(document).ready( function () {
//after page load
var isButtonActive = findGetParameter("isButtonActive");
if(isButtonActive){
alert("button_2 activated");
$('#button_2').click();
}
$('#button_1').on('click', function () {
//code
$.ajax({
method: "POST",
url: "/somewhere",
data: {
//code
}
}).done(function () {
alert("page will be reload. button_2 wil be activated");
location.href = "/?isButtonActive=true";
});
});
$('#button_2').on('click', function () {
alert("button_2 clicked");
});
});
function findGetParameter(parameterName) {
var result = null,
tmp = [];
location.search
.substr(1)
.split("&")
.forEach(function (item) {
tmp = item.split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
});
return result;
}
Thank you for your answers. I researched a bit more and found another way to do it:
$('#button_1').on('click', function () {
sessionStorage.setItem("reload", "true");
//code
$.ajax({
method: "POST",
url: "/somewhere",
data: {
//code
}
}).done(function () {
location.reload();
});
});
And in main page:
$(document).ready(function () {
var reload = sessionStorage.getItem("reload");
if (reload == "true") {
$("#button_2").click();
sessionStorage.setItem("reload", false);
}
});

Posting a php variable from one page to another using javascript

I'm trying to send a a php variable to another page using JS. My hopeless attempt so far:
header.php:
<script>
var county = "<?php echo $county; ?>";
$.post("ajax.php",county);
</script>
ajax.php:
<?php
$county = $_POST['county'];
echo $county;
?>
For context, I'm attempting to refine an infinite scroll script (http://www.inserthtml.com/2013/01/scroll-pagination/).
I am currently using this script and want to add to it:
(function($) {
$.fn.scrollPagination = function(options) {
var settings = {
nop : 10, // The number of posts per scroll to be loaded
offset : 0, // Initial offset, begins at 0 in this case
error : 'No More Posts!', // When the user reaches the end this is the message that is
// displayed. You can change this if you want.
delay : 500, // When you scroll down the posts will load after a delayed amount of time.
// This is mainly for usability concerns. You can alter this as you see fit
scroll : true // The main bit, if set to false posts will not load as the user scrolls.
// but will still load if the user clicks.
}
// Extend the options so they work with the plugin
if(options) {
$.extend(settings, options);
}
// For each so that we keep chainability.
return this.each(function() {
// Some variables
$this = $(this);
$settings = settings;
var offset = $settings.offset;
var busy = false; // Checks if the scroll action is happening
// so we don't run it multiple times
// Custom messages based on settings
if($settings.scroll == true) $initmessage = '';
else $initmessage = 'Click for more';
// Append custom messages and extra UI
$this.append('<div class="content"></div><div class="loading-bar">'+$initmessage+'</div>');
function getData() {
// Post data to ajax.php
$.post('ajax.php', {
action : 'scrollpagination',
number : $settings.nop,
offset : offset,
}, function(data) {
// Change loading bar content (it may have been altered)
$this.find('.loading-bar').html($initmessage);
// If there is no data returned, there are no more posts to be shown. Show error
if(data == "") {
$this.find('.loading-bar').html($settings.error);
}
else {
// Offset increases
offset = offset+$settings.nop;
// Append the data to the content div
$this.find('.content').append(data);
// No longer busy!
busy = false;
}
});
}
getData(); // Run function initially
// If scrolling is enabled
if($settings.scroll == true) {
// .. and the user is scrolling
$(window).scroll(function() {
// Check the user is at the bottom of the element
if($(window).scrollTop() + $(window).height() > $this.height() && !busy) {
// Now we are working, so busy is true
busy = true;
// Tell the user we're loading posts
$this.find('.loading-bar').html('Loading images');
// Run the function to fetch the data inside a delay
// This is useful if you have content in a footer you
// want the user to see.
setTimeout(function() {
getData();
}, $settings.delay);
}
});
}
// Also content can be loaded by clicking the loading bar/
$this.find('.loading-bar').click(function() {
if(busy == false) {
busy = true;
getData();
}
});
});
}
})(jQuery);
var county = "<?php echo $county; ?>";
$.ajax({
type: "POST",
url: "ajax.php",
data: {county:county},
success: function (data)
{
alert(data);
}
});
UPDATE:
It is now working. Thanks for your help.
Try this:
$.post("ajax.php", { county: county }, function(result){
console.log(result); // response, if any
});
var county = "<?php echo $county; ?>";
$.ajax({
type: "POST",
url: "ajax.php",
data: {county:county},
success: function (data)
{
alert(data);
}
});
Please use this code it will work
Please give some detail what you exactly want to do
or the easiest way you can use ajax jQuery for plugin
$('#myForm').ajaxForm(function(response){
//Print response
$('#ResultDiv').html(response);
});

Hide loading bar on no .HTML file found

I have the code below to find the next sequential page number and load it at the bottom of the page once the user hits the bottom of the screen.
the loading div slides down and as it is loading and up once it is done... it is set to "display:none" by default
What i need is a line of code in there which basically hides the #loading div if no more pages can be found to load... " var url = "page"+nextpage+".html";" finds the new page... titled 'page 2.html, page3.html' and so on.
Any help would be appreciated. I'm assuming it is easy but I can't find a solution anywhere...
alreadyloading = false;
nextpage = 2;
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
if (alreadyloading == false) {
$("#loading").slideDown();
var url = "page"+nextpage+".html";
alreadyloading = true;
$.post(url, function(data) {
$('#newcontent').children().last().after(data);
alreadyloading = false;
nextpage++;
$("#loading").slideUp();
});
}
}
});
If there is no such file then the AJAX request will fail, so you can do what you need from inside a "failure" handler. To be able to specify that, you one solution is to move from using $.post to using the more configurable $.ajax, which gives you all the necessary options:
$.ajax({
type: 'POST',
url: url,
success: function(data) {
$('#newcontent').children().last().after(data);
nextpage++;
},
complete: function() {
alreadyloading = false;
$("#loading").slideUp();
}
});
The complete callback contains code which will be executed no matter what happens with the request; the success callback will be executed before complete, but only if the request was successful.

Categories

Resources