kallakafar kallakafar - 2 months ago 6
jQuery Question

jquery form submit does not work after using a load function

I have an index.html page which, using jquery, calls somepage.php residing within the same site to load the contents of this index.html page.

So this is the intended page load sequence:
index.html -> somepage.php -> submit.php (if submit button is clicked)

The index.html has only the "main-div" and no contents as such. When the somepage.php is called, the "main-div" contents are loaded by running the php script. The main-div contains a sub div with a small form with a submit button. Using jQuery,I see if the submit button is clicked, and when clicked, the submit.php script is called.

This is the barebone code:

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$('document').ready(function(){

$("#main-div").load("http://www.someurl.com/somepage.php");

$('#item-submit').click(function(){
jsURL = $('#input').val();
submit(jsURL);

});

function submit(jsURL){
$.get(
'http://www.someurl.com/submit.php',
{ item: jsURL },
function(data){
if(data=="success")
{
$('#submit-status').html(data);
}
else
{
$('#submit-status').html(data);
}
}
);
}


});
</script>

</head>
<body>

<div id="main-div"> </div>

</body>
</html>


Now the issue:
The index.html page loads with everything displayed correctly (the small form with the submit button, all other main-div contents, everything is displayed). However, the submit button does not call the submit.php script, meaning I believe that the jQuery code corresponding to the click event is not being registered.

I am fairly new to jQuery. Does this have something to do with how I have "ordered" the code in the jQuery .ready()? Something to do with the DOM not being ready before the function is called, or maybe an issue with the .load() in jQuery?

Answer

Try this :

<script>
$(document).ready(function(){
        $("#main-div").load("http://www.someurl.com/somepage.php",function(){
        $("#main-div").on('click', '#item-submit', function(e){
           e.preventDefault();
           var jsURL = $('#input').attr('value');
           submit(jsURL);
        });
        });
});

function submit(jsURL){
                    $.ajax({
                    url:'http://www.someurl.com/submit.php',
                    type :'GET',
                    success: function(data){
                    $('#submit-status').html(data);
                    }
                    });

                }
</script>
Comments