简体   繁体   中英

how to get data from ajax request in laravel

I am doing ajax request and passing this data

    $.ajax({
  url: "{{URL::to('match')}}/"+ id,
  type: 'PUT',
  // dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
  data: {
    match_id : id,
    start_time : newTime,
    competitionId: {{$cid}},
    _token:     '{{ csrf_token() }}'
  }
})

and in laravel trying to get this data as

dd($request->start_time);

but it is not working i am getting null

In chrome developer tools data with ajax request sent correctly this is one simple

match_id:1
start_time:03:00
competitionId:1
_token:9p8plPay7HLvJvMrTgxayEH74Ow6c2D1cli1yU01

all of this was working fine before I moved this site to a new server

have i missed any file ?

It works fine after i changed type to Post and then added a field _method: PUT ie

$.ajax({
      url: "{{URL::to('match')}}/"+ id,
      type: 'POST',
      // dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
      data: {
        _method: 'PUT',
        match_id : id,
        start_time : newTime,
        competitionId: {{$cid}},
        _token:     '{{ csrf_token() }}'
      }
    })

type php artisan route:list

check your route there for example your

Method = put

Uri = match/{match}

Name = match.update

Action = App\\Http\\Controllers\\MatchController@ update //your method

Route:

Route::resource('/match', 'MatchController');

this is your ajax call:

$.ajax({
    url: 'match/'+ id, //this is your uri
    type: 'PUT', //this is your method
    data: { match_id:id, start_time:newTime },
    dataType: 'json',
    success: function(response){

    }
});

Your Controller:

public function update(Request $request, $match_id)
{
   if(request()->ajax()){
      $match = Match::find($match_id);
      $validator = Validator::make($request->all(), [
         'start_time'=>'required',
      ]);

      if($validator->passes()) 
      {
        $match->start_time = $request->start_time;
        $match->save();

        return response()->json(['msg'=>'Updated Successfully', 'success'=>true]);
      }
      return response()->json(['msg'=>$validator->errors()->all()]);
    }
}

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