weixin_33727510 2020-01-10 03:37 采纳率: 0%
浏览 26

Laravel Ajax映射所有输入

I have multi step form with different data type such as multiple checkbox, radio button and input (text) as my form steps are dynamic (depend on data from database) i cannot provide static data to send in backend like data: {1: one, 2:two, etc.} I need the way to make this data:{} dynamic, i mean if i have 5 inputs in my form send 5 data to backend, if i have 12 inputs then send 12 data.

Code

success:function(data){ // getting my form inputs from backend
    $('.projectName').append('of ', data.project.name);

    //return existed data to quizzes
    var index = 0;
    var countdownTimer = null;
    var count = 0;
    $("#clicks").click(function(e){
        e.preventDefault();

        // timer function
        function timer(seconds, countdownTimer, callback) {
            var days = Math.floor(seconds / 24 / 60 / 60);
            var hoursLeft = Math.floor((seconds) - (days * 86400));
            var hours = Math.floor(hoursLeft / 3600);
            var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
            var minutes = Math.floor(minutesLeft / 60);
            var remainingSeconds = seconds % 60;
            if (remainingSeconds < 10) {
                remainingSeconds = "0" + remainingSeconds;
            }
            document.getElementById('countdown').innerHTML = hours + ":" + minutes + ":" + remainingSeconds;
            if (seconds == 0) {
                clearInterval(countdownTimer);
                document.getElementById('countdown').innerHTML = "Times Up!";
                $("#clicks").attr("disabled", true);
                $("#clicks").hide();
                $('.answerPanel').html('<div class="text-center text-danger">OH NO! <br> Times Up!</div>');
            } else {
                seconds--;
            }
            //Pass seconds param back to the caller.
            callback(seconds);
        }
        //We pass the countdownTimer param into the timer function as well.
        if (countdownTimer != null) {
            clearInterval(countdownTimer);
        }
        if(typeof data.quizzes[index] !== 'undefined'){
            seconds = data.quizzes[index].quiz_time;
        }
        countdownTimer = setInterval(function() {
            timer(seconds, countdownTimer, function(_seconds){
                seconds = _seconds;
            })
        }, 1000);



        // printing function (this is my form inputs "3 types")
        if(typeof data.quizzes[index] !== 'undefined'){
            var html = '<div class="row"><div class="col-md-12"><div class="pull-left questionTitle">'+data.quizzes[index].question+'</div><div class="pull-right" id="countdown"></div></div></div>';
            if(data.quizzes[index].choices.length > 0){
                html+='<div class="col-md-12">';
                if(data.quizzes[index].question_type == 'multiple'){
                    data.quizzes[index].choices.forEach((element, index, array) => {
                        html+='<div class="checkbox checkbox-primary">';
                        html+='<input id="choice" name="choice" type="checkbox" value="'+element.choice+'">';
                        html+='<label for="checkbox2">'+element.choice+'</label>';
                        html+='</div>';
                    });
                } else if (data.quizzes[index].question_type == 'single') {
                    data.quizzes[index].choices.forEach((element, index, array) => {
                        html+='<div class="radio radio-primary">';
                        html+='<input id="choice" name="choice" type="radio" value="'+element.choice+'">';
                        html+='<label>'+element.choice+'</label>';
                        html+='</div>';
                    });
                } else {
                    data.quizzes[index].choices.forEach((element, index, array) => {
                        html+='<div class="radio radio-primary">';
                        html+='<input id="choice" name="choice" type="text" value="'+element.choice+'">';
                        html+='<label>'+element.choice+'</label>';
                        html+='</div>';
                    });
                }
                html+='</div>';
            }
            $(".answerPanel").html(html);
            index++;
        }

        if(data.quizzes.length > index+1) {
            $("#clicks").html("Next");
        }
        if(data.quizzes.length === index) {
            $("#clicks").html("Send");
            $('#clicks').removeClass('btn-primary').addClass('btn-success saveAnswers');
        }
        //end of printing function

        //send form data
        $('.saveAnswers').unbind().bind('click', function(e){
            e.preventDefault();

            // var formData = new FormData();
            // formData.append('radio buttons', $(this).closest("form").find("input[name=choice]").is(':checked'));
            // formData.append('select options', $(this).closest("form").find("input[name=choice]").is(':selected'));
            // formData.append('text inputs', $(this).closest("form").find("input[name=choice]").is(':selected'));
            $.post({
                type: 'POST',
                url: '{{route('quizzes.store')}}',
                dataType: "json",
                processData: false,
                contentType: false,
                data: formData,
                success:function(data){
                    console.log(data);
                }
            });
        });
        //send form data
    });
}

