1

I'm trying to learn how AJAX interaction with jQuery works. So far I have always worked with multi-page applications and am not very good with JavaScript. To learn this, I'm creating a small project that implements CRUDs on a MySQL table asynchronously.

I have created two jQuery functions that inject the 'index' and 'create' views into the page. The problem I have is that the main.js file does not listen to the events that occur in the injected part of the web page.

This is the main html document:

<html>
<head>
    <meta charset="utf-8">
    <title>MySql AJAX CRUD</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
    <h1>MySQL CRUD</h1>
    
    <button id="create">Create</button>
    <button id="index">Index</button>
    <button id="store">Store</button>
    
    <div id="content">
        Content goes here...
    </div>  
    
    
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- jQuery CDN -->
    <script type="text/javascript" src="js/main.js"></script>

</body>
</html>

This is the 'main.js' file wich is inside a directory called 'js':

    // Index
    $('#index').click( function() {
        $('#content').load("contents/index.php");
    });
    
    // Create
    $('#create').click( function() {
        $('#content').load("contents/create.html");
    });

    // Store
    $('#store').click( function() {

        alert('store function is working');    // Test
    
    });

});

And this is the content 'create.html' i inject into the main html page:

<p>Country name:</p>
<input type="text" id="countryName"><br><br>
 <p>Short description:</p>
<input type="text" id="shortDesc"><br><br>
<p>Long Description:</p>
<input type="text" id="longDesc"><br><br>

<button id="store">Store</button>

If i click on the button on 'create.html' nothing happens. If i click on the button on 'index.html' the store function trigger.

Can someone explain me why?

  • Because the elements on the `create.html` page don't exist yet when you look for them, so you don't end up attaching any event handlers to them. See the [linked question](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements)'s answers for details and what to do about it (typically event delegation). – T.J. Crowder Dec 01 '20 at 16:16

1 Answers1

0

as said before, you are using jquery to set a callback on an item that is not yet loaded in the DOM. To fix it, you can register the callback once 'create.html' is loaded:

// Create
    $('#create').click( function() {
        $('#content').load("contents/create.html", function(){
           // Store
           $('#store').click( function() {
              alert('store function is working');
           });
        });
    });
Mathieu Seiler
  • 726
  • 8
  • 13