简体   繁体   中英

Send multidimensional form array via .ajax post to PHP prepared statement

I understand how to send this form normally with a regular submit. I however am confused as to how to send my multidimensional form array via .ajax.

My form:

<form action="week_update.php" id="theform" method="post">   
 <input type="text" name="data[][wednesday_crew]" value=""/>
 <input type="text" name="data[][thursday_crew]" value=""/>
 <input type="text" name="data[][friday_crew]" value=""/>
 <input type="text" name="data[][saturday_crew]" value=""/>
 <input type="text" name="data[][sunday_crew]" value=""/>

My PHP:

$stmt = $connection->stmt_init();

if($stmt->prepare("UPDATE tableName SET ... = ?, ... = ?,)) {

// Bind your variables
$stmt->bind_param('ss', $.., $..,);

// get the multi array from form
$returnedData = $_POST['data'];

//let's loop through it.
for($i=0;$i<count($returnedData);$i+=2){
  $log_dates_ID = $returnedData[$i]['...'];
  $crew_chief = $returnedData[$i+1]['...'];
  $stmt->execute();
}

This is relatively easy, if i have understood you correctly. I answered a question similar to this a while back.

$("#theform").submit(function() {

    var url = "path/to/your/script.php"; // the script where you handle the form input.

    $.ajax({
           type: "POST",
           url: url,
           data: $("#theform").serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // show response from the php script.
           }
         });

    return false; // avoid to execute the actual submit of the form.
});

You've almost got it, but your input elements should be

<input .... name="data[friday_crew][]" />
                                   ^^--

That'll produce a sub-array under `data for every type you've got. Right now yours will be build some hideous franken-array that'll be really ugly to traverse/analyze. By comparison, the above version you can simply have

foreach($_POST['data']['friday_crew'] as $key => $val) {
    $fri_crew = $val;
    $sat_crew = $_POST['data']['sat_crew'][$key];
    etc...
}

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