Ryan Ryan - 4 months ago 8
Ajax Question

AJAX JQuery form submit only works once( requires page refresh)

When the page loads I can retrieve one result, but when I change the inputs and try to repopulate the update_form I receive nothing. Any ideas? When I check the parameters the browser is receiving the new parameters, but apparently the query is not be run again.

$(function() {
$("#select_form").submit(function (e) {
e.preventDefault();
$.ajax({
url: 'select_price.php',
data: $('#select_form').serialize(),
type: 'POST',
success: function (data) {
console.log(data);

if(data){
$("#update_form").html(data);
$("#norecord").css('display','none');

}
else{
$("#norecord").css('display','block');

}

},


});

});
});


My HTML

<form action="" method="post" id="select_form"><select style="max-width: 125px;border-radius:5px;" class="form-control" name="cus_no" autocomplete="off">
<?php

$sql = "SELECT DISTINCT debcode FROM cicmpy WHERE cicmpy.region IS NOT NULL";
$query = odbc_exec($conn, $sql);
while ($row = odbc_fetch_array($query)) {
echo '<option value="' . ($row['debcode']) . '">' .($row['debcode']) . ' </option>';
}


?>

</select ></div><label>Item Number</label><input style="max-width: 125px; border-radius:5px;" type="text" class="form-control" id="auto_item" name="item_no"/>
<button style="margin-top: 15px;" type="submit" name="update" class="btn btn-primary">Manage</button>
<button style="margin-top: 15px;" type="button" name="new_price" id="new_price" class="btn btn-success pull-right">New Price</button></div>
</div> </div>
</div>
</div>
</form>

Answer

First, in your HTML, give your button an id="btn_manage" and remove the type="submit", otherwise you're just POSTing the form (which is why your page is refreshing) instead of using AJAX. In your Javascript, get rid of the $("#select_form").submit(function (e) { stuff and simply register an event handler for the button itself, which will run the AJAX.

Update the HTML and then try this:

<script>
    $(function() {
        $("#btn_manage").on("click", function () {
            $.ajax({
                url: 'select_price.php',
                data: $('#select_form').serialize(),
                type: 'POST',
                success: function (data) {
                    console.log(data);

                    if(data){
                        $("#update_form").html(data);
                        $("#norecord").css('display','none');

                    } else {
                        $("#norecord").css('display','block');

                    }

                },
                error: function(data) {
                    console.log("Error: " + data)
                }
            });
        });
    });

    </script>