Unresolved Issue: Jquery Modal Fails to Activate on Subsequent Click for Ajax-

When I make an Ajax call, I load HTML into a div. This HTML content contains a jQuery modal that opens when clicked. However, on the first click, the modal opens correctly. On subsequent clicks, I receive the following error in the console:

 Uncaught TypeError: $(...).dialog is not a function

The HTML generated from the Ajax call includes this element, which triggers the modal:

 <div class="edit" rel="630000311">630000311</div>

This is the relevant CSS for the edit class:

.edit {
   cursor: pointer;
   color: blue;
   font-size: 16px;
   padding-left:5px;
   text-decoration: underline;
  }
  .ui-widget-overlay {
    position: fixed; 
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: #000;
    opacity: 0.7;
    filter: alpha(opacity=50); 
   }

Here is my jQuery code:

       $(document).ready(function(){
       $('body').on('click','.edit', function(){ 
      var myDialogX = $(this).position().left - $(this).outerWidth();
      var myDialogY = $(this).position().top - ( $(document).scrollTop() + $('.ui-dialog').outerHeight() );
   $("#viewDialog").dialog({
       width: 1140,
       modal: true,
       position: { my: 'top', at: 'top+150' },
   });
   var partID = $(this).attr('rel');
        $.ajax({
            async: false,
            type: 'GET',
            url: "parthistory.php",
            data: {
                "partID" : partID
            },
            success: function (data) {
                $("#viewDialog").html(data);

            }
        });
});
});

I have attempted to solve the issue by adding $(document).trigger('ready'); inside the success function, but it did not help.

Note: These are the jQuery scripts I am loading:

code.jquery.com/jquery-1.11.1.min.js"
code.jquery.com/ui/1.11.1/jquery-ui.min.js"
code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" 

Answer №1

Give this a try:

   $(document).ready(function(){
       $("#customDialog").dialog({
           width: 800,
           modal: true,
           autoOpen: false,
           position: { my: 'top', at: 'top+150' }
       });
       $('body').on('click','.popup', function(){ 
           $("#customDialog").dialog('open');
           var dialogX = $(this).position().left - $(this).outerWidth();
           var dialogY = $(this).position().top - ( $(document).scrollTop() + $('.ui-dialog').outerHeight() );
           var partID = $(this).attr('rel');
           $.ajax({
                async: false,
                type: 'GET',
                url: "partdetails.php",
                data: { "partID" : partID },
                success: function (data) {
                    $("#customDialog").html(data);
                }
           });
       });
   });

One common mistake is to initialize the dialog inside an event, such as a click. This can result in the dialog working only once because the autoOpen property defaults to true. On subsequent clicks, the attempt to initialize the dialog gets ignored and it doesn't open.

The solution: Initialize your dialog outside of the on click event, set autoOpen to false, and open it within the desired event instead.

You can also safely remove the comma after setting the position value in the dialog since it's the last property being set.

Sidenote: Double-check the versions of jQuery you're importing. Strange issues like this can occur when multiple or outdated versions of jQuery are imported.

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

Inquiring about socket.io: How can an io emit its own signal?

