A guide on linking a jQuery dialog to an HTML element once the data has been updated with an AJAX response

On my PHP page, I have implemented a jQuery script to open a dialog window. The code for this is as follows:

<script type="text/javascript">
            $(document).ready(function() {
                var $loading = $('<img src="loading.gif" alt="loading" class="loading">');

                $('#data-specs a').each(function() {
                    var $dialog = $('<div></div>')
                        .append($loading.clone());

                    var $link = $(this).one('click', function() {
                        $dialog

                            .load($link.attr('href'))
                            .dialog({
                                title: '<?php echo $_GET["indQ"];?>',
                                modal: true,
                                width: 500,
                                height: 300,
                                minHeight: 300,
                                maxHeight: 600,
                                minWidth: 500,
                                maxWidth: 800
                                });

                            $link.click(function() {
                            $dialog.dialog('open');

                            return false;
                        });

                        return false;
                    });
                });

                $('#dav').val(getURLParameter('davQ'));

                $('#pathogen').val(getURLParameter('pathogenQ'));

                $('#topicF').val(getURLParameter('topicQ'));

                $('#ind').val(getURLParameter('indQ'));

                $('#subind').val(getURLParameter('subindQ'));

                $(".selfont").change(function (event) {
                        window.location = '?davQ=' + $('#dav').val() + '&pathogenQ=' + $('#pathogen').val() + '&topicQ=' + $('#topicF').val() + '&indQ=' + encodeURIComponent($('#ind').val()) + '&subindQ=' + encodeURIComponent($('#subind').val());
                });

                function getURLParameter(name) {
                         return decodeURIComponent((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]);
                }

            });
    </script>

The data is displayed in a table with the id 'data-specs' and everything works smoothly. However, when I added a dropdown box with sorting values using an AJAX script, it caused an issue. After the AJAX call for sorting, clicking the link to open the dialog window opens it in the parent window instead. If I press the back button on the browser and then click the link again, the dialog window opens without any errors. How can I resolve this even after sorting is done using AJAX? Please provide me with some solutions. The AJAX code for sorting is shown below:

function ajaxFunction(){

    //to keep selection in countryList - GP
    var ref = document.getElementById('countryRF');
    for(i=0; i<ref.options.length; i++)
    ref.options[i].selected = true;


    var ajaxRequest;  // The variable that makes Ajax possible!

    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }
    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            //document.myForm.time.value = ajaxRequest.responseText;
            document.getElementById("result").innerHTML=ajaxRequest.responseText

        }
    }

    var dav = document.getElementById('dav').value;
    var pathogen = document.getElementById('pathogen').value;
    var topicF = document.getElementById('topicF').value;
    var ind = document.getElementById('ind').value;
    var subind = document.getElementById('subind').value;
    var selObj = document.getElementById('countryRF');
    var cnty = loopSelected(selObj).join('~');  // join array into a string
    var sortby = document.getElementById('sortby').value;

    var queryString = "?dav=" + dav + "&pathogen=" + pathogen + "&topicF=" + topicF + "&ind=" + encodeURIComponent(ind) + "&subind=" + encodeURIComponent(subind) + "&cnty=" + encodeURIComponent(cnty) + "&sortby=" + sortby;
    ajaxRequest.open("GET", "sortbyD.php" + queryString, true);
    ajaxRequest.send(null);
    return false;
}

Please assist me in resolving this issue.

Answer №1

Upon initial page load, the dialog box events are bound to elements. However, after an AJAX call, you must re-bind the dialog box events using the .bind() function.

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

Issue with fancyBox not functioning properly when integrated with a caption script

Hey there! I've been working with both jQuery's fancyBox for displaying image/video galleries and the Capty script for showing image titles on images. However, I've run into a snag - when the title is displayed on the image, fancyBox st ...

PHP response triggers AJAX autocomplete functionality in JavaScript

