0

I'm trying to make a multi-step forms with radio buttons, which will be used to filter some custom posts. Here you can see an example. Right now, once the user complete and submit the form, the page re-charge and the results appear just below the form. What I'd like to achieve is to output the results instead of the form and to keep the sidebar tag filter, which right now disappear on form submit.

Here my php code:

    <?php  global $wp;
    $current_url = home_url( add_query_arg( array(), $wp->request ) );?>
        <div id="res-cont" class="container">
            <div id="bloccoton" class="row sw-main sw-theme-arrows">
                <ul id="progressbar" class="nav nav-tabs step-anchor">
                    <li class="nav-item done"><a href="#step-1" class="nav-link">Cloud di interesse</a></li>
                    <li class="nav-item"><a href="#step-2" class="nav-link">Livello di esperienza sulla piattaforma</a></li>
                    <li class="nav-item"><a href="#step-3" class="nav-link">Ruolo nell'utilizzo di Salesforce</a></li>
                    <li class="nav-item"><a href="#step-4" class="nav-link">Modalità di eorgazione del corso</a></li>
                    <li class="nav-item"><a href="#step-5" class="nav-link">Corsi</a></li>
                </ul>
                <div class="intro">
                    Stai già utilizzando uno dei prodotti di Salesforce? O lo farai nel prossimo futuro? Diventa un esperto di Salesforce, scegli di specializzarti nel tuo Cloud di riferimento e costruisci il tuo percorso di crescita all’interno dell’azienda.
                </div>
                <div class="col-md-3">
                    <div id="corsi-res">
                        <div class="filtro">
                            <p style="font-weight:bold; text-align:center;padding:25px 0;">My Training</p>
                            <div class="scelt-con prod">

                                <p id="prodotto"></p>
                                <input type="button" id="uno" class="del" name="del" value="X">
                            </div>
                            <div class="scelt-con liv">
                                <p id="livello"></p>
                                <input type="button" id="due" class="del" name="del" value="X">
                            </div>
                            <div class="scelt-con role">
                                <p id="ruolo"></p>
                                <input type="button" id="tre" class="del" name="del" value="X">
                            </div>
                            <div class="scelt-con sta">
                                <p id="stato"></p>
                                <input type="button" id="tre" class="del" name="del" value="X">
                            </div>
                        </div>


                    </div>

                </div>
                <div class="col-md-9">
                    <form id="msform" method="post">
                        <!-- progressbar -->

                        <!-- fieldsets -->
                        <fieldset class="con-img">
                            <h2 class="fs-title">PRODOTTO DI RIFERIMENTO</h2>


                            <?php

$prodotto_terms = get_terms( 'prodotto', array(
      'orderby'    => 'date',
      'order' => 'DESC',
      'hide_empty' => 0
    ) );
?>
                                <?php foreach( $prodotto_terms as $term ) {
                      $term_link = get_term_link( $term );
                      echo '<label class="table-disp">';
                         if ($term->slug === 'service-cloud') {
                        echo '<img class="iconza" src="'.get_stylesheet_directory_uri().'/img/Service-cloud.png">';
                        } elseif ($term->slug === 'platform') {
                        echo '<img class="iconza" src="'.get_stylesheet_directory_uri().'/img/Platform.png">';
                         }
                             elseif  ($term->slug === 'marketing-cloud-pardot') {
                        echo '<img class="iconza" src="'.get_stylesheet_directory_uri().'/img/Marketing-cloud.png">';
                         }
                        elseif ($term->slug === 'einstein-analytics') {
                        echo '<img class="iconza" src="'.get_stylesheet_directory_uri().'/img/Einstein.png">';
                         }
                        elseif ($term->slug === 'community-cloud') {
                        echo '<img class="iconza" src="'.get_stylesheet_directory_uri().'/img/Community-cloud.png">';
                         }
                        elseif ($term->slug === 'sales-cloud') {
                        echo '<img class="iconza" src="'.get_stylesheet_directory_uri().'/img/Sales-cloud.png">';
                         }


                      echo '<input type="radio" name="prodotto" class="smoothie" value="'.$term->name.'"><span>'.$term->name.'<br><span style="font-weight:400">'.$term->description.'</span></span></label><br>';


                    }       

                ?>
                                    <input type="button" name="next" class="next action-button" value=">" />
                        </fieldset>
                        <fieldset>
                            <h2 class="fs-title">IMPOSTA IL TUO LIVELLO DI PARTENZA</h2>

                            <?php $livello_terms = get_terms( 'livello', array(
      'orderby'    => 'date',
      'order' => 'DESC',
      'hide_empty' => 0
    ) );
