Home > Software engineering >  WordPress: Content in foreach remains on page because it does not refresh on form submission | Reloa
WordPress: Content in foreach remains on page because it does not refresh on form submission | Reloa

Time:11-09

I have tried the javascript refresh options on submit (on the <form> but none of them work. If I put the javascript refresh with the submit function, then every time it refreshes, the item gets sent to the database (do not want that).

What I have tried onsubmit="location.reload()"
onsubmit="window.location.reload()"
onsubmit="setTimeout(function () { window.location.reload(); }, 10)"

It currently renders an array of items with a checkbox. When I click the checkbox, the item gets sent to the database as read -- but it stays on the screen (unless I revisit the page manually in the address bar). I am developing in WordPress using PHP.

Perhaps there is a small trick we can use just to remove the array that is sent on submit out of the books_array as soon as the submit button is clicked? Or reload the books_array after submission?

Here is my code: form function

<form action="<?php user_add_new();?>" method="post">
<?php
foreach($books_array as $index => $i ) {
    $s = $i->title;
    $o = $i->listID;
    $r = $i->submittedBy;
    $d = $i->bookDESC;
    $t = $i->id;
    $current_user = wp_get_current_user();
    $current_id = $current_user->ID;

    if ($r == $current_user->ID || $r == 'administrator') {
        echo '<div >';
            echo '<div >';
                echo '<!---entire checkbox--->';
                echo '<div><span >';
                    echo "<input type='checkbox' name='checkbox[]' value='$index' onChange='this.form.submit()'>";
                    echo "<input type='hidden' name='item$index' value='$t'>";
                    echo "<input type='hidden' name='listID$index' value='$o'>";
                    echo "<input type='hidden' name='userID$index' value='$current_id'>";
                echo '</span></div>';
                echo '<!---entire checkbox--->';
                echo '<!---info from book--->';
                echo "<div><b>$s</b><br>$d</div>";
                echo "<!---info from book--->";
            echo '</div>';
        echo '</div>';
    }
};
?>
</form>

foreach loop

function user_add_new() {
    global $wpdb;

    $value = $_POST["checkbox"][0];
    $bookTOadd = $_POST["item" . $value];
    $listTOadd = $_POST["listID" . $value];
    $userID = $_POST["userID" . $value];

    $addTABLE = $wpdb->prefix . 'plugin_read';

    $wpdb->insert(
        $addTABLE,
        array(
            'bookID' => $bookTOadd,
            'userID' => $userID,
            'listID' => $listTOadd,
        )
    );
}

I keep running into issues, but I am so grateful to anyone who can give a little insight on how to approach this best. Thank you for taking the time to read this!

CodePudding user response:

Problem fixed by creating a WordPress action and calling/rendering it only when the form is clicked (since before the action was rendered on page load just not executed until the click, which was 1 thing causing my issue re the not refreshing the entire page after form submission). No ajax (though its great with wordpress) nor .php files (that would just be a workaround).

Removed the action="" from my form, since we'll be using wordpress to do this.

Added this line <?php wp_nonce_field('book_send', 'book_send_nonce', true, true);?> to my form, you can see that below (this will help call my action in my WordPress file, associating it with this form)

<form method="post">
<?php wp_nonce_field('book_send', 'book_send_nonce', true, true);?>
<?php
foreach($books_array as $index => $i ) {
    $s = $i->title;
    $o = $i->listID;
    $r = $i->submittedBy;
    $d = $i->bookDESC;
    $t = $i->id;
    $current_user = wp_get_current_user();
    $current_id = $current_user->ID;

    if ($r == $current_user->ID || $r == 'administrator') {
        echo '<div >';
            echo '<div >';
                echo '<!---entire checkbox--->';
                echo '<div><span >';
                    echo "<input type='checkbox' name='checkbox[]' value='$index' onChange='this.form.submit()'>";
                    echo "<input type='hidden' name='item$index' value='$t'>";
                    echo "<input type='hidden' name='listID$index' value='$o'>";
                    echo "<input type='hidden' name='userID$index' value='$current_id'>";
                echo '</span></div>';
                echo '<!---entire checkbox--->';
                echo '<!---info from book--->';
                echo "<div><b>$s</b><br>$d</div>";
                echo "<!---info from book--->";
            echo '</div>';
        echo '</div>';
    }
};
?>
</form>

And this is my action (steps are described in the notes within the code) which makes the post when the action is called upon submit. It only submits the data after form validation. Once the data has been submitted, it then reloads the page using a built in WP function:

add_action('book_check', function() {
   if ( ( is_single() || is_page() ) &&
        isset($_POST[book_send_nonce]) &&
        wp_verify_nonce($_POST[book_send_nonce], 'book_send')
    ) {
      // form validation
    function validate_book_data(){
        $errors = new WP_Error();

        if (isset($_POST[ 'item' ]) && $_POST[ 'item' ] !== '') {
            $errors->add('item_error', 'Book not selected');
        }

        if (isset($_POST[ 'listID' ]) && $_POST[ 'listID' ] == '') {
            $errors->add('list_error', 'No valid list this belongs to.');
        }

        if (isset($_POST[ 'userID' ]) && $_POST[ 'userID' ] == '') {
            $errors->add('user_error', 'Not signed in');
        }
        return $errors;
    }
      // If form validation passes, send the info
      $pass_validation = validate_book_data($_POST);
      if ( $pass_validation ) {
        $value = $_POST["checkbox"][0];
        $data = array(
          'userID' => $_POST["userID" . $value],
          'bookID' => $_POST["item" . $value],
          'list' => $_POST["listID" . $value],
        );
        global $wpdb;
        // Select the table to post the data to
        $book_checked = $wpdb->prefix . 'plugin_read';
        // Insert the data to the table
        $wpdb->insert($book_checked, $data, '%s'); 
        // Set page refresh
        $refresh_page = wp_redirect($_SERVER['HTTP_REFERER']);
        // After data is inserted, refresh the page
        wp_safe_redirect( $refresh_page );
        // and exit
        exit();
      }
   }
});

Using this action solves the issue of the page not refreshing because the action is only called when the checkmark is clicked and within the action, I refresh the page only after the data has sent.

I hope this will help anyone else with the issue. Coding from 8am-2am lately really had my brain become mush so the solution took me a short bit.

  • Related