0

I am facing a problem.I have multiple form submission in one page. I need to submit all of those with out page reload. I am try with some Ajax code. with ajax code, first form are submit properly but rest of form is not working.

here is my view file

<div class="col-md-6 col-lg-6 col-sm-6 col-lg-offset-5">

@foreach($questions as $question)

<form method="post" action="{{route('answer.store')}}" id="ansform">
    {{ csrf_field() }}

    <h1>{{$question->question}} ?</h1>
    <div class="col-lg-offset-1">
        <input type="hidden" name="question" value="{{$question->question}}">
        <input type="hidden" name="student_id" value="{{$student_id}}">
        <input type="hidden" name="true_answer" value="{{$question->answer}}">
        <input name="answer" value="{{$question->choice1}}" type="radio"> {{$question->choice1}} <br>
        <input name="answer" value="{{$question->choice2}}" type="radio">{{$question->choice2}}<br>
        <input name="answer" value="{{$question->choice3}}" type="radio">{{$question->choice3}}<br>
        <input name="answer" value="{{$question->choice4}}" type="radio">{{$question->choice4}}<br>
        <input type="submit" name="submit" value="submit" class="btn btn-primary">
    </div>
 </form>

@endforeach

Output of view file is-

enter image description here

My route Answer.store is here

public function store(Request $request)
{
    //
    if ($request->ajax()) {
        $answer=Answer::create([
            'stu_id' => $request->input('student_id'),
            'question' => $request->input('question'),
            'given_answer' => $request->input('answer'),
            'true_answer' => $request->input('true_answer')

        ]);
        return response($answer);
    }else{
        return "ajax not done";
    }
}

And finally ajax script is

<script type="text/javascript">
    $(document).ready(function(){
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
    });

    $('#ansform').on('submit',function(e){
        e.preventDefault();
        var data = $(this).serialize();
        var url = $(this).attr('action');
        var post = $(this).attr('method');
        $.ajax({
            type : post,
            url : url,
            data :data,
            success:function(data){
                console.log(data)
            }
        })
    })
</script>

Anyone please help me. How can I do this?

5
  • 2
    You can't repeat element ID's in a page. They are unique by definition. Use classes instead Commented Dec 7, 2017 at 18:13
  • 2
    first thing, you seem to generate multiple forms with the same id, use a class and change te event listener( $('.someclass').on('submit',function(e){ ) Commented Dec 7, 2017 at 18:13
  • would you please suggest where i use class in my code? Can you give me a sample code please? Commented Dec 7, 2017 at 18:18
  • @MustaqueAhmed instead of <form method="post" action="{{route('answer.store')}}" id="ansform"> and $('#ansform').on('submit',function(e){ use <form method="post" action="{{route('answer.store')}}" class="ansform"> and $('.ansform').on('submit',function(e){ Commented Dec 7, 2017 at 18:18
  • @CappY thank you. It works. a little bit help more...how can i disable button after submit a form? Like It would be show Submitted and link is disable? Commented Dec 7, 2017 at 18:26

1 Answer 1

1

I'm answering to last comment.

$('.ansform').on('submit',function(e){
    var form = $(this);
    var submit = form.find("[type=submit]");
    var submitOriginalText = submit.attr("value");

    e.preventDefault();
    var data = form.serialize();
    var url = form.attr('action');
    var post = form.attr('method');
    $.ajax({
        type : post,
        url : url,
        data :data,
        success:function(data){
           submit.attr("value", "Submitted");
        },
        beforeSend: function(){
           submit.attr("value", "Loading...");
           submit.prop("disabled", true);
        },
        error: function() {
            submit.attr("value", submitOriginalText);
            submit.prop("disabled", false);
           // show error to end user
        }
    })
})

This should work. Before sending the form we are disabling submit button (this protects us from double submit). And then we are changing the text to "Loading..." or something that tells end user that he must wait until query completes.

If AJAX is successfully: We are leaving the button disabled and we are changing text to submitted.

If ERROR occurs: we enable submit, returns the original text and allow end user to submit again. You must show him error or something else.

You can look at AJAX events: https://api.jquery.com/Ajax_Events/.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.