?>
                                <?php foreach( $livello_terms as $term ) {
                      $term_link = get_term_link( $term );
                      echo '<label class="table-disp"><input  type="radio" name="livello" class="smoothie" value="'.$term->name.'"><span>'.$term->name.'</span></label><br>';
                    }       

                ?>
                                    <input type="button" name="previous" class="previous action-button" value="<" />
                                    <input type="button" name="next" class="next action-button" value=">" />
                        </fieldset>
                        <fieldset>
                            <h2 class="fs-title">QUALE MANSIONE RICOPRI NELL’UTILIZZO DEL CRM?</h2>

                            <?php $livello_terms = get_terms( 'ruolo', array(
      'orderby'    => 'date',
      'order' => 'DESC',
      'hide_empty' => 0
    ) );
?>
                                <?php foreach( $livello_terms as $term ) {
                      $term_link = get_term_link( $term );
                      echo '<label class="table-disp"><input type="radio" name="ruolo" class="smoothie" value="'.$term->name.'"><span>'.$term->name.'</span></label><br>';
                    }       

                ?>
                                    <input type="button" name="previous" class="previous action-button" value="<" />
                                    <input type="button" name="next" class="next action-button" value=">" />
                        </fieldset>
                        <fieldset class="con-img">
                            <h2 class="fs-title">COMPLETA FLESSIBILITÀ NELLE MODALITÀ DI EROGAZIONE </h2>

                            <?php $livello_terms = get_terms( 'stato', array(
      'orderby'    => 'date',
      'order' => 'DESC',
      'hide_empty' => 0
    ) );
