Rick Helston
Rick Helston

Reputation: 763

Retrieving Data with jQuery AJAX Without Reloading Page

I have this jQuery AJAX code that retrieves data from a MySQL database. It works without reloading the page, the problem is that it only works the first time. If I submit the form again, then the whole page reloads. How can I make it so I can submit the form multiple times and retrieve the data without reloading the page?

jQuery

$(document).ready(function() {
    $('form').on('change', function() {
        $(this).closest('form').submit();
    });

    $('form').on('submit', function(event) {
        event.preventDefault();
        $.ajax({
            url: $(this).attr('action'),
            type: $(this).attr('method'),
            data: $(this).serialize(),
            success:function(data) { $('form').html(data); }
        });
    });
});

HTML

<form action="form.php" method="post" id="cars">
    <select name="id">
        <option value="">Selection...</option>
        <option value="1" <?php echo (isset($id) and $id == 1) ? 'selected' : '';?>>Chevy</option>
        <option value="2" <?php echo (isset($id) and $id == 2) ? 'selected' : '';?>>Ford</option>
        <option value="3" <?php echo (isset($id) and $id == 3) ? 'selected' : '';?>>Dodge</option>
    </select> 
</form>

Upvotes: 0

Views: 10417

Answers (1)

Rahul DSouza
Rahul DSouza

Reputation: 56

Please do not use submit, instead use change function

<script type="text/javascript">
$(document).ready(function() {
    $('form').on('change', function() {
        $.ajax({
            url: 'form.php',
            type: 'post',
            data: {'id':jQuery('select[name=id]').val()},
            success:function(data) { $('form').html(data); }
        });
    });
});
</script>

Upvotes: 1

Related Questions