Two separate $.ajax call "kill" each other on click function - javascript

So here is the problem:
I have two click event in one page. The first when you click on a thumbnail picture it's open a modal which shows a bigger image like Instagram on PC (I make an Instagram clone for practicing btw). The other button is for show more image.
The problem is, I use ajax for both click to get some variable and pass to the php. When the page loaded it's shows only 3 image and when I clicked one of them It's shows the right image in the modal but when I click show more it shows 3 more and after when I clicked on the thumbnail it's stucked. I mean its shows only one picture doesn't matter which thumbnail i clicked so the ajax request not runs again. I hope you can understand the problem and can help me. (sorry for my English).
So here is the code:
This is the ajax calling function:
function ajaxShow(urls,datas,element){
$.ajax({
url: urls,
data: {datas: datas},
cache:true,
}).always(function(result){
console.log("done");
element.html(result);
});
}
And these are the click events:
$(document).ready(function(){
//Open picture in modal
var pic = $(".pics");
var modalCont = $(".modal-content");
pic.on('click',function(event){
event.preventDefault();
var id = $(this).attr('data-id');
console.log(id);
ajaxShow("../php/ajax_modal.php",id,modalCont);
});
//Load more
var smbt = $(".smbt");
var limit = $(smbt).data('loaded');
smbt.on('click',function(event) {
event.preventDefault();
var cont = $("#cont");
limit += 3;
console.log(limit);
ajaxShow("../php/show_more.php",limit,cont);
});
});
In a nutshell: After I clicked on load more the modal open ajax request not run again.

Use overloaded version of .on() on document node.
$(document).on(events, selector, data, handler );
So your code should be rewritten as this:
$(document).on('click', '.pics', null, function (event) {
event.preventDefault();
var id = $(this).attr('data-id');
console.log(id);
ajaxShow("../php/ajax_modal.php",id,modalCont);
});
and
$(document).on('click', '.smbt', null, function (event) {
event.preventDefault();
var cont = $("#cont");
limit += 3;
console.log(limit);
ajaxShow("../php/show_more.php",limit,cont);
});

Related

AJAX post and page refresh

