I have a few buttons on one page in which I need different ajax calls for. In Chrome, this is working perfectly, but in Firefox, it seems that it's always pulling that first ajax call in the file, no matter what button is pressed. The main difference between the two calls is the action. Do I need to fix my code in order for Firefox to recognize the different calls/actions?
(function ($) {
$(document).ready(function() {
$(document).on('click', '.js-filter-item > a', function(e){
e.preventDefault();
var profCategory = $(this).data('category')
$.ajax({
url: wpProfAjax.ajaxProfUrl,
data: { action: 'profFilter', profCategory: profCategory },
type: 'post',
success: function(result) {
$("#professionals-container").hide().html(result).fadeIn(1000);
$(".misha_loadmore").hide();
},
error: function(result) {
console.warn(result);
}
});
});
$('div.sidebar-filter form').find('button').click(function(e){
e.preventDefault();
var title = $('#title').val();
$.ajax({
url: wpProfAjax.ajaxProfUrl,
data: { action: 'lnFilter', title: title },
type: 'post',
success: function(result) {
var profs = $(result).find('.professionals-column');
if(profs.length < 9){
$('.misha_loadmore').css('display', 'none');
$('#page').val('1');
}
else{
$('.misha_loadmore').css('display', 'block');
}
$("#professionals-container").hide().html(result).fadeIn(1000);
},
error: function(result) {
console.warn(result);
}
});
});
Related
I am new to Ajax. I am currently submitting a form into my database using jQuery AJAX but it sends the same data multiple times in my database.
Here's my Ajax code :
$(document).ready(function () {
var id_js;
$(document).on('click', '.btn-success', function () {
id_js = $('#ID_TXT').val();
$('form').submit(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
$.ajax({
type: "POST",
url: 'server.php',
data: {
'Mark': 1,
'id': id_js,
},
success: function (response) {
$('#result').html(response);
}
});
return false;
});
});
});
Also I have tried .one() and .stopImmediatePropogation() but still no results
I see both form submit and Ajax call are doing the same work. If you are going to post the data only with AJAX call then form submit is not required.
I hope this works well for you.
$(document).ready(function () {
function postDataToServer() {
var id_js = $('#ID_TXT').val();
$.ajax({
type: "POST",
url: 'server.php',
data: {
'Mark': 1,
'id': id_js,
},
success: function (response) {
$('#result').html(response);
}
});
}
$(document).on('click', '.btn-success', postDataToServer);
});
The submit handler shouldn't be inside the click handler. Every time you click on the button, it adds another submit handler. So when you finally submit the form, it will submit it as many times as you clicked on the button.
If you want to ensure that the form isn't submitted until you've clicked on the button, add a test in the submit handler.
$(document).ready(function() {
var id_js;
$(document).on('click', '.btn-success', function() {
id_js = $('#ID_TXT').val();
});
$('form').submit(function(e) {
if (id_js !== undefined) {
$.ajax({
type: "POST",
url: 'server.php',
data: {
'Mark': 1,
'id': id_js,
},
success: function(response) {
$('#result').html(response);
}
});
} else {
alert("You need to click on the success button first");
}
return false;
});
});
I am in shopify and trying to Ajax a filter. I have a dropdown and the dropdown onchange should use Ajax to replace the contents of a bunch of products in the #collection div.
My onchange can't find my update products function. What is wrong with my syntax?
<script>
$(function() {
var popped = ('state' in window.history && window.history.state !== null),
initialURL = location.href;
//function to handle the scenarios where back and forward buttons used in browser
$(window).bind("popstate", function(e) {
// Ignore inital popstate that some browsers fire on page load
var initialPop = !popped && location.href == initialURL;
popped = true;
if (initialPop) {
return;
}
ajaxLoadPage(location.href);
});
//the ajax function that does the AJAX calls to get the products and load them into the grid
var ajaxLoadPage = function(url) {
$.ajax({
type: 'GET',
url: url,
data: {},
complete: function(data) {
$('#collection').html($("#collection", data.responseText).html());
history.pushState({
page: url
}, url, url);
}
});
}
}
function update_flavors(ajax_page) {
$.ajax({
type: "GET",
url: ajax_page + "?view=flavors-field",
success: function(html) {
$("#collection").html(html);
}
});
}
function update_products(ajax_page) {
$.ajax({
type: "GET",
url: ajax_page + "?view=products",
data: {},
success: function(html) {
$("#collection").html(html);
history.pushState({
page: ajax_page
}, "", ajax_page);
}
});
}
</script>
I have dilaog box which loads data in success function of an ajax call as follows.
$.ajax({
url: '#Url.Action("GetPolicyPremiumAllocation", "Policy")',
data: { policyID: selPolicyId },
type: 'POST',
success: function (data) {
if (data.length > 0) {
alert(data);
document.getElementById("modal_dialog").innerHTML = "";
// $("#modal_dialog").empty();
$("#modal_dialog").load(data,function( ) {
$("#close-button-id").on("click", CloseDialog);
});
$("#modal_dialog").dialog("open");
}
}
});
First time the div of dilaog is loading correct data.But Second time,it just shows the old data. I have tried to clear cache in the index action of my controller.Unable to figure out how to solve this.Please help.
Set ajax cache option to false:
$.ajax({
url: '#Url.Action("GetPolicyPremiumAllocation", "Policy")',
data: { policyID: selPolicyId },
cache:false,
type: 'POST',
success: function (data) {
if (data.length > 0) {
alert(data);
document.getElementById("modal_dialog").innerHTML = "";
// $("#modal_dialog").empty();
$("#modal_dialog").load(data,function( ) {
$("#close-button-id").on("click", CloseDialog);
});
$("#modal_dialog").dialog("open");
}
}
});
Or decorate your Action with [OutputCache(NoStore = true, Duration = 0)]
Having some issues properly getting the manipulated data from an element.
Everywhere on the internet doesn't seem to cover such a simple question with a simple answer. Please help.
I have manipulated an element with a returning ajax request:
$("#last_comment_added").html("1457856458")
now my function on the page:
jQuery(document).ready(function($) {
var post_slug = $("#post_slug").html();
var last_comment_added = $("#last_comment_added").text();
if (post_slug && last_comment_added) {
setInterval(function() {
$.ajax({
type: "POST",
url: "ajax_comments.php",
data: {
"task": "updates",
"post_slug": post_slug,
"last_comment_added": last_comment_added
},
cache: false,
success: function(html) {
eval(html)
}
});
}, 10000);
}
});
I get the old data from the element, not the new ajax "1457856458" data.
Please help.
If I understand your problem right it's just that you create this variable called last_comment_added and expect it to be continually updated, you set it once to be the text of the last_comment_added, it's never updated in your interval function. Here's a change that should make it work better for you.
jQuery(document).ready(function($) {
var post_slug = $("#post_slug").html();
if (post_slug && last_comment_added) {
setInterval(function() {
$.ajax({
type: "POST",
url: "ajax_comments.php",
data: {
"task": "updates",
"post_slug": post_slug,
"last_comment_added": $("#last_comment_added").text()
},
cache: false,
success: function(html) {
eval(html)
}
});
}, 10000);
}
});
Don't use eval.
Try
$(document).ready(function() {
var post_slug = $("#post_slug").html();
var last_comment_added = $("#last_comment_added").html();
if (post_slug && last_comment_added) {
setInterval(_update, 10000);
}
});
function _update() {
$.ajax({
type: "POST",
url: "ajax_comments.php",
data: {
"task": "updates",
"post_slug": post_slug,
"last_comment_added": last_comment_added
},
cache: false,
success: function(data) {
$("#last_comment_added").html(data)
}
});
}
and you return from PHP only NEW data. (something like: echo '1457856458';)
I'm trying to prevent multiple requests when user click on login or register button. This is my code, but it doesn't work. Just the first time works fine, then return false..
$('#do-login').click(function(e) {
e.preventDefault();
if ( $(this).data('requestRunning') ) {
return;
}
$(this).data('requestRunning', true);
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
success: function(msg) {
//stuffs
},
complete: function() {
$(this).data('requestRunning', false);
}
});
});
Any ideas? Thanks!
The problem is here:
complete: function() {
$(this).data('requestRunning', false);
}
this no longer points to the button.
$('#do-login').click(function(e) {
var me = $(this);
e.preventDefault();
if ( me.data('requestRunning') ) {
return;
}
me.data('requestRunning', true);
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
success: function(msg) {
//stuffs
},
complete: function() {
me.data('requestRunning', false);
}
});
});
Use on() and off(), that's what they are there for :
$('#do-login').on('click', login);
function login(e) {
e.preventDefault();
var that = $(this);
that.off('click'); // remove handler
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize()
}).done(function(msg) {
// do stuff
}).always(function() {
that.on('click', login); // add handler back after ajax
});
});
In your ajax callbacks the context (this) changes from the outer function, you can set it to be the same by using the context property in $.ajax
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
context: this, //<-----
success: function(msg) {
//stuffs
},
complete: function() {
$(this).data('requestRunning', false);
}
});
You can disable the button.
$(this).prop('disabled', true);
I have also faced a similar problem.
Just adding $('#do-login').attr("disabled", true); gives me the solution.
$('#do-login').click(function(e) {
e.preventDefault();
$('#do-login').attr("disabled", true);
.........
.........
Here do-login is button id.
I've tried this and worked very fine for me, I was having trouble that $.ajax send more request until results return,
var settings = {
"url": "/php/auth/login.php",
"method": "POST",
"timeout": 0,
"async": false,
"headers": {
"Content-Type": "application/json; charset=utf-8"
},
"data": jsondata, //data pass here is in JSON format
};
$.ajax(settings).done(function (ress) {
try{
console.log(ress, "Result from Ajax here");
}
catch(error){
alert(error);
console.log(ress);
}
});
async : false worked for me.
Thanks.
Or you can do it by $(this).addClass("disabled"); to you button or link and after click is performed, you can $(this).removeClass("disabled");.
// CSS
.disabled{
cursor: not-allowed;
}
// JQUERY
$('#do-login').click(function(e) {
e.preventDefault();
$(this).addClass("disabled");
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
context: this,
success: function(msg) {
//do more here
$(this).removeClass("disabled");
},
});
});
P.S. If you use bootstrap css, you do not need the css part.
I found the approach useful. I've implemented it as a general purpose function for jQuery with ES6.
export default function (button, promise) {
const $button = $(button);
const semaphore = 'requestRunning';
if ($button.data(semaphore)) return null;
$button.data(semaphore, true);
return promise().always(() => {
$button.data(semaphore, false);
});
}
Because $.ajax() returns a promise, you simply pass in the promise and the function takes care of the rest.
Roughly speaking, here's the usage.
import preventDoubleClick from './preventdoubleclick';
...
button.click(() => {
preventDoubleClick(this, () => $.ajax()
.done(() => { console.log("success") }));
});
This function can help you with control multi Ajax requests and it's has timeout function which can return flag status to 0 after ex. 10sec (In case the server took more than 10 seconds to respond)
var Request_Controller = function(Request_Name = '', Reactivate_Timeout = 10000)
{
var a = this;
a.Start_Request = function(){
if(window.Requests == undefined){
window.Requests = {};
}
window.Requests[Request_Name] = {'Status' : 1, 'Time': + new Date()};
}
a.End_Request = function(){
if(window.Requests == undefined){
window.Requests = [];
}
window.Requests[Request_Name] = undefined;
}
a.Is_Request_Running = function(){
if(window.Requests == undefined || window.Requests[Request_Name] == undefined){
return 0;
}else{
var Time = + new Date();
// Reactivate the request flag if server take more than 10 sec to respond
if(window.Requests[Request_Name]['Time'] < (Time - Reactivate_Timeout))
{
return 0;
}else{
return 1
}
}
}
}
To use it:
var Request_Flag = new Request_Controller('Your_Request_Name');
if(!Request_Flag.Is_Request_Running()){
Request_Flag.Start_Request();
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
success: function(msg) {
//stuffs
},
complete: function() {
Request_Flag.End_Request();
}
});
}
for prevent multiple ajax request in whole site. For example: If use ajax request in other ajax page, Using ajax in php loop, etc, Give you multiple ajax request with one result. I have solution:
Use window.onload = function() { ... }
instead of
$(document).ready(function(){ ... });
on the main index.php page. Its will be prevent all multi request. :)