简体   繁体   中英

Post array from form using xmlhttprequest

I have an php generated table/form with checkboxes like this:

    if ($query) {
if (!mysqli_num_rows($query)) {
    //Empty storage
    echo "There are no items in '$storage'.";
    exit();
} else {
    //form
    echo "<form name='send_parts_form' action='../includes/generatetab.php' method='post'>";
    //Table header
    echo "
        <table>
        <tr>
            <th>Part</th>
            <th>PN</th>
            <th>Manufactured</th>
            <th>Serial</th>
            <th>Site</th>
            <th>Date replaced</th>
            <th>By user</th>
            <th>Faulty</th>
            <th>Send</th>
            <th>Select</th>
        </tr>";
    //Retrieved data
    while ($row = mysqli_fetch_array($query)) {
        echo "<tr>";
        echo "<td>" . $row['part_type'] . "</td>";
        echo "<td>" . $row['pn'] . "</td>";
        echo "<td>" . $row['manufactured'] . "</td>";
        echo "<td>" . $row['serial'] . "</td>";
        echo "<td>" . $row['site_id'] . "</td>";
        echo "<td>" . $row['date'] . "</td>";
        echo "<td>" . $row['user'] . "</td>";
        echo "<td>" . $row['faulty'] . "</td>";
        echo "<td><input type='checkbox' name='send_parts[]' class='checkclass' value=" . $row['id'] . "></td>";
        echo "</tr>";};
    echo "</table>";
    echo "</br>";
    echo "</br>";
    echo "<input type='button' onclick='sendToZG()' value='Send'/>";
    echo "</br>";
    echo "<input type='submit' name='submit' value='Generate tab' />";
    echo "</form>";
    exit();
}
    } else {
    die("Query failed");
   }

User then checks option they want and upon submiting (Generate tab) they get tab delimited text with values they selected. I now want when they click "Send" to have values posted to another php page and results returned on the same page (under SentList div). I have js like this:

    //Browser Support Code
    function sendToZG(){
var ajaxRequest;  // The variable that makes Ajax possible!

    try{
    // Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
    }catch (e){
    // Internet Explorer Browsers
    try{
    ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    }catch (e) {
    try{
     ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }catch (e){
     // Something went wrong
     alert("Your browser broke!");
     return false;
    }
    }
    }

    ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
    var ajaxDisplay = document.getElementById('SentList');
    ajaxDisplay.innerHTML = ajaxRequest.responseText;
    }
    }

    // Now get the value from page and pass it to server script.
    var formData = new FormData( document.getElementsByName("send_parts")[0] );
    ajaxRequest.open('POST', "../includes/sendtozg.php", true);
    ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    ajaxRequest.send("send_parts=" + formData);
    }

Edited: ajaxRequest.send("send_part=" + formData); to ajaxRequest.send("send_parts=" + formData); Now it returns:

Invalid argument supplied for foreach() on line 53 (That is where I fetch my data in sendtozg.php).

I'll add sendtozg.php at the end of the post.

If instead of:

    <form name='send_parts_form' action='../includes/generatetab.php' method='post'>

I echo:

    <form name='send_parts_form' action='../includes/sendtozg.php' method='post'>

Upon submit, script sendtozg.php gets executed fine but on a different page.

So basically what I'm trying to do is to have 2 options for the php generated form:

  1. Generate tab delimited txt file
  2. Execute sendtozg.php and return results on same page

I already have both scripts (generatetab.php and sendtozg.php) and they work fine.

sendtozg.php:

    if (!empty($_POST['send_parts'])){
foreach ($_POST['send_parts'] as $send_parts){
$getchecked = mysqli_query($con, "SELECT * FROM $storage WHERE id=$send_parts");
while ($row = mysqli_fetch_array($getchecked)) {
    $copypart = mysqli_query($con, "INSERT INTO sent_parts (part_type, pn, manufactured, serial, site_id, date, user, faulty, log)
                                    SELECT part_type, pn, manufactured, serial, site_id, date, user, faulty, log 
                                    FROM $storage WHERE id=$send_parts");                                       

    // check to see if it copied
    $getserial = mysqli_query($con, "SELECT serial FROM $storage WHERE id=$send_parts");
    $getserial_row = mysqli_fetch_array($getserial, MYSQLI_NUM);
    $foundserial = $getserial_row[0];
    $checkcopy = mysqli_query($con, "SELECT id FROM sent_parts WHERE serial = '$foundserial'");

    // add user info and date
    $addinfo = mysqli_query($con, "UPDATE sent_parts SET sent2zg='$user', date2zg='$strdate' WHERE serial = '$foundserial'");

    if (!$check1_res) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
    };

    //delete from storage
    if($checkcopy > 0) {
        $getpart = mysqli_query($con, "SELECT part_type FROM sent_parts WHERE serial='$foundserial'");
        $getpart_row = mysqli_fetch_array($getpart, MYSQLI_NUM);
        $deletedpart = $getpart_row[0];
        $removepart = mysqli_query($con, "DELETE FROM $storage WHERE id = '$send_parts'");
        echo "Part " . $deletedpart . " has been transfered";
    } else {
        echo "Part " . $row['part_type'] . "was NOT transfered";
    };      
};
    } exit ();
    } else {
echo "Nothing was selected, please try again!";
    }

Your <form> doesn't have an id attribute on it so you'll either need to add id="send_parts" to the <form> or you'll need to change your code from getElementById to getElementsByName like this:

// Now get the value from page and pass it to server script.
// Serialize the data
var formData = new FormData( document.getElementsByName("send_parts")[0] );
ajaxRequest.open('POST', "../includes/sendtozg.php", true);
ajaxRequest.send(formData);

Then inside sendtozg.php you'll need to change the first two lines to:

if (!empty($_POST)){
  foreach ($_POST as $send_parts){

This is the final code for the sendtozg.js:

// Get get the value from page and pass it to server script.
var formData = new FormData( document.getElementsByName("send_parts")[0] );

ajaxRequest.open('POST', "../includes/sendtozg.php", true);
ajaxRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
ajaxRequest.send(formData);
}

and sendtozg.php should be:

    if (!empty($_POST)){
    foreach ($_POST['send_parts'] as $send_parts){
    $getchecked = mysqli_query($con, "SELECT * FROM $storage WHERE id=$send_parts");

By the way:

    print_r ($some_array)

and

    if (!$check1_res) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
    };

Are great tools for troubleshooting.

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