?>
                                <?php foreach( $livello_terms as $term ) {
                      $term_link = get_term_link( $term );
                            echo '<label class="table-disp">';
                         if ($term->slug === 'privato') {
                        echo '<img class="iconza" src="'.get_stylesheet_directory_uri().'/img/Salesforce-private-training.png">';
                        } elseif ($term->slug === 'pubblico') {
                        echo '<img class="iconza" src="'.get_stylesheet_directory_uri().'/img/Salesforce-public-training.png">';
                         }

                      echo '<input type="radio" name="stato"  class="smoothie" value="'.$term->name.'"><span>FORMAZIONE STANDARD - '.$term->name.'<br><span style="font-weight:400">'.$term->description.'</span></span></label><br>';
                    }       

                ?>    <input type="button" name="previous" class="previous action-button" value="<" />

                                    <input type="submit" name="submit" class="submit action-button" value=">" />
                        </fieldset>
                    </form>
                         <div id="res-tab" class="row">
                <?php    
 if(isset($_REQUEST['submit']))
            { 
                $prodotto = $_POST["prodotto"];       
                $livello = $_POST["livello"];       
                $ruolo = $_POST["ruolo"];       
                $stato = $_POST["stato"]; 



                $args = array( 
                        'post_type' => 'corsi',
                        'posts_per_page' => -1,
                        'orderby' => 'title',
                        'order'   => 'ASC',
                        'tax_query' => array(

                            array(
                                'taxonomy' => 'prodotto',
                                'field' => 'name',
                                'terms' => $prodotto,
                                     ),
                            array(
                                'taxonomy' => 'livello',
                                'field' => 'name',
                                'terms' => $livello,
                                     ),
                             array(
                                'taxonomy' => 'ruolo',
                                'field' => 'name',
                                'terms' => $ruolo,
                                     ),
                       array(
                                'taxonomy' => 'stato',
                                'field' => 'name',
                                'terms' => $stato,
                                     ),        
                                  ) 
                                );
                $soluzioni = new WP_Query($args);

                            if ( $soluzioni->have_posts() ) {

                                        while ( $soluzioni->have_posts() ) {
                                            $soluzioni->the_post(); ?>
                    <div class="col-md-6 largo">
                        <div class="blocco">
                            <h3 style="font-size:20px;line-height:23px;"><?php the_title();?><br/>
                    <?php  
                    $codice = get_post_meta($post->ID, '_corsi_codice', true);
                    echo '( '.$codice .' )'; ?></h3>
                            <p>
                                <?php the_content();?>
                            </p>
                            <div class="dettagli row">
                                <div class="col-md-6 no-pads">
                                    <h5>PRODOTTO</h5>
                                    <p>
                                        <?php echo get_the_term_list( $post->ID, 'prodotto', '',', ', '' ); ?>
                                    </p>
                                    <h5>AUDIENCE</h5>
                                    <p>
                                        <?php echo get_the_term_list( $post->ID, 'ruolo',  '',', ', ''); ?>
                                    </p>
                                </div>
                                <div class="col-md-6 no-pads">
                                    <h5>MODALITà DI EROGAZIONE</h5>
                                    <p>
                                        <?php  $modalita = get_post_meta($post->ID, '_corsi_modalita', true);
                    echo $modalita; ?>
                                    </p>
                                    <h5>DURATA</h5>
                                    <p>
                                        <?php  $durata = get_post_meta($post->ID, '_corsi_durata', true);
                    echo $durata; ?>
                                    </p>
                                </div>
                                <a href="<?php echo the_permalink()?>">
                                    <button>DETTAGLI</button>
                                </a>
                            </div>
                            <?php  /*
                $prezzo = get_post_meta($post->ID, '_corsi_prezzo', true);
                    echo '€ '.$prezzo;*/ ?>
                        </div>


                    </div>
                    <?php   
                                                                        }


                                                        wp_reset_postdata();
                                                            } else 
                                                                {
                                                                       echo '<br/>NO POST FOUND';
                                                                }




                         } ?>



            </div>

                </div>
            </div>
        </div>

And the jQuery part

            jQuery(document).ready(function ($) {

                var current_fs, next_fs, previous_fs; 
                var left, opacity, scale; 
                var animating; 

                $(".next").click(function () {
                    if (animating) return false;
                    animating = true;

                    current_fs = $(this).parent();
                    next_fs = $(this).parent().next();


                    $("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active")
                    $("#progressbar li").eq($("fieldset").index(current_fs)).addClass("done");


                    next_fs.show();

                    current_fs.animate({
                        opacity: 0
                    }, {
                        step: function (now, mx) {

                            scale = 1 - (1 - now) * 0.2;
                            left = (now * 50) + "%";
                            opacity = 1 - now;
                            current_fs.css({
                                'transform': 'scale(' + scale + ')',
                                'position': 'absolute'
                            });
                            next_fs.css({
                                'left': left,
                                'opacity': opacity
                            });
                        },
                        duration: 800,
                        complete: function () {
                            current_fs.hide();
                            animating = false;
                        },

                    });
                });



                $(".previous").click(function () {
                    if (animating) return false;
                    animating = true;

                    current_fs = $(this).parent();
                    previous_fs = $(this).parent().prev();

                    $("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");


                    previous_fs.show();

                    current_fs.animate({
                        opacity: 0
                    }, {
                        step: function (now, mx) {

                            scale = 0.8 + (1 - now) * 0.2;

                            left = ((1 - now) * 50) + "%";

                            opacity = 1 - now;
                            current_fs.css({
                                'left': left
                            });
                            previous_fs.css({
                                'transform': 'scale(' + scale + ')',
                                'opacity': opacity
                            });
                        },
                        duration: 800,
                        complete: function () {
                            current_fs.hide();
                            animating = false;
                        },

                    });
                });

                $('.del').hide();
                  $('.scelt-con').hide();

                $("input[name='prodotto']").change(function () {
                    var strText = $("input[name='prodotto']:checked").val();
                    var result = strText;
                    $('#prodotto').text(result);
                    $('#uno').show(500);
                    $ ('.prod').show(500);
                    return false;

                });

                $("input[name='livello']").change(function () {
                    var strText = $("input[name='livello']:checked").val();
                    var result = strText;
                    $('#livello').text(result);
                    $('#due').show(500);
                    $ ('.liv').show(500);
                });

                $("input[name='ruolo']").change(function () {
                    var strText = $("input[name='ruolo']:checked").val();
                    var result = strText;
                    $('#ruolo').text(result);
                    $('#tre').show(500);
                    $ ('.role').show(500);
                });

                $("input[name='stato']").change(function () {
                    var strText = $("input[name='stato']:checked").val(); 
                    var result = strText;
                    $('#stato').text(result);
                    $('#qua').show(500);
                    $ ('.sta').show(500);
                });
                $(".submit").click(function () {
                    $("fieldset").hide();
                    $("#res-tab").show();


                }); 


            });

I'd like to do the trick with ajax, but can't figure out how to do that. Any help is appreciated! tnx :)


Thanks for your answer. So, I tried but I'm missing something, cause nothing seems to happen, not even an error in console :/

My functions:

function process_form() {   
global $wpdb;
    $prodotto = $_POST["prodotto"];       
    $livello = $_POST["livello"];       

        echo $prodotto;
        echo $livello;


        wp_send_json_success( $data );   

    wp_die();}


add_action( 'wp_ajax_nopriv_process_form', 'process_form' );

wp_localize_script('radio', 'ajax_object', array( 
'ajax_url' => admin_url( 'admin-ajax.php' ),));

The js is an external file, enqueued before the ajax action.

function enqueue_radio() {
  if ( is_page_template('modello-2.php' )) {
    wp_enqueue_script( 'radio', get_stylesheet_directory_uri() . '/js/radio.js', true );
  }
}
add_action( 'wp_enqueue_scripts', 'enqueue_radio' );

What am I missing? Tnx


EDIT

I edited the function part, it seems that the form submit, the page recharge but it output the form again and not the results. Here full code:

FUNCTIONS - ENQUEUE JS FILES

 function enqueue_radio() {
        if (is_page_template('modello-2.php')){
            wp_enqueue_script( 'radio', get_stylesheet_directory_uri() . '/js/radio.js', array('jquery'), '', false );
            wp_localize_script( 'radio', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')) );
        }
    }
    add_action( 'wp_enqueue_scripts', 'enqueue_radio' );

FUNCTIONS - AJAX LOADING - This is where I probably messed up, but I can't figured how

function process_form() { 

    global $wpdb;
        $prodotto = $_POST["prodotto"];       
        $livello = $_POST["livello"];       
        $ruolo = $_POST["ruolo"];       
        $stato = $_POST["stato"]; 
    ?>
    <div id="res-tab" class="row">
        <?php

            $args = array( 
                        'post_type' => 'corsi',
                        'posts_per_page' => -1,
                        'orderby' => 'title',
                        'order'   => 'ASC',
                        'tax_query' => array(
                                array(
                                    'taxonomy' => 'prodotto',
                                    'field' => 'name',
                                    'terms' => $prodotto,
                                    ),
                                array(
                                    'taxonomy' => 'livello',
                                    'field' => 'name',
                                    'terms' => $livello,
                                    ),
                                array(
                                    'taxonomy' => 'ruolo',
                                    'field' => 'name',
                                    'terms' => $ruolo,
                                    ),
                                array(
                                    'taxonomy' => 'stato',
                                    'field' => 'name',
                                    'terms' => $stato,
                                    ),        
                                ) 
                            );
            $soluzioni = new WP_Query($args);
                if ( $soluzioni->have_posts() ) {
                    while ( $soluzioni->have_posts() ) {
                    $soluzioni->the_post(); ?>

            <div class="col-md-6 largo">
                <div class="blocco">
                 <!-- THIS IS THE RESULT LAYOUT -->
                    </div>
            </div>
            <?php   } 

            wp_reset_postdata(); } 
            else {
                    echo '<br/>NO POST FOUND';
                }

        ?>
    </div>

    <?php         

        wp_send_json_success( $soluzioni);   

        wp_die();
}

add_action( 'wp_ajax_nopriv_process_form', 'process_form' );

JS FILE

jQuery(document).ready(function ($) {       

    $("#idForm").submit(function(e) {

    var form = $('#msform');
    var url = ajax_object.ajax_url;       
    var fdata = {};
    fdata['action'] = 'process_form';
    fdata['prodotto'] = form.find('input[name="prodotto"]').val();
    fdata['livello'] = form.find('input[name="livello"]').val();
    fdata['ruolo'] = form.find('input[name="ruolo"]').val();
    fdata['stato'] = form.find('input[name="stato"]').val();

    $.ajax({
           type: "POST",
           url: url,
           data: fdata,
           success: function(resp)
           {
               var res_tab = $("#res-tab");

               res_tab.empty();
               res_tab.append(resp.data);

               $("fieldset").hide();
               res_tab.show();
           },
           error: function(error) {
               console.log(error);
           },
        });

        e.preventDefault(); // avoid to execute the actual submit of the form.
    });
});
1

You will need a function that will handle the sent data from the form. Then you have to attach this function to the wp_ajax_nopriv_[your_action_name] hook.

function process_form() {
    // process $_POST data, prepare $output to return
    //
    // send: array( 'success' => true, 'data' => $data )
    wp_send_json_success( $data );     
    wp_die();
}
// add_action( 'wp_ajax_my_action',        'process_form' );  // ajax from back-end
add_action( 'wp_ajax_nopriv_my_action', 'process_form' );  // ajax from front-end

Add code in functions.php or in plugin.

Now in the javascript code, you need to collect data from the form fields and add action field with the appropriate value. It is also worth checking their correctness before sending.

Using ajax, send data to the server and display the result. Remove:

$(".submit").click(function () {  
    $("fieldset").hide();  
    $("#res-tab").show();  
});

And add:

$("#idForm").submit(function(e) {

    var form = $('#msform');
    var url = ajax_object.ajax_url;
    // var url = "<?php echo admin_url( 'admin-ajax.php' ); ?>", // if this is inline JS

    var fdata = {};
    fdata['action'] = 'my_action';
    fdata['prodotto'] = form.find('input[name="prodotto"]').val();
    // ... colect remaining data

    $.ajax({
           type: "POST",
           url: url,
           data: fdata,
           success: function(resp)
           {
               var res_tab = $("#res-tab");
               //
               // show response "resp.data" from the php script.
               res_tab.empty();
               res_tab.append(resp.data);

               $("fieldset").hide();
               res_tab.show();
           },
           error: function(error) {
               console.log(error);
           },
        });

        e.preventDefault(); // avoid to execute the actual submit of the form.
    });
});

If your javascript code is in separated file, add this to function.php to localize script

wp_localize_script('script_name', 'ajax_object', array( 
    'ajax_url' => admin_url( 'admin-ajax.php' ),
));

If javascript is inline then add var url = "<?php echo admin_url( 'admin-ajax.php' ); ?>".
Replace my_action in php and javascript with some names.
script_name replace with the name under which the js file was registered.

Read about ajax in codex.


Edit
script registration:

function enqueue_radio() {
  if ( is_page_template('modello-2.php' )) {
    wp_enqueue_script( 'radio', get_stylesheet_directory_uri() . '/js/radio.js', array('jquery'), '', true );
    wp_localize_script( 'radio', 'ajax_object',  
        array('ajax_url' => admin_url('admin-ajax.php')) );
  }
}
add_action( 'wp_enqueue_scripts', 'enqueue_radio' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.