Block ajax script execution before the previous call succeeded - php

I have a button that executes an ajax function.
Sometimes the server lags so maybe an user presses it more times, thinking the first time it didn't work...
The main ajax function looks like this:
$.ajax({
type: "POST",
url: "page.php",
dataType: "html",
data:"data=data",
success: function(){
ajax2();
ajax3();
}
});
Since that ajax function updates db and makes others 2 ajax functions i need to block the button from remake the main ajax func...
Only when ajax2() and ajax3() are finished, the button, if pressed, must remake the ajax function.
Hope to have explained well my problem!

disable the button and then reenable it when the 2 ajax are finished
/// the click event
$('yourbutton').prop("disabled",true);
/// show a loading or something....
$.ajax({
type: "POST",
url: "page.php",
dataType: "html",
data:"data=data",
success: function(){
var ajax1 = ajax2();
var ajax2 = ajax3();
$.when(ajax1,ajax2).done(function(risp1,risp2){
console.log(risp1,risp2);
$('yourbutton').prop("disabled",false);
/// hide the loading
});
}
});
read this for more info

Try this
//before this ajax call disable button
$.ajax({
type: "POST",
url: "page.php",
dataType: "html",
data: "data=data",
success: makeAjaxCalls
});
function makeAjaxCalls() {
var a1 = ajax2();
var a2 = ajax3();
$.when(a1, a2).done(function () {
//enable your button here
});
}

Unbind the event listener when it's activated the first time :
custom_ajax_handler = function(){
$('#mybutton').unbind('click'); //won't intercept event from now on.
//here is your ajax call.
ajax2();
ajax3();
}
$('#mybutton').click(custom_ajax_handler);
Then in ajax3 success rebind it :
success : function(){
$('#mybutton').click(custom_ajax_handler);
}
Note that you probably shouldn't make that much ajax calls.
Or at least that doing so won't help your server with its lags.

Related

Prevent AJAX calls from firing twice everytime

I am building a web application using JQuery 3.3.1. It would seem that everytime I make ajax call, the request is sent twice. I can tell because I tried logging the requests on server side. I tried solutions from similar questions but they do not seem to help.
I separated the ajax call from click events, so it does not happen because of click event being registered twice.
$(function() {
console.log("hi");
var request = {};
request["user_id"] = 1;
request["date"] = new Date();
request["assignments"] = [{
"point_count" : 1,
"skill_mnemo" : "SKILL_FARM"
}];
$.ajax({
type: "POST",
dataType: "json",
mimeType: "application/json",
url: "./api/update_skill_point.php",
enctype: 'multipart/form-data',
data: request,
async: false,
cache: false,
success: function(result) {
console.log(result);
}
});
});
You have to debug this code by the following ways:
Check how many times hii is printing into console.
Add break point at start of $.ajax. Then check the call stack.
Check into network tab and analyse the call stack at initiator column for the corresponding ajax call.(for Chrome)
Hope it will help for you.
There is a chance that the submit button in your form is NOT set to type="button".
So, on-clicking the button, your ajax function runs and the browser also attempts to submit the form (default behavior of submit buttons) to your current URL. This might give the appearance that ajax is being called twice.
don't use
(function(){})
if we use (function(){}), it will call itself when DOM is getting ready and then again when required.
Try
function ajaxCall()
{
console.log("hi");
var request = {};
request["user_id"] = 1;
request["date"] = new Date();
request["assignments"] = [{
"point_count" : 1,
"skill_mnemo" : "SKILL_FARM"
}];
$.ajax({
type: "POST",
dataType: "json",
mimeType: "application/json",
url: "./api/update_skill_point.php",
enctype: 'multipart/form-data',
data: request,
async: false,
cache: false,
success: function(result) {
console.log(result);
}
});
}
$(document).ready(){
ajaxCall();
}
In this way you can control your ajax call,
Now you might have some idea how to deal, if not let me know, I'll try to explain more.

Ajax submit not working

