The method of using Ajax to submit form in lavarel framework

Time:2020-2-16

About laravel:

Laravel is a concise and elegant PHP web development framework. It can free you from the messy code like noodles; it can help you build a perfect network app, and each line of code can be concise and expressive. “Development” should be a creative mental work, not a boring “code base”.

Let’s get to the point, because laravel needs to add{{csrf_field()}}Prevent cross site attacks, so when you submit a form with Ajax, you should add it.

I read a lot of solutions on the Internet. I use the following methods to solve this problem:

1. First, add a meta to the template:


<meta name="_token" content="{{ csrf_token() }}"/> 

2, and then add


headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},

This is the Ajax method. I found a very useful jQuery function, $(). Serialize() and $(). Serializearray(), which I used in the code. I can get the data in the form form form and transfer it directly through Ajax. It’s amazing!!! (I’ve heard so little about it that you can laugh at it.)


$(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. Go to $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";
  }

Conclusion:

I think every step I say is necessary!!!. the code in my callback function is to reprint the data obtained in the form. What I don’t need can be ignored. Then the code will look at it. It’s provided by a PHP beginner