Skye Lans
Skye Lans

Reputation: 41

Passing form data to multiple functions using JQuery

I have a form that has multiple steps and collects form data within each step. When I submit the form via ajax request only the data from the last page is sent. Should I pass the form data to each function or what is the best approach to fix this issue?

<script type="text/javascript">
$(document).ready(function() {

    var email = $('input[name=email]');
    var phone = $('input[name=phone]');
    var comments = $('textarea[name=comments]');

    // Sumbit first slide
    $('.slide-btn-sm1').click(function(e){ 
        $('.step1').fadeOut('slow', function(){
        $('.step1').empty();
        $(".step2").show().fadeIn(300);

        });
    });

    // Sumbit second slide
    $('.slide-btn-sm2').click(function(e){    
        $('.step2').fadeOut('slow', function(){
        $('.step2').empty();
        $(".step3").show().fadeIn(300);
        });
    });

    //Submit the form
    $('.send').click(function () {  
    var formData = $('#formcontents').serialize();

        $.ajax({
        url : "http://website.com/test.php",type: "POST",data : formData,
        success: function(data, textStatus, jqXHR)
        {
            $('.step3').fadeOut('slow', function(){
            $('.step3').empty();
            $(".step4").show().fadeIn(300);
            });
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
                alert ("error");
        }
        });
            return false;
    }); 


});
</script>

Upvotes: 0

Views: 54

Answers (1)

Mustapha Larhrouch
Mustapha Larhrouch

Reputation: 3393

when you use empty() you remove the form data from the DOM.

https://api.jquery.com/empty/

you need just to hide the step :

$('.slide-btn-sm1').click(function(e){ 
    $('.step1').fadeOut('slow', function(){
    //$('.step1').empty(); //remove this line
    $(".step2").show().fadeIn(300);

    });
});

Upvotes: 1

Related Questions