I'll make it easy, I want to submit data without using a form, etc, etc, etc...
I have this code:
HTML
<span class="categ-edit">Edit</span>
<span class="categ-add">Add</span>
<span class="categ-delete">Delete</span>
JQUERY
$('.categ-edit').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'edit'},
});
window.location.href = "categoryactions.php";
});
$('.categ-add').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'add'},
});
window.location.href = "categoryactions.php";
});
$('.categ-delete').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'delete'},
});
window.location.href = "categoryactions.php";
});
And in categoryactions.php I have this:
PHP
<?php
$action = $_POST['action'];
echo $action;
?>
But when it redirects me to categoryactions.php I get nothing. I'm not sure if that's the way to submit data with AJAX but at least I tried. If someone knows how to fix this, I'll be grateful!
You click handler is making two separate requests. First, you are sending a request with AJAX, then you are going to the page. When you look at the page, you won't see the result because the result was given to the AJAX request.
The point of AJAX is to avoid changing the page.
Try this:
$('.categ-edit').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'edit'},
success: function(data) {
alert(data);
}
});
});
You are actually calling "categoryactions.php" twice. First as an asynchronous call (ajax) and the second time as a redirect: window.location.href = "categoryactions.php";
In the 2nd call, nothing is being posted so your output is empty. This line does not serve any purpose - you should remove it.
The ajax call happens in the background so you won't see the output from the echo in the browser. if you really want to verify it is working, replace the echo with a file call to write it to a file. Then check the file contents.
Using redirection with Ajax doesn't make sense. You need to use the success method.
$('.categ-delete').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'delete'},
success: function(data){
alert(data);
//or, put response in a div
$('#someDivId').html(data);
}
});
});
The point of Ajax is to retrieve the response from a request to another page without changing the URL in the address bar. It retrieves the response for you in the variable that is the input to your success method, and then you do something with that.
Example AJAX with PHP
I can't exactly answer your question, but I will help you understand ajax requests to http server and how to handle responses accordingly.
Sample jQuery
$('.categ-edit').click(function() {
$.get('/path/to/file.php', function(data) {
console.log(data);
});
});
Sample file.php
<?php
echo json_encode('HELLO');

How to prevent multiple loading PHP script calling JS script?

