简体   繁体   中英

405 error in laravel 5.6

im sending a form data via ajax to the server using laravel 5.6 when sending the data to the server, i have specified the method of ajax to POST and the routing method in web.php to post too, the problem is, ajax sendS the form data with GET method not POST. what should i change???

ajax code

var form = $('#personPersonalInfoForm')[0];
var formData = new FormData(form);

$.ajax({
    url:"/addNewPerson",
    Type: "POST",
    data: formData,
    contentType: false,
    processData: false,
    success: function(data)
    {
        alert(data);
    }
});

web.php code

Route::post('/addNewPerson', 'adminController@addNewPerson');

Here is an example of working code using the FormData. Using the configuration instead of .配置而不是

var form = document.getElementById("ajaxForm");
var formData = new FormData(form);
var url = form.action;
$.ajax({
    method : 'POST',
    url : url,
    data : formData,
    contentType: false,
    processData: false
}).done(function (data) {
    console.log(data);
}).error(function (data) {
    console.log(data);
});

Dont forget to add the CSRF token in the form.

<form method="POST" action="/addNewPerson" id="ajaxForm">
    @csrf
    ...
</form>

configure the ajax method from the start with it.从头开始配置ajax方法。

in the add添加

<meta name="csrf-token" content="{{ csrf_token() }}">

and in the JavaScript add

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

web.php

Route::post('/addNewPerson', 'adminController@addNewPerson')->name(admin.add_new_person);

in your adminController :

public function addNewPerson(Request $request){
   // you can check request parameters
   //return response()->json($request->all());

   // add new person code here ...

   return response()->json(array('status'=>'success','message'=>'person added'));
}

your ajax code should be :

$.ajax({
    url:"/addNewPerson",
    type: "POST",
    data:$('#personPersonalInfoForm').serialize(),
    dataType:'json',
    contentType: 'application/json',
    success: function(data)
    {
        alert(data);
    }, 
    error:function(){
       alert('ERROR');
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM