Skip to content
Advertisement

Pass form data to PHP script with jquery [closed]

I have the following form I’ve been working on.

Now, I’m unsure how to grab the form data and push it to my update.php script.

I’d like my update.php script to loop through the rows in index.php and output the account_name value for each.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div id="exampleTable" class="row effects text-center">
     <div class="col-md-12">
        <table id="example" class="table table-striped">
            <thead>
                <tr>
                    <th class="tg-yw4l">Reference</th>
                    <th class="tg-yw4l">Account Name</th>
                </tr>
            </thead>
            <tbody>
                <tr class="row-id-139">
                    <td class="tg-yw4l">123</td>
                    <td class="tg-yw4l"><input type="text" class="account_name" value="John Johnson"></td>
                </tr>
                    
                <tr class="row-id-140">
                    <td class="tg-yw4l">123</td>
                    <td class="tg-yw4l"><input type="text" class="account_name" value="Jack Thomson"></td>
                </tr>            
            </tbody>
        </table>
    </div>
</div>
<p>&nbsp;</p>
<form action="" method="post" class="revise">
    <input id="btnSubmit" type="submit" class="btn btn-success btn-lg btn-xl" value="Update"/>
</form>
<div class="refund-content"></div>

<script type="text/javascript">
$('.revise').submit(function (e) {
    e.preventDefault();
    e.stopImmediatePropagation();

    var data = new FormData();

    // process the form
    $.ajax({
        type: 'POST',
        url: 'update.php?action=edit',
        data: data,
        dataType: 'text',
        cache: false,
        contentType: false,
        processData: false,
        complete: function (data) {
            $('.refund-content').html("<br><div class='alert alert-success' role='alert'>Updated.</div>");
            console.log(data);
        }
    })
});
</script>

Advertisement

Answer

As mentioned in my comment and depending on your intention behind the form submission, you would want to use the <form> to allow for jQuery to serialize() and submit the data to the specified URL.

Below I use a pseudo database result as the $accounts array, in order to output each of the accounts within your form.

I also optimized the code based on standard practices such as escaping the database values using htmlentities or htmlspecialchars being output in your HTML code, to ensure they do not break the DOM with the single or double quotes.

/index.php

<?php 
//psuedo database values

$accounts = array(
    array('id' => 1, 'name' => 'John Johnson'),
    array('id' => 2, 'name' => 'Jack Thomson'),
);

?>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<form action="/update.php?action=edit" method="post" class="revise">
    <div id="exampleTable" class="row effects text-center">
        <div class="col-md-12">
            <table id="example" class="table table-striped">
                <thead>
                <tr>
                    <th class="tg-yw4l">Reference</th>
                    <th class="tg-yw4l">Account Name</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($accounts as $i => $account) { ?>
                <tr class="row-id-<?php echo $i; ?>">
                    <td class="tg-yw4l"><?php echo $account['id']; ?></td>
                    <td class="tg-yw4l"><input type="text" name="account[<?php echo $account['id']; ?>]name" class="account_name" value="<?php echo htmlspecialchars($account['name'], ENT_QUOTES, 'UTF-8'); ?>"></td>
                </tr>
                <?php } ?>
                </tbody>
            </table>
        </div>
    </div>
    <p>&nbsp;</p>

    <button id="btnSubmit" type="submit" class="btn btn-success btn-lg btn-xl">Update</button
</form>
<div class="refund-content" style="display:none;">
    <br><div class='alert alert-success' role='alert'>Updated.</div>
</div>

<script type="text/javascript">
jQuery(function($) {
    var editForm = $('form.revise');
    editForm.on('submit', function (e) {
        e.preventDefault();
        e.stopImmediatePropagation();

        $('.refund-content').hide();
        var data = editForm.serialize();
        var url = editForm.attr('action');

        // process the form
        $.ajax({
            type: 'POST',
            url: url,
            data: data,
            cache: false,
        }).done(function (response) {
           $('.refund-content').show();
           console.log(response);
        });
    });
});
</script>

Now you can retrieve the $_POST results in update.php.

/update.php

//debugging
var_dump($_POST);
/* should output:
array(
    'account' => array(
        '1' => ['name' => 'John Johnson'],
        '2' => ['name' => 'Jack Thomson'],
    )
);
*/

//processing
if (isset($_GET['action']) && 'edit' === $_GET['action']) {
   if (!empty($_POST) && array_key_exists('account', $_POST)) {
      foreach ($_POST['account'] as $id => $account) {
          echo $id . ' ' . $account['name'] . PHP_EOL;
      }
   }
}

Special considerations: PHP by default has a limited amount of input values that can be requested at one time. Please update your form pagination or PHP max_input_vars and post_max_size configuration accordingly to prevent missing data.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement