简体   繁体   中英

Ajax submit form Laravel 5.1

Hello guy's i try to figure out a Live feed application in Laravel 5.1 when user can submit their posts. I'm still in stuck with Ajax because i want to save data in DB usign Ajax request.

Here is my form

{!! Form::open(array('url'=>'saveposts','method'=>'POST')) !!}                     
                     <div class="panel-body">
                        <textarea name="post" class="form-control share-text" rows="3" placeholder="Share your status..."></textarea>
                    </div>
                    <div class="panel-footer share-buttons">
                      <a href="#"><i class="fa fa-map-marker"></i></a>
                      <a href="#"><i class="fa fa-photo"></i></a>
                      <a href="#"><i class="fa fa-video-camera"></i></a>
                     <button type="submit" class="send-btn btn btn-primary btn-xs pull-right display-none" id="submit">Post</button> 
                    {!! Form::close() !!}

Here is Ajax script

<script type="text/javascript">
$(document).ready(function(){
  $('#submit').click(function(){            
    $.ajax({
      url: 'saveposts',
      type: "post",
      data: {'post':$('input[name=post]').val(), '_token': $('input[name=_token]').val()},
      success: function(data){
        alert(data);
      }
    });      
  }); 
});
</script>

The route:

Route::post('saveposts', 'UserController@savePosts');

And the method in Controller

public function savePosts() {
    if(Requestjx::ajax()) {
        $data = Input::all();
        return Response::json([
                'error' => false,
                'insertedData' => $data
            ], 200);
    }
}

What' is wrong? It didn't work. Any help is appreciated. Thanks

Your Controller method needs request to be injected. I don't know what "Requestjx" is???? I assume spelled wrong. Try this:

public function savePosts(Request $request) {
    if($request->ajax()){
        $data = Input::all();

        return response()->json([
          'error' => false,
          'insertedData' => $data
        ]);
    }
}

Solved. The problem is that for some reason "button" tag tag doesen't call Ajax properly. So i have created an "a" link that call ajax request and now work as well.

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