During the click event, two distinct $.ajax requests interfere and cancel each other out

Here's a dilemma I'm facing: On my webpage, I have implemented two different click events. The first one opens a modal displaying a larger image when you click on a thumbnail picture (similar to Instagram on PC - I created an Instagram clone for practice). The second button is used to load more images.

The issue arises because I am using AJAX for both clicks to retrieve certain variables and pass them to PHP. Initially, the page only shows 3 images, but when I click on a thumbnail, the correct image is displayed in the modal. However, after clicking "show more" to display 3 additional images, the modal gets stuck. Regardless of which thumbnail I click on afterwards, only one picture is shown, indicating that the AJAX request isn't being triggered again. I hope this description clarifies the problem, and I would greatly appreciate any assistance. (Apologies for any language errors).

Below is the corresponding code:

Here is the function for the AJAX call:

function ajaxShow(urls,datas,element){
    $.ajax({
        url: urls,
        data: {datas: datas},
        cache:true,
    }).always(function(result){
        console.log("done");
        element.html(result);
    });
}

And here are the click event functions:

$(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);
    });
});

To summarize: After clicking on "load more," the modal does not open, and the AJAX request fails to run again.

Answer №1

Utilize the overloaded version of the .on() method on the document element.

$(document).on(events, selector, data, handler);

Incorporate this revised code:

$(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);
});

Additionally:

$(document).on('click', '.smbt', null, function (event) {
    event.preventDefault();
    var cont = $("#cont");
    limit += 3;
    console.log(limit);
    ajaxShow("../php/show_more.php", limit, cont);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Try utilizing querySelectorAll() to target the second item in the list

As I delve into the world of HTML and JS, I came across the document.querySelectorAll() API. It allows me to target document.querySelectorAll('#example-container li:first-child'); to select the first child within a list with the ID 'exampl ...

The dropdown menu button stubbornly remains open and refuses to close

Having an issue with a dropdown menu button where it should open when clicked on the icon and close when clicking off the icon or on the icon again, but instead, it remains open. Here is a screenshot for reference: https://i.stack.imgur.com/UX328.jpg I&a ...

Creating a buffered transformation stream in practice

In my current project, I am exploring the use of the latest Node.js streams API to create a stream that buffers a specific amount of data. This buffer should be automatically flushed when the stream is piped to another stream or when it emits `readable` ev ...

Error encountered in Django due to repeated AJAX calls causing a closed socket issue: [WinError 10053] The established connection was abruptly terminated by the software running on your host machine

Trying to integrate live search functionality using the Select2 jQuery plugin in my Django 1.11.4 project has led to some server-related issues. Upon entering text into the search box, the server seems unable to handle the volume of requests and ends up sh ...

Could the comments within a NodeJS script be causing memory problems?

I specialize in creating NodeJS libraries, and my coding practice includes adding JSDoc comments for documentation purposes. Here is an example of how my code usually looks: /** * Sum * Calculates the sum of two numbers. * * @name Sum * @function * ...

It is impossible to alter the data contained within the input box

Objective: Upon clicking a button to display the modal, the selected data (first and last name) should be inserted into an input box and editable. The user should be able to modify the data. Issue: The data entered into the input box cannot be edited ...

Locate the closing anchor tag following the image

I need to locate the closing anchor tag that wraps an image with the class name "cat-image" in order to move a div right after it. However, I am unable to modify the HTML by adding IDs or classes to the anchor or image tags. Below is an example of the HTM ...

React fails to display the content

Starting my React journey with Webpack configuration. Followed all steps meticulously. No error messages in console or browser, but the desired h1 element is not showing up. Aware that React version is 18, yet working with version 17. App.jsx import Reac ...

Incapable of retrieving data from MongoDB due to a failure in fetching results using streams in Highland.js

I have recently started working with streams and I am experimenting with fetching data from my collection using reactive-superglue/highland.js (https://github.com/santillaner/reactive-superglue). var sg = require("reactive-superglue") var query = sg.mong ...

Transferring a variable from an Angular 2 constructor into the template via the then statement

I'm struggling with implementing a secure login system. My goal is to first check the device's native storage for an item named 'user', then verify if the user exists in our database, and finally retrieve the unique id associated with t ...

Django: Error - < found where unexpected

Using a combination of Django and jQuery, I have implemented a file upload feature with AJAX. Everything seems to be working correctly - the files are successfully uploaded, reflected in the database, and stored on the server. However, upon completion of t ...

Find and substitute numerous PHP code lines

Hello there, I am a beginner when it comes to using preg_replace and similar functions so please be patient with me. I have several hundred lines that include this specific line: <strong>[*<a title="*" name="*"></a>]</strong><b ...

Delivering HTML with Python Socket Server

I am currently learning about HTTP/CGI and exploring how to display HTML content on a webpage through the use of the socket library in Python. However, I am encountering some confusion regarding the correct syntax for this task: #!/usr/bin/env python impo ...

Trouble with displaying autocomplete options for ajax requests

I recently implemented the autocomplete feature using bootstrap typeahead in my project. The original code snippet worked flawlessly: $(function () { var $input = $(".typeahead"); $input.typeahead({ source: [ {id: "someId1", name: "Display nam ...

The FontLoader feature seems to be causing issues when integrated with Vuejs

While working on a Vue project with threejs, I encountered an error similar to the one described here. The issue arose when attempting to generate a text geometry despite confirming that the path to the typeface font is accurate and in json format. ...

receiving a pair of components instead of just one

Here is the code for router.js: import React from 'react'; import { Route } from 'react-router-dom'; import CommentList from './containers/commentview'; import CommentDetalList from './containers/commentdetailview'; ...

ExpressJS exhibits unique behavior based on whether the API is requested with or without the specified PORT number

I have encountered an issue with my 2 flutter web apps. One of them is functioning flawlessly when I request the URL, but the other one only works when I include the port xxxxx:4000/nexus-vote. However, when I remove the port, I receive a status code of 20 ...

The functionality of Ajax is not supported on iPhone Safari browsers

I have encountered an issue where my ajax function works perfectly in Firefox, but it fails to work on my iPhone. Initially, I suspected the XMLHttpRequest was causing the problem, but that does not appear to be the case. I can confirm that the PHP script ...

Syntax error encountered: unexpected character '*'

Here is the code snippet I am currently working on: <?php function calculateCompoundInterest($principle, $rate, $time) { $ci = ($principle * (( (1 + $rate / 100) ** $time) - 1)); echo $ci; } ?> <?php echo calculateCompoundInterest ...

Adjust CSS classes as user scrolls using skrollr

I am currently facing an issue with the prinzhorn/skrollr plugin when trying to use removeClass/addClass on scroll function. I have attempted to find a solution but unfortunately, nothing has worked for me. <li class="tab col s3"><a data-800="@cl ...