The autocomplete hints are not displaying any response for me. Here is the jQuery code that I am using: jQuery( ".newtag_new" ).autocomplete({ minLength: 0, source: function( request, response ) { jQuery.ajax({ type: 'GET ...

What is the most effective way to perform two GET requests in PHP?

Here's the code snippet I am currently working on: $header = [ 'phoneType' => $mobileType ]; \Drupal::logger("cam")->debug('PageNameHere retrieveAPINameHere REQUEST: '.json_encode($head ...

Unlocking the Power of AngularJS through Deferred and Promise for Maximum Reus

I am new to using deferred promises and I couldn't find specific answers to my questions. Is it recommended to use deferred promises even for a single simple ajax($http angularjs) call? I know it is beneficial if we have multiple ajax calls in seq ...

Is it possible to compare two charts in Chart.js in a way that avoids the issue of small values appearing as large as big values?

I am currently working on a production tracking page that features multiple charts. I want to avoid inconsistencies in tracking at first glance. Is there a way to achieve this using chart.js? If not, what would be the best approach to address this issue? ...

The function $.ajax may not be available, but rest assured that the jquery library is functioning properly

Upon checking the console, I noticed the following: Here is the AJAX code snippet in use: $("#accept").click(function(){ id = $("#idInput").val(); password = $("#passwordInput").val(); alert(id) alert(password) $.aja ...

Converting Ruby strings into pure binary format

PHP has a hash() function that is capable of returning raw binary data. https://www.php.net/manual/en/function.hash.php I am interested in achieving the same functionality in Ruby. Does anyone know how I can accomplish this? To create the hash, I curren ...

The Power of jQuery Slider and Toggle

I found a really cool slide show on the internet! You can check it out at this link. It uses the easySlider plug-in and also includes the jQuery Toggle function. There's one thing I noticed though - when you navigate through the slides, the descripti ...

How to use AJAX script to call a non-static page method in ASP.NET

Is it possible to achieve this task without utilizing the UpdatePanel feature? ...

As you hover over the chosen image, the selected image will appear

I have a simple HTML code with some JavaScript where I display sets of images. All I want is for the images to pop up when hovered over, appearing in a larger size. Below is the example HTML Code: <div class="content-box-left-bootomgrid lastgrid"> ...

Zoom out the slider when scrolling

Take a look at this link and as you scroll down the page, notice how the image transitions to iPhone. Can anyone provide insight on how this effect is achieved? ...

Ways to select a single checkbox when other checkboxes are selected in JavaScript

var select_all = document.getElementById("select_all"); //reference to select all checkbox var checkboxes = document.getElementsByName("testc"); //retrieving checkbox items //function to select all checkboxes select_all.addEventListener("change", function ...

Adding new data to Codeigniter database

Having recently started to work with codeigniter, I have encountered a challenge when it comes to inserting data into my MySQL database. While I am able to retrieve information from the database through a controller called home.php using a model I create ...

Issue with executing Exec, passthru, and System functions

Hello everyone, my dear friends and teachers... Heart During the design phase of my current project, I have encountered a problem while using Game. Unfortunately, I did not achieve the desired outcome. HuhHuh For this project, I have been utilizing AutoHo ...

The CORS policy does not permit the use of the POST request method

I rely on asp.net core 2.1 for creating web APIs and utilize ajax requests on my website to interact with the API. Initially, I encountered an issue with the GET method, which I managed to resolve using a Chrome plugin. However, I am still facing difficu ...

I currently have two responsive menus and I'm trying to figure out how to modify the javascript so that when one menu is opened, the other

I am facing an issue with my responsive menus on a webpage, similar to the example provided in the jsfiddle link below. Currently, when one menu is open and I click on another, both remain open. How can I modify the JavaScript code so that when one menu op ...

Unexplainable space or padding issue detected in OwlCarousel grid gallery

There seems to be an unusual gap or margin at the bottom of each row section in this portfolio grid gallery that's running in OwlCarousel. You can view an example here. https://i.stack.imgur.com/NHOBd.png I've spent a lot of time trying to solv ...

Pattern matching to locate text that is not enclosed within HTML tags and does not fall within certain specified tags

I am attempting to create a regular expression that will match specific words located outside and between HTML tags (but not within the tags themselves). However, I also need to ensure that these words are excluded when they appear between heading tags suc ...

Tips for dynamically populating JSON data using a dropdown selection?

I am currently exploring HTML forms as a new web developer. I have been experimenting with displaying JSON data in a div based on a selection from a dropdown menu using jQuery in Chrome. However, my code does not seem to be functioning properly. Even tho ...

Creating an SQL select statement with a three-level expression is a complex task that requires careful planning and

How can I create a SQL select query with 3 levels of expressions and statements? Typically, my website operates on an SQLite database and the search results are displayed using the following SQL query: "SELECT DISTINCT * FROM amz WHERE Title LIKE \" ...