I am currently working on implementing the emit event in an express router, and I'm attempting to pass a global.io variable. However, I've encountered an issue where despite adding the following code: io.emit('join','Tudis' ...

Printed plaintext of CSS & jQuery code on the 200th iteration in PHP

I encountered an issue while working on a script that involved displaying query data based on domain type (referred to as typeX & type Y). To achieve this, I utilized the jQuery slidetoggle function along with some CSS. Everything was functioning perfectly ...

What causes the left click to not trigger in Kendo's Angular Charts?

My homepage features a simple bar chart that displays correctly, but I am having trouble capturing the left click event (the right click works fine). This is an example of code from my template: <kendo-chart *ngIf="(dataExists | async)" [ ...

Is there a way for me to discover the identity of the victor?

There are 4 divs that move at different, random speeds each time. I am trying to determine which one is the fastest or reaches the goal first. Additionally, there is a betting box where you can choose a horse to bet on. I need to compare the winner with my ...

Deleting a hyperlink within a content-editable area

Presently, I am in the process of working on a straightforward project where users can format text using contenteditable. I have successfully implemented a feature that allows users to add hyperlinks to selected text by clicking on the "Create Link" button ...

loading JSON file using dynamic JavaScript techniques

My Raspberry Pi is running a C++ application in the background that performs complex mathematical calculations based on sensor input and generates results every second. I want to showcase this data on a website by having the application create a JSON file ...

The radio button becomes unchecked when moving to the next fieldset

While developing a dynamic page using PHP and Laravel, I encountered a situation where I needed to add an additional radio button option to each card. Below is the code snippet for the card in question: <div class="card" style="margin:10p ...

A guide on incorporating jQuery alert messages into Angular 2

Whenever I submit a form by clicking on the "send message" button, I want to display an Alert message using jQuery. However, currently, I have to double click for the alert message to appear. How can I make it so that the alert message is shown with just o ...

Tips for inserting the <style> element within a Vue.js component

Currently working with Vue.js v2, I am facing an issue where I have a CSS stylesheet stored as a string in a variable. import sitePackCss from '!!raw-loader!sass-loader!../../app/javascript/styles/site.sass'; I am trying to generate a <style& ...

Create a centrally located search bar in the header with a stylish button using Bootstrap 5

Struggling with aligning elements on my simple search page. The goal is to center the company name above the search input and have buttons centered under it with some spacing in between. https://i.stack.imgur.com/FdadF.png <div class="backgroundWh ...

Arranging particular placement

How can I position my links to the right of the second photo (opus1) and slightly below the first photo (coverPhoto)? I've tried various methods but haven't found a simple solution yet. <!DOCTYPE html> <html lang="en"> <head ...

HTML comment without the presence of javascript

Is it possible to use different expressions besides checking for the browser or version of IE in order to display/hide content? For example: <!--[if 1 == 0]--> This should be hidden <!--[endif]--> I am considering this option because I send o ...

"Utilize Vuejs to establish a binding between two objects when necessary

With the help of moment, my calendar generates 41 days. for (let x = 0; x < 42; x++) { context.add(1, 'd'); let day = { 'date': moment(context), 'events': [] }; } ...

Develop a CSS layout for the specified design

Aiming to achieve a unique layout using dynamic html strings. The challenge arises when transitioning to the second page as the layout does not adjust upward and images cannot be added to the first page. Attempting to implement the following sample code ...

Javascript tabs with clickable links

I have created a page with a series of thumbnails that reveal content below when clicked. The content is positioned absolutely and set to display:none, with javascript changing this for each thumbnail. (I am not very familiar with javascript and learned t ...

Troubleshooting: jQuery AJAX failing to receive JSON data in HTTP request

Experimenting with HTML and jQuery to practice JSON requests, I conducted some research and attempted a small test. However, upon running the script in Google Chrome, only my HTML/CSS elements appeared instead of expected results. Below is the code snippet ...

Utilizing JavaScript to Incorporate Node Packages

Sorry for the basic question, as I am fairly new to web development and JavaScript. I am trying to utilize a package that I installed via npm called shopify-buy by following the instructions provided at: The package is located in my node_modules director ...

utilize dynamic variable within the template's views

Here is a snippet of my HTML code var marker; function initMap() { map = new google.maps.Map(document.getElementById("mymap"), myOptions); getMapMetadata([]); // setInterval(function(){ getMapMetadata([]); }, 3000); } function createMarke ...

A guide on updating various states using React Hooks

Creating a background component with the use of Vanta in NextJS, here's the code snippet: import { useEffect, useRef, useState } from "react"; import * as THREE from "three"; import FOG from "vanta/dist/vanta.fog.min"; im ...

Setting up Webpack and Babel for ReactJS development

Recently, I started delving into the world of ReactJS and stumbled upon a tool called webpack which acts as a module bundler. However, I've hit a roadblock while configuring it and keep encountering the following error message: ERROR in ./src/index. ...