w3m
w3m

Reputation: 11

Ajax works after I press submit twice

Very brief, this is my php code in myPage.php:

<div class="table-responsive" id="items">
 <table class="table" id="myTable">
  <thead><tr><th>item<th>status<th>options</thead>
   <tbody>
    [...]
    echo "<tr><td>$item<td>$status<td>to-be-added
    [...]
    echo "<tr><td colspan='3'>";
    echo "<form method='post' id='newitem'>";
    echo "<input type='hidden' id='uid' name='uid' value='$uid'>";
    echo "<div><button type='submit' class='btn btn-info' id='submitbtn'>new item</button></div>";
    echo "</form>";
[...]

And this is my .js file ajax code:

$(document).ready(function () {
    $('form').submit(function (event) {
        $('#errors').remove(); // remove the error text
        $('#success').remove(); // remove the success text
        var formData = $("#newitem").serialize();
        $.ajax({
            type: 'POST',
            url: 'process.php',
            data: formData,
            dataType: 'json',
            encode: true
        })
                .done(function (data) {
                    console.log(data);
                    if (!data.success) {
                        $('form').append('<div id="errors" class="alert alert-warning"></div>');
                        if (data.errors.validitem) {
                            $('#errors').append('<p>' + data.errors.validitem + '</p>');
                        }
                    } else {
                        $('#addresses').append('<div id="success" class="alert alert-success">' + data.message + '</div>');
                        $("#myTable").load("mypage.php #myTable");
                    }
                })
                .fail(function (data) {
                    console.log(data);
                });
        event.preventDefault();
    });
});

I Don't show the process.php function as that is not most likely the problem.

  1. When I first load the page and press submit following things happen:
    • a new item is created via ajax
    • table gets populated with new entry w/o page refresh but using the load option: *$("#myTable").load("mypage.php #myTable");*
    • in conclusion, everything works as expected!

Note: only after I add the table load the problem appears. $("#myTable").load("mypage.php #myTable"); Without this reload of the table after submit, submit always work, just that the table doesn't show real time the changes and I need to do F5 ... which is not the plan.

  1. After the load of the table, when I press the button again, nothing appears to happen, except that my success message disappears.

  2. At this stage I need to press the button twice. Only after I press submit a second time, the ajax executes ok and table shows the new item created. This behavior is consistent for all next submits. All execute only after second submit.

I need some help here please. What is happening?

I want to reload only a section of the myPage.php, so only the full table #myTable or whole div #items, with all the validation functions I have in myPage.php I don't want to recreate full table in the process.php and send it over via POST as I have seen some recommend in other forums.

Upvotes: 0

Views: 119

Answers (1)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33943

The issue is here : $("#myTable").load("mypage.php #myTable");

mypage.php is your main page. And you load it once. Then, inside the table, you use that .load() to overwrite it all. Which is no good.

You then have a brand new table where no handler is binded to the submit button. So on submit button click (second time), the form is submitted using the "normal behavior" of a <form> element... And the page is fully reloaded.

As a possible solution, I would use .load() on the form... Not the table, like this:

$("#newitem").load("mypage.php #newitem");

But you should try $("#newitem").reset() and just remove #error and #success... Instead of that .load().


EDIT
Second taugth:

Try $(document).on("submit", "form", function (event) {
instead of $('form').submit(function (event) {

That is delegation... So your submit button always will be binded to the function, even if it is overwritten.

Upvotes: 1

Related Questions