AJAX PHP - Reload div after submit

864 views Asked by At

I'm trying to reload a select with jquery and ajax, this select must be reload after I submit a new entry, right now I reach this point.

$("form").on("submit", function (e) {
    e.preventDefault();
    var form_id = $(this).attr('id');
    var form_details = $('#' + form_id);
    $.ajax({
        type: "POST",
        url: 'Users.php',
        data: form_details.serialize(),
        success: function (data) {
            $('#check_data').html(data);
            $('#div_to_update').load('my_page.php #div_to_update');
        }
    }
});

The div to be reloaded has a html select generate by a php code, the other fields are just plain html:

This is the first form, that must be reloaded with the values I enter in the form2:

<div id="div_to_update">
    <form id="form1">
        <?php Helper::combo_users(); ?>
        /*
        ...
       */
    </form>
</div>

This is the form 2:

<form id="form2" method="post">
    <input type="text" id="user_reg" name="user_reg"/>
    <input type="text" id="user_name" name="user_name"/>
    <input type="submit" value="Add"/>
</form>

The odd thing is, this code will run the first time ok(I enter the values in the form2 and send, the form1 will reload with the new value), but the second time it does not work(when I click submit on the form2 nothing seems to happen) and the third time it will work again (click the submit button again and the value is send and the form 1 is reloaded) and so on.

1

There are 1 answers

0
Alex On

Simply you are not working for second time since you are serializing a form which is dynamically updated within ajax.

jQuery won't serialize when you load a form elements such as inputs dynamically.

You're solution can be loading your new values with JSON object, and put in a foreach to display new content.