简体   繁体   中英

How can I avoid submit input to redirect on ajax form submission? PHP

The HTML is a post loading dynamically inside a modal popup, I just realized that when I submit the form directly in the post it works but doesn't work inside the modal:/

Everytime I submit the form from the modal I'm redirected to the post page.

This is my PHP template which has the AJAX and the html code.

<?php get_header(); ?>

<script>
    jQuery(document).ready(function($){
        $(document).on("submit","#couponform",function(event){
            console.log("hola");
            event.preventDefault();
            var code =  $("#promocode").val(); console.log(code);
            $.ajax({
                type: 'POST',
                url: '/wp-content/themes/buddyboss-theme-child/cpt-functions.php',
                data: {"code": code},
                success: function(data){
                    console.log(data);
                    $('#submit').html(data);
                },
                error: function(jqxhr, status, exception) {
                    alert('Exception:', exception);
                }
            });
            return false;
        });
    });
</script>

<div id="modal-ready">
    <main id="main" class="site-main" role="main" style="width: 70%; margin: auto;">
        <?php
        while ( have_posts() ) : the_post();
        ?>
            <h2 style="text-align: center;">Earn Opportunity</h2>

            <div class="featured-image"><?php the_post_thumbnail(); ?></div>

            <?php
            if ( get_field('require_code_input') ){
            ?>
                <form method="post" id="couponform" action="">
                    <input type="text" placeholder="Enter Promo Code" name="promocode" id="promocode">
                    <div class="action-container" style="display: flex; width: 100%; margin: auto;">
                    <div class="custom-fields" style="width: 50%; line-height: 1.3; text-align: center; vertical-align: middle; margin: auto;">
                        <?php echo 'Earn' . '<br>'; ?>
                        <?php echo '+' . get_field('points', $current_post_id) . 'pts'; ?>
                    </div>
                    <div class="button-container" style="width: 50%;">
                        <input name="submit" type="submit" value="Submit" id="submit">
                    </div>
                </form>
            </div>
            <?php
            }else{            
            ?>

            <div class="action-container" style="display: flex; width: 100%; margin: auto;">
                <div class="custom-fields" style="width: 50%; line-height: 1.3; text-align: center; vertical-align: middle; margin: auto;">
                    <?php echo 'Earn' . '<br>'; ?>
                    <?php echo '+' . get_field('points', $current_post_id) . 'pts'; ?>
                </div>
                <div class="button-container" style="width: 50%;">
                    <button onclick="window.location.href='https://w3docs.com';" style="width: 100%; background-color: #FFC51C; color: #ffffff; border-radius: 0; margin: 5% auto;"> GO TO SITE </button>
                </div>
            </div>
            <?php
            }
            ?>

            <h2 class="title"><?php the_title(); ?></h2>

            <div class="content">
                <div id="excerpt"><?php the_excerpt(); ?></div>
                <div id="text-content" style="display: none;"><?php the_content(); ?></div>
                <p class="link-container"><a id="show-more">READ MORE</a></p>
            </div>            

        <?php
        endwhile;
        ?>

    </main><!-- .site-main -->

</div><!-- #modal-ready -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

and this is my cpt-functions.php

    <?php
    if(!empty($_POST)){
      $code = $_POST['code'];
      echo "code :".$code;
    } 
    ?>

SOLVED: Changing the jQuery function embed in the code to the.js file solved my problem.

An id must be unique.

You are running a while loop to render all posts. In each post, there will be some elements with non-unique id . Just DO NOT use ids in a loop. replace all of them with a class.

Then, the jQuery would slightly change to target the classes from the submited form.

PHP part to change:

if ( get_field('require_code_input') ){
?>
    <form method="post" class="couponform" action="">
        <input type="text" placeholder="Enter Promo Code" name="promocode" class="promocode">
        <div class="action-container" style="display: flex; width: 100%; margin: auto;">
        <div class="custom-fields" style="width: 50%; line-height: 1.3; text-align: center; vertical-align: middle; margin: auto;">
            <?php echo 'Earn' . '<br>'; ?>
            <?php echo '+' . get_field('points', $current_post_id) . 'pts'; ?>
        </div>
        <div class="button-container" style="width: 50%;">
            <input name="submit" type="submit" value="Submit" class="submit">
        </div>
    </form>
</div>
<?php
}

The jQuery:

jQuery(document).ready(function($){
    $(document).on("submit",".couponform",function(event){
        console.log("hola");
        event.preventDefault();
        var code =  $(this).find(".promocode").val(); console.log(code);
        var theInput = $(this).find('.submit')
        $.ajax({
            type: 'POST',
            url: '/wp-content/themes/buddyboss-theme-child/cpt-functions.php',
            data: {"code": code},
            success: function(data){
                console.log(data);
                theInput.val(data); // That is an input! so .val() should be used instead of .html()
            },
            error: function(jqxhr, status, exception) {
                alert('Exception:', exception);
            }
        });
        return false;
    });
});

Note that this will change the submit button text from "Submit" to the promocode that was submitted... Quite weird... But maybe that is a test you do. ;)

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