Because Laravel will need to add {{Csrf_field ()}} to prevent cross-site attacks when submitting data as a post, this article is mainly to share the method of using AJAX to submit forms in the Lavarel framework, let's look at it and hope to help everyone.
Laravel Introduction:
Laravel is a simple, elegant PHP Web development Framework (PHP Web framework). It frees you from the messy code of noodles, and it helps you build a perfect web app, and every line of code can be concise and expressive. "Development" should be a creative mental work, not a dull "base code".
Come to the point, because Laravel will need to add {{Csrf_field ()}} to prevent cross-site attacks when submitting data as a post, so it's natural to add the form when you use Ajax.
On the internet to see a lot of solutions, I use the following method to solve:
1, first add a meta in the template:
<meta name= "_token" content= "{{Csrf_token ()}}"/>
2, and then in the Ajax method add
Headers: {' X-csrf-token ': $ (' meta[name= ' _token "] '). attr (' content ')},
This is the Ajax method, found a very useful jquery function, $ (). Serialize () and $ (). Serializearray (), I use the latter in the code, can get the data in the form form, and can be transmitted directly through AJAX, it is AMAZING!!! (Ignorant let everyone laughed at)
$ (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 is OK.
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 below:
I think every step I say must be!!!, my callback function is written in the code is to get the form inside the data re-printed out, do not need to ignore it, and then the code will see it, a PHP beginner to serve.