简体   繁体   中英

Submitting form via POST with jQuery and Ajax

I am trying to POST data from a form using jQuery & Ajax. However, when I check on my PHP to see if the form has been "submitted", it shows it has not because the MySQL code does not run. I am guessing my HTML is not setup correctly and therefore the Ajax request is not sending the data to my post-update.php script. Here is my code:

<script type="text/javascript">
    $(document).ready(function() {
        $('#ajax-remove-completion-date').click(function() {
            $.ajax({
                type:'POST',
                url:'post-update.php',
                data: dataString,
                success: function(response) {
                 $('#success-remove-completion-date').removeClass('hidden');
                }
            });
        });
    });

HTML:

<form action="">
    <div id="myModal1" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel1" aria-hidden="true">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
            <h3 id="myModalLabel3">Remove Completion Date</h3>
        </div>
        <div class="modal-body">
            <p>Are you sure you want to remove the students Completion Date?</p>
        </div>
        <div class="modal-footer">
          <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
          <button class="btn blue" data-dismiss="modal" id="ajax-remove-completion-date">Yes</button>
          <input type="hidden" name="submitted" value="remove-completion-date" />
        </div>
    </div>
</form>

PHP:

<?
session_id();
session_start();

require_once('assets/includes/mysql-connect.php');

/*Check to see if the completion date is being removed*/
if ($_POST['submitted'] == 'remove-completion-date') {
    $query = "UPDATE students SET completion_date = NULL, completed = NULL WHERE student_id = {$_SESSION['student_id']} LIMIT 1";
    $result = mysqli_query($dbc, $query);
} 
?>

Where does dataString come from?

It's better if you define the data you want to send as an object. It's more readable and it's automatically converted to a query String.

$(document).ready(function() {
    $('#ajax-remove-completion-date').click(function() {
        $.ajax({
            type:'POST',
            url:'post-update.php',
            data: {
                submitted: 'remove-completion-date'
            },
            success: function(response) {
                $('#success-remove-completion-date').removeClass('hidden');
            }
        });
    });
});

If you want to take the value from the field, set submitted as:

$('input[name="submitted"]').val()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM