The method for submitting forms using ajax in the Lavarel framework, lavarelajax
Laravel introduction:
Laravel is a simple and elegant PHP Web development Framework ). It can free you from the messy code like a noodle; it can help you build a perfect web APP, and each line of code can be concise and expressive. "Development" should be a creative mental work, rather than a boring "base code".
The reason is that laravel needs to add{{csrf_field()}}
This prevents cross-site attacks. Therefore, when you submit a form using ajax, you must add it as well.
I have read a lot of solutions on the Internet. I used the following method to solve the problem:
1. Add a meta in the template:
<meta name="_token" content="{{ csrf_token() }}"/>
2. Then add
headers: {'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')},
This is the ajax method, and found a very useful jquery function, $ (). serialize () and $ (). serializeArray (). I use the latter in the code. I can get the data in the form and transmit it directly through ajax. It's amazing !!! (It makes everyone laugh)
$(form[1]).submit(function(event){ var data = $(form[1]).serializeArray(); // console.log(data); $.ajax({ type:'post', url:'/basic', data:data, headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')}, success:function(msg){ if (msg) { $('.basicEdit').hide(); $('.basicShow').show(); $('.basicShow span').html(data[1].value+' | '+data[2].value+' | '+data[3].value+' | '+data[4].value+'<br>'+data[5].value+' | '+data[6].value+' | '+data[7].value); } }, }); // event.preventDefault(); return false; });
3. Then, you can get the data in the Controller method. You just need $ req-> your form name.
public function basic(Request $req){ // return $req->gender; $uid = Auth::user()->uid; // return $uid; // $inf = new \App\Info; $inf = Info::where('uid',$uid)->first(); // return $inf; $inf->name = $req->name; $inf->gender = $req->gender; $inf->topDegre = $req->topDegre; $inf->workyear = $req->workyear; $inf->tel = $req->tel; $inf->email = $req->email; return $inf->save()?"ok":"fail"; }
Summary:
I think every step I say is required !!!, The code written in my callback function is to re-print the data obtained in the form. If you don't need it, you can ignore it. Then the code will show you. A php beginner will offer it.