I'have and AJAX post request:
$(document).ready(function() {
$("span").click(function(e) {
e.preventDefault();
e.stopPropagation();
var URL = "someURL";
$.post(URL, this.id, function(data, status) {
var val = parseInt(document.getElementById(this.data).innerHTML)
document.getElementById(id).innerHTML = val + 1 ;
document.getElementById(id).disabled=true;
});
});
});
Read
<span id="${book.id}">
This script is working as expected; a button with number in it increase by one.
The problems are:
A refresh of the page occurs. On button click it reloads all on the page.
I'm not able to disable the button after the change
In short I need a count button which increase by 1 and can be changed once per user.
Update It seems that reload it's related to another function defined as
$(document).ready(function() {
So i have one in the body and one in the head.
Of course it refreshes the page, you're sending it a link to go to via href. Instead, remove the href, and put an onclick event and handler. Replace your anchor tag, with this:
<a onclick="runFunction()">Read</a>
And replace your script, with this.
<script>
function runFunction(){
$(document).ready(function(){
$("span").click(function(e){
e.preventDefault();
e.stopPropagation();
var URL="someURL";
$.post(URL,
this.id,
function(data,status){
var val = parseInt(document.getElementById(this.data).innerHTML)
document.getElementById(id).innerHTML = val + 1 ;
document.getElementById(id).disabled=true;
});
});
});
}
</script>

Handling State changes jQuery and History.js

Ok, so I need some insight into working with History.js and jQuery.
I have it set up and working (just not quite as you'd expect).
What I have is as follows:
$(function() {
var History = window.History;
if ( !History.enabled ) {
return false;
}
// Capture all the links to push their url to the history stack and trigger the StateChange Event
$('.ajax-link').click(function(e) {
e.preventDefault();
var url = this.href; //Tells us which page to load
var id = $(this).data('passid'); //Pass ID -- the ID in which to save in our state object
e.preventDefault();
console.log('url: '+url+' id:'+id);
History.pushState({ 'passid' : id }, $(this).text(), url);
});
History.Adapter.bind(window, 'statechange', function() {
console.log('state changed');
var State = History.getState(),
id = State.data.editid; //the ID passed, if available
$.get(State.url,
{ id: State.data.passid },
function(response) {
$('#subContent').fadeOut(200, function(){
var newContent = $(response).find('#subContent').html();
$('#subContent').html(newContent);
var scripts = $('script');
scripts.each(function(i) {
jQuery.globalEval($(this).text());
});
$('#subContent').fadeIn(200);
});
});
});
}); //end dom ready
It works as you'd expect as far as changing the url, passing the ID, changing the content. My question is this:
If I press back/forward on my browser a couple times the subContent section will basically fadeIn/fadeOut multiple times.
Any insight is appreciated. Thanks
===================================================
Edit: The problem was in my calling all of my <script> and Eval them on each statechange. By adding a class="no-reload" to the history controlling script tag I was able to do:
var scripts = $('script').not('.no-reload');
This got rid of the problem and it now works as intended. Figure I will leave this here in case anyone else runs into the same issue as I did.
The problem was in my calling of all of my <script> and Eval them on each statechange. By adding a class="no-reload" to the history controlling script tag I was able to do:
var scripts = $('script').not('.no-reload');
This got rid of the problem and it now works as intended. Figure I will leave this here in case anyone else runs into the same issue as I did.

jQuery .on not working after ajax delete and div refresh

On a page with a tab control, each tab contains a table, each tr contains a td with a button which has a value assigned to it.
<td>
<button type="button" class="btn" name="deleteEventBtn" value="1">Delete</button>
</td>
This code below works for the first delete. After the AJAX call & the refresh of the div, no further delete buttons can be clicked. The .on is attached to the document. The same happens if I attach it to the body or anything closer to the buttons.
function deleteRecord(url, id, container) {
$.ajax({
type: "POST",
url: url,
data: { id: id },
success: function (data) {
$('#delete-popup').hide();
$(container).trigger('refresh');
}
});
}
$(document).ready(function () {
$(document).on('click', '[name^="delete"]', function (e) {
e.preventDefault();
var id = $(this).val();
$('#current-record-id').val(id);
$('#delete-popup').modal('show');
});
$('#delete-btn-yes').on('click', function (e) {
e.preventDefault();
var recordId = $('#current-record-id').val();
var recordType = location.hash;
switch (recordType) {
case "#personList":
deleteRecord(url, recordId, recordType);
break;
}
});
});
Any ideas? Could it be related to the wildcard for starts with [name^="delete"]? There are no other elements where the name starts with 'delete'.
EDIT
When replacing
$(container).trigger('refresh');
with
location.reload();
it "works", however that refreshes the whole page, loses the users position and defeats the point of using AJAX.
As the button click is firing at first attempt, there is no issue in that code. All you have to do is, put the button click event in a method and call it after the refresh. This way, the events will be attached to the element again. See the code below,
function deleteRecord(url, id, container) {
$.ajax({
type: "POST",
url: url,
data: { id: id },
success: function (data) {
$('#delete-popup').hide();
$(container).trigger('refresh');
BindEvents();
}
});
}
$(document).ready(function () {
BindEvents();
});
function BindEvents()
{
$(document).on('click', '[name^="delete"]', function (e) {
e.preventDefault();
var id = $(this).val();
$('#current-record-id').val(id);
$('#delete-popup').modal('show');
});
$('#delete-btn-yes').on('click', function (e) {
e.preventDefault();
var recordId = $('#current-record-id').val();
var recordType = location.hash;
switch (recordType) {
case "#personList":
deleteRecord(url, recordId, recordType);
break;
});
}
Apologies to all and thanks for your answers. The problem was due to the way the popup was being shown & hidden.
$('#delete-popup').modal('show');
and
$('#delete-popup').hide();
When I changed this line to:
$('#delete-popup').modal('hide');
it worked. Thanks to LShetty, the alert (in the right place) did help!
If you are using Bootstrap Modal
After Ajax Request before Refreshing page add
$('.modal').modal('hide');
This Line will Close your Modal and reload your page. Before that it will complete all Ajax Request things.
But for google chrome there is no issues :) hope this help someone.

Prevent multiple ajax submissions on multiple clicks

I've a WordPress blog running this jQuery code that allows users to click a bookmark link that saves the post as a bookmark. Each post shows a total bookmark counter that looks like: "Bookmarked (5)". Although this code works, it registers multiple clicks whenever someone clicks multiple times on the bookmark link and then saves the same post as multiple bookmarks. When the user tries to remove the bookmark by clicking on the bookmark link again, it registers multiple clicks again and the counter starts showing minus numbers which looks like: "Bookmarked (-5)".
I've been searching for an instruction on how to prevent this from happening so that the bookmark counter never runs minus and the user can't bookmark the same post multiple times but had no success so far.
Here is the jQuery code that I'm using:
jQuery(document).ready( function($) {
var added_message = upb_vars.added_message;
var delete_message = upb_vars.delete_message
$(document).on('click', '.upb_add_bookmark', function () {
var post_id = $(this).attr('rel');
var data = {
action: 'bookmark_post',
post_read: post_id
};
$.post(upb_vars.ajaxurl, data, function(response) {
$('.upb_bookmark_control_'+post_id).toggle();
if($('.upb-bookmarks-list').length > 0 ) {
var bookmark_data = {
action: 'insert_bookmark',
post_id: post_id
};
$.post(upb_vars.ajaxurl, bookmark_data, function(bookmark) {
$(bookmark).appendTo('.upb-bookmarks-list');
$('.no-bookmarks').fadeOut();
});
}
});
return false;
});
$(document).on('click', '.upb_del_bookmark', function () {
var post_id = $(this).attr('rel');
var data = {
action: 'del_bookmark',
del_post_id: post_id
};
$.post(upb_vars.ajaxurl, data, function(response) {
$('.bookmark-'+post_id).fadeOut();
$('.upb_bookmark_control_'+post_id).toggle();
});
return false;
});
});
Could you please help me solve this problem?
Thanks a lot!
One way is to add a .disabled class to your link before the $.post().
// Before ajax...
if ($(this).hasClass('disabled')) {
return false;
} else {
$(this).addClass('disabled');
}
// Make sure we refer to the same element
var that = this;
// On post success...
$(that).removeClass('disabled');

Show loading animation when collapsible block is opening Jquery Mobile

I have a problem trying to show loading icon when collapsible block is opening. I have a collapsible block with a listview inside which is populated dynamically via ajax/php. They list might have up to 500 elements, so I would like to show loading animation while it is loading.
I have tried
$('div.century').live('expand', function(){
var idval = $(this).attr('id');
console.log('expanded'+idval);
$.mobile.showPageLoadingMsg ();
$.get("helpers/getByCentury.php", { id: idval},
function(data){
$("#"+idval+" ul.ulist").html(data);
$("#"+idval+" ul.ulist").listview('refresh');
});
$.mobile.hidePageLoadingMsg ();
});
I have also tried
$('div.century').live('expand', function(){
var idval = $(this).attr('id');
console.log('expanded'+idval);
$.mobile.pageLoading();
$.get("helpers/getByCentury.php", { id: idval},
function(data){
$("#"+idval+" ul.ulist").html(data);
$("#"+idval+" ul.ulist").listview('refresh');
});
$.mobile.pageLoading(true);
});
without any luck.
Can anyone tell me how to fix this?
Thanks in advance.
You want to call $.mobile.hidePageLoadingMsg() in the callback function for your ajax call:
$('div.century').live('expand', function(){
var idval = $(this).attr('id');
console.log('expanded'+idval);
$.mobile.showPageLoadingMsg ();
$.get("helpers/getByCentury.php", { id: idval},
function(data){
$("#"+idval+" ul.ulist").html(data);
$("#"+idval+" ul.ulist").listview('refresh');
$.mobile.hidePageLoadingMsg ();//NOTICE: this has been moved inside the callback function for your $.get() call
});
});
Also a couple pointers.
You are using the $("#"+idval+" ul.ulist") selector twice in a row, you can make that more efficient by chaining function calls together like so:
$("#"+idval+" ul.ulist").html(data).listview('refresh');
If other people view your webpage in a browser that does not have the console.log function they will get an error and your JS will stop running, it is normally a good idea to put calls to the console.log function inside a conditional that checks for the existance of that function:
if (typeof(console.log) == 'function') {
console.log('expanded'+idval);
}

Categories

Resources