0
votes

Am working on a form which has various input fields including a field to upload files. When the user hits the submit button, I want to submit the form via AJAX POST request to the backend which is PHP Laravel. The problem is that the data is not being submitted as expected.. I am serializing the data then posting directly but am not sure if it is the correct way.

Form Layout

<form method="POST" action="#" id="form" enctype="multipart/form-data" accept-charset="UTF-8">
    <!-- CSRF TOKEN-->
      <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <!-- END CSRF TOKEN-->
    <div class="form-line registar2 love">
        <input id="passport" type="text-area" class="form-input" name="passport" value="{{ old('passport') }}" autofocus>
            <label> Passport</label>
            <div class="error-label"></div>
            <div class="check-label"></div>
             @if ($errors->has('passport'))
                <span class="help-block">
                    <strong>{{ $errors->first('passport') }}</strong>
                </span>
            @endif
   </div>

    <div class="form-line registar2 move" >
      <input id="kra" type="text-area" class="form-input" name="kra" value="{{ old('kra') }}" required>
      <label>KRA Pin *</label>
      <div class="error-label">Field is required!</div>
      <div class="check-label"></div>
      @if ($errors->has('kra'))
        <span class="help-block">
            <strong>{{ $errors->first('kra') }}</strong>
        </span>
      @endif
    </div>

    <div class="form-line registar2 love {{ $errors->has('residence') ? ' has-error' : '' }}">
      <input id="residence" type="text-area" name="residence" class="form-input" required>
      <label>Current Residential Address *</label>
      <div class="error-label">Field is required!</div>
      <div class="check-label"></div>
      @if ($errors->has('residence'))
        <span class="help-block">
            <strong>{{ $errors->first('residence') }}</strong>
        </span>
      @endif
    </div>

    <div class="form-line registar2 move {{ $errors->has('documents') ? ' has-error' : '' }}">
      <input id="documents" type="file" class="form-input" name="documents" value="{{ old('documents') }}" multiple>
      <div class="error-label"></div>
      <div class="check-label"></div>
      @if ($errors->has('documents'))
          <span class="help-block">
            <strong>{{ $errors->first('documents') }}</strong>
          </span>
      @endif
    </div>

    <button type="submit"id="pay"> Proceed to Payament</button>


  </form>

AJAX code being called when the form is submitted

<script>
    // Get the form via its id
    var form = $('#form');

    // Set up an event listener for the contact form.
    $(form).submit(function(e) {
    // Stop the browser from submitting the form.
    event.preventDefault();

    var inputs = $("#form :input");
    console.log(inputs);

    var entries = inputs.serialize();

    console.log(entries);

    $.ajax({
        type: "POST",
        //url in the routes file to post the data
        url: "saveAdd",
        contentType: "application/x-www-form-urlencoded",
        data: entries,
        success: function(response){
          alert(response);
        },
        failure: function(errMsg) {
            alert(errMsg);
        }
    });
});

</script>

Routes file of the controller to POST to

Route::any( '/saveAdd', 'B2CController@saveAdd')->name('b2c.saveAdd');

Controller file in Laravel Backend

    public function saveAdd(Request $request){

        dd($request->all());
    }
1
can you show us what response is returned from the server? You can find that by pressing f12 and going to the network tab and then by looking at the 'saveAdd' request.Junaid Ahmad
@JunaidAhmad Am getting an array of all the data except the file that has been uploaded by the user array:5 [ "_token" => "RMDvaDBbCuQA3aGl5M4BUfJKwASyBIzQpLun8o3p" "passport" => "897897987" "kra" => "09709709709" "residence" => "u8768768768" ]Pweb
@JunaidAhmad All the inputs are being fetched well except the file uploaded by the userPweb
I see. I think this answer will solve your problem. stackoverflow.com/questions/5392344/…Junaid Ahmad
The issue must be due to contentType. Which must be multi-part in case of files.Junaid Ahmad

1 Answers

1
votes

On form submit function, it fetches all the data from the form including file. let keyword is used as local scope.

$( "form" ).submit(function( event ) {
    let form = $( this )
    let formData = new FormData(form[0]);
    event.preventDefault();
    console.log(formData);

    $.ajax({
        type: "POST",
        data:formData,
        processData: false,
        contentType: false,
        url: "saveAdd",
        success: function(response){
            alert(response);
        },
        failure: function(errMsg) {
            alert(errMsg);
        }
    });
});