Home >Web Front-end >JS Tutorial >How to submit a form using ajax in Lavarel framework_AJAX related
Because laravel needs to add {{csrf_field()}} to prevent cross-site attacks when submitting data in the form of a post. Let’s share with you how to use ajax to submit a form in the lavarel framework through this article. Let’s take a look.
Introduction to laravel:
Laravel is a simple and elegant PHP Web development framework (PHP Web Framework). It can free you from messy codes like noodles; it can help you build a perfect network APP, and every line of code can be concise and expressive. "Development" should be a creative mental work, not a boring "base code".
Let’s get straight to the point, because when laravel submits data in post form, it needs to be added {{csrf_field()}}
to prevent cross-site attacks, so it is natural to add it when you use ajax to submit a form.
I read a lot of solutions on the Internet. I solved it with the following method:
1. First, add a meta to the template:
<meta name="_token" content="{{ csrf_token() }}"/>
2, then add
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') },
in the ajax method. This is the ajax method. I found it very useful. jquery's functions, $().serialize() and $().serializeArray(), I use the latter in the code, which can get the data in the form and transmit it directly through ajax, which is amazing!! !(My ignorance 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 get the data in the controller method, just $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"; }
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Two solutions for Ajax opening a new window and being intercepted by the browser
The above is the detailed content of How to submit a form using ajax in Lavarel framework_AJAX related. For more information, please follow other related articles on the PHP Chinese website!