Submitting two radio button type forms on a single page using AJAX

I have 2 forms. I would like both forms to act separately and so on form one I would like to submit the form instantly using AJAX using the radio button. The same also for form 2. I can do this for one form but not two. Is this possible?

<form id="poll_form" method="post" action="{{URL::route('poll-update')}}">
fieldset class="polling">  
<input type="radio" name="poll_option" value="1"/>
<input type="radio" name="poll_option" value="2"/>
<input type="text" name="poll_option" value="sometext"/> 
<fieldset>
</form>

<form id="poll_formtwo" method="post" action="{{URL::route('poll-update')}}"> 
<fieldset class="polling">  
<input type="radio" name="poll_option" value="1"/>
<input type="radio" name="poll_option" value="2"/>
<input type="text" name="poll_name" value="sometexttext"/>
</fieldset>
</form>  

I've tried

JQuery

  $('input:radio').change(function(){

       var article = $('#poll_form').serializeArray();
       var url     = $('#poll_form').attr('action');

       $.post(url, article, function(data){
           console.log(data);
       });
    });




 $('input:radio').change(function(){

       var article = $('#poll_formtwo').serializeArray();
       var url     = $('#poll_formtwo').attr('action');

       $.post(url, article, function(data){
           console.log(data);
       });
    });

Answers 1

  • You can try the following.

    $('input:radio').change(function(){
                var $form = $(this).closest('form')
        var article = $form.serializeArray();
        var url     = $form.attr('action');
    
       $.post(url, article, function(data){
           console.log(data);
       });
    });
    

    See fiddle


Related Articles