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?