jeudi 8 novembre 2018

Problem collecting the checkbox value using AJAX and PHP

Am working on a form which has a checkbox input. The form has a checkbox input field whereby I change the value dynamically depending on whether the checkbox is checked or not. When the user clicks the checkbox the value should change to 1 ,,, when not clicked the value should be zero. Am collecting the value via AJAX and submitting to the backend (build in PHP Laravel),, when I dd() the value I get a null value of the checkbox,, please assist

Layout containing the checkbox field

 <div class="check-now " style="width: 100%;">
        <h1 class="cover-travel">I am travelling with</h1>
        <label class="spouse-me">
            <h1 class="pumba">Spouse</h1>
            <input type="checkbox" id="spouse" value="" class="spouse"  onClick="checkMark()">
        </label>
        @if ($errors->has('spouse'))
            <span class="help-block">
                <strong></strong>
            </span>
        @endif
    </div>

Function that changes the checkbox value

 function checkMark() {
      var checkBox = document.getElementById("spouse");
      var text = document.getElementById("spouseDetail");

      // If the checkbox is checked, display the output text
      if (checkBox.checked == true){
        checkBox.value = '1';
      } else {
        checkBox.value = 'O';
      }
    }

AJAX to submit data to backend

// Get the form via its id
    var form = $('#travel_form');

    $( "form" ).submit(function( event ) {
        event.preventDefault();
        //alert('clicked');


        //Fetch the value of spouse
        var spouse = $('#spouse').val();

        //Log in console tab am getting an empty value
        console.log(spouse);

        //Add in a JS object
        var type = {
            'spouse' : spouse 
        }

        $.ajax({
            type: "POST",
            url: "getplans",
            data:JSON.stringify(type),
            contentType: 'application/json',
            dataType: "json",
            success: function(response){
                window.location.href="getp" ;
            },
            //Alert errors from backend
            error: function(data) {
                var errors = '';
                for(datos in data.responseJSON){
                    errors += data.responseJSON[datos] + '\n';
                }
                alert(errors);
            }
        });
    });

Controller handling the AJAX call

 public
    function validatePlanEntries(Request $request)
    {   
        //dd($request->all());
    }




Aucun commentaire:

Enregistrer un commentaire