user3735411
user3735411

Reputation: 43

Ajax not working when submitting twice

Hello and thank you for reading!

First things first, so here is my setup:

This is the script:

var jq = $.noConflict();
jq(function () {

    jq('form').on('submit', function (e) {

        e.preventDefault();

        var page = jq(this).attr("page");

        jq.ajax({
            type: jq(this).attr("method"),
            url: jq(this).attr("action"),
            data: jq(this).serialize(),
            success: function (data) {
                jq('#' + page + '-content').html(data);
            }
        });

    });

});

This is the form:

<form action="content/stuff.php" method="post" page="p5">
    <input type="hidden" name="p5-submit-1" />
    <input type="image" style="margin-top: 20px;" src="images/send.png" />
</form>

I am running into the problem that sometimes when clicking the send button, the whole page is redirected to content/stuff.php and sometimes only the wanted content inside the div (p5-content) responds to the form. I want only the content of the p5-content to be replaced.

Also when it worked and different content is then loaded into p5-content which contains another (similar) form, the whole page changes to content/stuff.php when clicking this second form.

Additionally I am wondering why the script doesn't work if it is in the <head> part of my index.php.

Summary:

Upvotes: 0

Views: 970

Answers (1)

AJ Richardson
AJ Richardson

Reputation: 6830

Where does the p5-content element land in your hierarchy? If the <form> is a child element of p5-content, then your original form (which you assigned a submit handler to) will be replaced with a new, identical <form>, which does not have any submit handler tied to it. That would explain why it is posting the entire page, since e.preventDefault(); is no longer getting called.

To fix this, find a way to NOT replace the entire <form> with your ajax call. This is better anyways because it means you are sending less data with every ajax postback. Alternatively, if you really must replace the entire <form>, re-add the submit event handler at the end of the ajax callback.

As for why your script doesn't work in the <head>, it may be because your script is running before jQuery is included (I'm not sure where you are including jQuery). Since the HTML parser will block while it is waiting for scripts to load, you probably want to load all your scripts at the end of the <body>, anyways, to make your content load faster. You can also use the async attribute as described in this post, but this won't guarantee that your scripts will load in the right order, so I wouldn't recommend it in your case. Or, if you really care about optimizing your load time and want to put in some work, have a look at this article.

Upvotes: 1

Related Questions