I created a simple voting system (+ and -) on Ajax for users comments. One page have 50 posted comments and you can vote for each "plus" or "minus". This data sent through the PHP script to the database. However, if a user votes, the PHP script is called 50 times - it is visible in Chrome developer tool. There are errors - more value than expected. Here is my code (two DIV buttons and the script).
Tell me please how to change the code to the script (up_vote.php or down_vote.php) is called only once.
<script type="text/javascript" src="raitings/jquery.js"></script>
<script type="text/javascript">$(function() {$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='down')
{
$(this).fadeIn(200).html('<img src="raitings/dot.gif" align="absmiddle">');
$.ajax({type: "POST", url: "raitings/down_vote.php", data: dataString, dataType : "html", cache: false, success: function(html)
{ parent.html(html);}
});
}
else
{
$(this).fadeIn(200).html('<img src="raitings/dot.gif" align="absmiddle">');
$.ajax({type: "POST", url: "raitings/up_vote.php", data: dataString, dataType : "html", cache: false, success: function(html)
{ parent.html(html);
} });
}
return false;
});
});
</script>
//php code below;
echo "<div class=\"box1\"><div class=\"up\">".$up."</div>"
."<div class=\"down\">".$down."</div></div>\n";
Using jQuery, it's important to know that events are stackable, even if the event is exactly the same. For example:
$(".vote").click(function() { alert("hi"); });
$(".vote").click(function() { alert("hi"); });
$(".vote").click(function() { alert("hi"); });
If we ran these three lines verbatim, we'll have 3 different events attached. That is, we would get 3 alerts one after the other by clicking in an element with the vote class.
In addition, oftentimes it happens that pages being loaded through ajax carry the same <script></script> block of the parent page, and when this is the case, the code is inadvertently being processed again and again with every ajax call.
While I was not able to pinpoint exactly how is this happening by the code you provided, it seems this is the most likely scenario: your click handler event is being loaded several times, and as a result one click triggers several ajax calls.
The quick and dirty solution when this presents as I mentioned in the comments is replacing:
$(".vote").click(function()
By:
$(".vote").unbind("click").click(function()
Which thanks to the unbind function forces it to discard previously attached events every time a new one is attached, thus preventing it from having more than one event attached no matter how many times the code is processed.
While this will work, the better solution is, of course, to locate where is the js code being loaded multiple times and make sure it is loaded just once.
$(".vote").each(function () { $(this).click( clickHandler .... etc should solve your problem.
I don't fully understand how your version works but I would do it similar to this:
+
-
Where 200 would be the unique id of the comment.
Then have a vote_up() and vote_down() function defined in a JavaScript and add your ajax requests there.
That way it should not call the script more than once when +/- button is clicked.
You can disabled button before send you ajax request.
// Sample:
$(function() {
$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
parent.fadeIn(200).html('<img src="raitings/dot.gif" align="absmiddle">');
if(name=='down')
{
$.ajax({
type: "POST",
url: "raitings/down_vote.php",
data: dataString,
dataType : "html",
cache: false,
beforeSend: function() {
parent.attr("disabled", true);
},
success: function(html) {
parent.html(html);
}
});
} else {
$.ajax({
type: "POST",
url: "raitings/up_vote.php",
data: dataString,
dataType : "html",
cache: false,
beforeSend: function() {
parent.attr("disabled", true);
},
success: function(html) {
parent.html(html);
}
});
}
return false;
});
});

How to show Loading message instantly while using jquery ajax?

Below is my Ajax code I have made using jQuery Ajax method.
$(".loading_msg").show();
$.ajax({
type: "POST",
url: "submit_ops.php?action=submit_form",
data: $( "#frmMyForm" ).serialize(),
success: function(result){
if(result=='Success'){
$("#msgContainer").html('<div style="color:#3CA322;font-weight:bold;font-size:14px;padding:10px;">Thank you.</div>');
$("#msgContainer").fadeIn();
}
else{
$("#msgContainer").html('<div style="color:red;font-size:12px;padding:10px;">' + result + '</div>');
$("#msgContainer").fadeIn();
}
},
error: function(){
//console.log('error');
},
complete: function(){
//console.log('complete');
$(".loading_msg").hide();
$("#submit").attr("disabled", false);
}
});
So the logic is, whenever the Ajax request is about to made,
the .login_msg container is displayed first
then ajax call made
and when it is completed, again the .loading_msg is hidden.
Now the problem, it is not working smoothly as it should be. So when the ajax call is made, the browser hangs for a seconds but it doesn't show the loading message. But when the request is completed, the login message appears like for half a second and then it goes away as I have set it hidden on request completion.
So I want that the .login_msg should be shown before the request is made.
Any suggestions for this? Thanks in advance.
try using beforeSend and complete settings of $.ajax:
$.ajax({
type: "POST",
url: "submit_ops.php?action=submit_form",
data: $( "#frmMyForm" ).serialize(),
beforeSend:function(){
$(".loading_msg").show();
}
complete:function(){
$(".loading_msg").hide();
}
....
....
});

Calling AJAX from jQuery and displaying a waiting message

I'm very new at AJAX calls from jQuery and I'm a bit stuck trying do to this; I have an AJAX call from jQuery like this:
$(document).ready(function() {
$('tr.table-row').click(function(){
$.ajax({ url: 'stats-render.php', data: {ref: $(this).attr('id')}, type: 'post', success: function(d) {//the_output_here}});
});
});
This script is inside a web page triggered when the user hits a particular row (<tr></tr>) from a table. stats-render.php outputs HTML text with some info and graphics. This answer some times takes a while (15 seconds), so I would like to show the user a waiting message when he/she triggers the script and when the call returns an answer show the output text in a div (lets call it <div id="render-div">).
So the questions are, how can I show a waiting message? If you know a good script for showing this in a modal, I would appreciate it.
How can I output the result from stats-render.php into a div?. Thank you so munch for any help!
Just display a loading message in the div where the results go in the interim.
$(document).ready(function() {
$('tr.table-row').click(function(){
$.ajax({ url: 'stats-render.php', data: {ref: $(this).attr('id')}, type: 'post', success: function(d) { $('div.for-results').html( /* d... */ ); });
$('div.for-results').html('loading...');
});
});
Or for even more fun:
$(document).ready(function() {
$('tr.table-row').click(function(){
$.ajax({ url: 'stats-render.php', data: {ref: $(this).attr('id')}, type: 'post', success: function(d) {
clearInterval(loading);
$('div.for-results').html( /* d... */ );
});
$('div.for-results').html('loading');
var loading = setInterval(function() { $('div.for-results')[0].innerHTML += '.' }, 1000);
});
});
The easiest option is probably to check out the jquery-loading plugin.
I just do a simple show the message before the call, and hide it on the success callback like this:
However I think jquery might have a callback option when the ajax call starts, and when it stops.
$(document).ready(function() {
$('tr.table-row').click(function(){
//Show the loading message, or chage a css class, or what have you.
$('#loadingmessagetext').show();
$.ajax({ url: 'stats-render.php', data: {ref: $(this).attr('id')}, type: 'post', success: function(d) {
//Hide the loading message
$('#loadingmessagetext').hide();
//the_output_here
}
});
});
});

Categories