Submitting a form with jQuery/Ajax only works every other time

怎甘沉沦 提交于 2019-12-31 01:49:16

问题


I'm trying to submit a form which includes a file upload via Ajax/jQuery, process the form through a PHP script, and return the result in the div that the form originally resided in.

My current form code is:

<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 is:

<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" (the details don't matter).

I also have YUI.Pjax running to handle normal navigation (a href) links and load those in #content-right (if a user clicks anything, I want it loading in #content-right).

With this set up, navigating through normal links works perfectly, everything loads in #content-right, but the uploader only works every other time.

For example, the uploader will load upload-song.php in #content-right and process everything perfectly, then if I navigate away from the page and try to upload another item, it won't work, it'll just refresh the page (if I put action="upload-song.php" in the form tag it'll load upload-song.php as a full page, not in #content-right). After it refreshes the page I can upload another item and it will work perfectly.

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

In addition, if I disable YUI.Pjax it fixes the uploader but obviously breaks my links, so I'm looking for a work around.

Any ideas?


回答1:


Try this:

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

This syntax will let the submit event bubble up to the document. That way, when the #content_right section reloads, the document retains the event listening response set up in the DOM ready function.



来源:https://stackoverflow.com/questions/14741746/submitting-a-form-with-jquery-ajax-only-works-every-other-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!