Form submission with jQuery / Ajax only works at other times

I am trying to submit a form that involves uploading a file via Ajax / jQuery, processing the form via a PHP script, and returning the result in the div that the form was originally in.

My current form code:

<section id="content-right">
<form name="uploader" id="uploader" method="POST" enctype="multipart/form-data">
    <input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="10485760" />
    <input type="file" name="fileselect" id="fileselect" />
    <input type="submit" name="submit" id="submit" value="Upload" />
</form>
</section>

      

And my current Ajax / jQuery script:

<script> 
$(function() {
$('#uploader').submit(function() { 
        $(this).ajaxSubmit({
            type: $(this).attr('method'),
            url: 'upload-song.php',
            success: function(response) {
                $('#content-right').html(response);
                }
            }); 
    return false; 
    });
});

      

My PHP script is "upload-song.php" (details don't matter).

I also have YUI.Pjax doing the processing of normal navigation links (href) and loading them in # content-right (if the user clicks on anything, I want it to load in # content-right).

With this setting, working on normal links works great, everything is loaded in # content-right, but the loader only works at other times.

For example, the uploader will upload upload-song.php to # content-right and handle everything fine, then if I navigate away from the page and try to load another element it doesn't work, it will just refresh the page (if I set action = "upload- song.php "in the form tag, it will load upload-song.php as a full page, not in # content-right). After refreshing the page, I can load another item and it works fine.

I think it has to do with how I bind my Ajax script to the form submit (because if I refresh the page it works fine), but I don't have much experience with these languages, so I'm not sure how it is fix.

Also, if I disable YUI.Pjax, it fixes the loader, but obviously breaks my links, so I'm looking for a job.

Any ideas?

+3


source to share


1 answer


Try the following:

$(document).on("submit", "#uploader", function() ...

      



This syntax will allow the event to send a bubble to the document. This way, when the section is #content_right

reloaded, the document retains the event listener response configured in the DOM ready function.

+5


source







All Articles