Jump to content

Recommended Posts

I have some some divs which are dynamically created from a PHP script and displayed to a page via AJAX so the data in the divs are updated/refreshed when new data is present in a JSON file. These divs have a link on it to open a modal. When the page first loads the links work great. When the script updates the PHP file and there is new data to display on the page the links for the new data do not work. Therefore I have found out I need to bind the event via .on(click).

Here is my problem I am running into since they are not static IDs to bind to. The IDs are dynamically produced based on the ID from a JSON file that is created from a 3rd party API. Here is a snippet of the code that creates the link.

    $AlertData .= "<div class='alert__view' id='eventID'>\n";
    $AlertData .= "<a href='#{$eventID}' data-toggle='modal' data-backdrop='false' data-target='#{$eventID}'><i class='fa fa-info-circle'></i></a>\n";
    $AlertData .= "</div>\n";

$eventID is the ID for the link as shown in the code above and is also the ID for the modal which it is linked to in order to open dynamic and unique modals for the associated data. So what I have tried to do is this since it doesn't have to be binded to the exact ID I can bind it to the parent ID or class. In this case alert__view for the link as you see above and for the modal using the class .alert-modal instead of the ID since it is dynamic is uses $eventID like the link does. 

$('.alert__view').on('click', 'a', function () {
    $('.alert-modal').html(data); 
});

So I have included this snippet in my AJAX file for updating/refreshing the PHP script like as follows. 

 

function auto_load(){


  //National Warning & Watches Settings
        $.ajax({
          url: "inc/alertsUS.php",
          cache: false,
          success: function(data){
             $("#svrAlertsUS").html(data);
          }
        });
}


$(document).ready(function(){


$('.alert__view').on('click', 'a', function () {
   $('.alert-modal').html(data);
});


auto_load(); //Call auto_load() function when DOM is Ready


});


//Refresh auto_load() function after 10000 milliseconds
setInterval(auto_load,55000);

Unfortunately this is not working. Am I including the binding wrong? Should I put it in the PHP script or should it be merged into the AJAX call somehow? Or do I have this just completely wrong. 

 

-Thanks

 

 

Link to comment
https://forums.phpfreaks.com/topic/304725-event-binding-with-dynamic-ids/
Share on other sites

You'll need to attach the click listener to an element higher up, that isn't replaced by AJAX.

 

So for example, if you have a div with class `.alert-views-container`, and this is where the AJAX loaded data gets injected, then you would attach the listener to that, and use the second parameter of the `.on()` function to target the `a` element.

 

Something like this:

$(".alert-views-container").on('click', 'a', function(e) {
  var id = e.target.id; // Get the ID of the link that was clicked
  var id = this.id; // You could also get the ID this way, as the `this` keyword will contain the element clicked, but it's good to get into the practice of using the event, especially if you move to using arrow functions in the future
});

It would probably be ideal that you give the `a` element a class, so you can target the class name rather than the element tag

 

Hope that helps

Denno

Yeah that makes sense and something I had thought about if I needed to go higher up. I had tried that but I didn't go outside the script being called by the AJAX. I just wrapped the entire modal in a new ID etc. 

 

So as you can see from my first post the AJAX calls an ID svrAlertsUS. On the page which the divs with the data being displayed it is in a container like so...

<div id="alertsUS-expanded" class="collapse">
   <div id="svrAlertsUS"></div>
</div>

So since the ID svrAlertsUS is the container would this work?

$('#alertsUS-expanded').on('click', 'a', function () {
   $('.alert-modal').html(data);
});

Should this be in the script with the AJAX calls or somewhere else?

 

 

The reason I am not using the actual event names with "var id = this.id;is because I don't know the ID as they are dynamic and generated from a JSON file from an API. So when I parse the JSON I have to insert the PHP variable for the ID to use so the modals and links are unique. Would that suggestion still work even though the ID's are generated dynamically?

 

-Thanks

You should be able to attach the listener to `#svrAlertsUS`, because the element itself isn't being replace, only it's contents, so the JS event binding won't be lost. But to answer your question, yes that event binding you've written will work.

 

The suggestion I gave in regard to getting the ID will read whatever the ID is, regardless of how it came to be assigned to the returned data. I wasn't sure if you'd need it, I added it just in case.

 

Looking at your original code again, the function executed when a link is clicked is going to need some more work. You'll likely want to read the content of the `#svrAlertsUS`, and then inject that into the modal, rather than relying on `data` still having the correct data that you want

 

Denno

You'll likely want to read the content of the `#svrAlertsUS`, and then inject that into the modal, rather than relying on `data` still having the correct data that you want

 

 

The content of #svrAlertsUS isn't what is getting injected into the modal. That just displays the page from inc/alertsUS.php in DIVs where I want the data outputted. That ID is the AJAX ID to that script if that makes sense and I am explaining it correctly. 

 

I have tried this but it's not working ether

function auto_load(){


  //National Warning & Watches Settings
        $.ajax({
          url: "inc/alertsUS.php",
          cache: false,
          success: function(data){
             $("#svrAlertsUS").html(data);
          }
        });
}


$(document).ready(function(){


$('#svrAlertsTX').on('click', 'a', function () {
  $('.alert-modal').html(data);
});

auto_load(); //Call auto_load() function when DOM is Ready


});


//Refresh auto_load() function after 10000 milliseconds
setInterval(auto_load,55000);

How would I use that "var id = e.target.id" option? 

What exactly isn't working? is the modal not being populated with the right data? That is because when you call $('.alert-modal').html(data), the data variable likely has a value of undefined

 

If you can let me know exactly what isn't working, I can help you work through that.

 

Ignore that I wrote the ID section of my code, that just seems to be confusing you

When the script inc/alertsUS.php script is updated by the AJAX script there is an icon on the divs which in this case is a link to open a modal for more information. When the page is first loaded the links work fine and open the modals and the modals are populated with the correct information. BUT if there is new data that means a new div is generated in which case that link is not clickable. If I refresh the page then I can click the link. 

 

After doing research I discovered this is because the click event needs to be binded. So that is what I am trying to accomplish is so that when new data is populated with a new link that link is clickable without having to refresh the page manually. 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.