Note: I shared full code in case you need to figure out the logic but to be clear my issue is in saving part that i commented with //send form data

PS: some of my form data are multiple choice (checkbox)

Example:

Let say one of my form has 3 steps with 3 different types, here how i need the data,

{
"step 1" : {good, bad} // checkbox
"step 2" : {no} // radio button
"step 3": {this is my testing input} // text input
}

This data will be saved in json column, so it needs to be send as json i guess.

Question

How can I wrap my dynamic inputs and send data to backend?

Update

Well as I was losing the data of each step after clicking next button i've decided to save data of each step in localStorage and then send them at once in final step.

with my edited code i am facing 3 issues:

  1. Else part won't work
  2. Data of second step will save in localStorage when i click in first step! also in different rows instead of their row as json {} two
  3. Next steps clears previous step data in localStorage.

code

// printing function
if(typeof data.quizzes[index] !== 'undefined'){
    var html = '<div class="row"><div class="col-md-12"><div class="pull-left questionTitle">'+data.quizzes[index].question+'</div><div class="pull-right" id="countdown"></div></div></div>';
    if(data.quizzes[index].choices.length > 0){
        html+='<div class="col-md-12">';
        if(data.quizzes[index].question_type == 'multiple'){
            data.quizzes[index].choices.forEach((element, index, array) => {
                html+='<div class="checkbox checkbox-primary">';
                html+='<input class="styled form-check-input" id="choice" name="'+data.quizzes[index].question+'[]" type="checkbox" value="'+element.choice+'">';
                html+='<label class="control-label">'+element.choice+'</label>';
                html+='</div>';
                // added part
                $('#clicks').on('click', function(e) {
                    e.preventDefault();
                    var checkboxes = [];
                    $("input[name='"+data.quizzes[index].question+"']").each(function(){
                        checkboxes.push(this.value);
                    });
                    console.log(checkboxes);
                    localStorage.setItem(data.quizzes[index].question, JSON.stringify(checkboxes));
                });
            });
        } else if (data.quizzes[index].question_type == 'single') {
            data.quizzes[index].choices.forEach((element, index, array) => {
                html+='<div class="radio radio-primary">';
                html+='<input class="styled form-check-input" id="radio" name="'+data.quizzes[index].question+'" type="radio" value="'+element.choice+'">';
                html+='<label class="control-label">'+element.choice+'</label>';
                html+='</div>';
                // added part
                $('#clicks').on('click', function(e) {
                    e.preventDefault();
                    var radios = [];
                    $("input[name='"+data.quizzes[index].question+"']").each(function(){
                        radios.push(this.value);
                    });
                    console.log(radios);
                    localStorage.setItem(data.quizzes[index].question, JSON.stringify(radios));
                });
            });
        } else { // added part
            alert('hi');
            data.quizzes[index].choices.forEach((element, index, array) => {
                html+='<div class="row">hi';
                html+='<input id="input" name="'+data.quizzes[index].question+'" type="text">';
                html+='<label>'+element.choice+'</label>';
                html+='</div>';
                // added part
                $('#clicks').on('click', function(e) {
                    e.preventDefault();
                    var inputss = [];
                    $("input[name='"+data.quizzes[index].question+"']").each(function(){
                        inputss.push(this.value);
                    });
                    console.log(inputss);
                    localStorage.setItem(data.quizzes[index].question, JSON.stringify(inputss));
                });
            });
        }
        html+='</div>';
    }
    $(".answerPanel").html(html);
    index++;
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 树莓派与pix飞控通信
    • ¥15 自动转发微信群信息到另外一个微信群
    • ¥15 outlook无法配置成功
    • ¥30 这是哪个作者做的宝宝起名网站
    • ¥60 版本过低apk如何修改可以兼容新的安卓系统
    • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
    • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
    • ¥50 有数据,怎么用matlab求全要素生产率
    • ¥15 TI的insta-spin例程
    • ¥15 完成下列问题完成下列问题