douyuan6490
2018-05-24 19:47
浏览 213
已采纳

显示来自Laravel的Ajax响应的返回消息

I've got a working form that submits to a database from an HTML form using Laravel Collective that submits to my Controller, and it works fine.

I want to submit it without a page reload, so I'm submitting the data with AJAX.

I've got it working, and it's writing to the db, but I can't get the controller to return the response to the page on success.

The following is my script:

SCRIPT:

$(document).ready(function(){
  $("#msg").hide();

  $("#submit").click(function() {
    $("#msg").show();


    var name = $("#recipeName").val();
    var description = $("#recipeDescription").val();
    var token = $("#token").val();

    $.ajax({
      headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
      type: "post",
      data: "name="+name+"&description="+description,
      dataType:'json',
      url: "{{ route('recipes.store') }}",
      success:function(data){
        $("#msg").html("Recipe Saved");
        $("#msg").fadeOut(2000);

      }
    });
  })
})

HTML:

<div class="row">
  <div class="col">
    <p class="alert alert-success" id="msg"></p>
  </div>
</div>
<div class="row">
  <div class="col">

    <!-- Start Form -->
    <input type="hidden" name="csrf" value="{{csrf_token()}}" id="token">
    <div class="form-group">
      <label for="recipeName">Recipe name:</label>
      <input type="text" class="form-control" id="recipeName" aria-describedby="emailHelp" placeholder="Enter recipe name">
      <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
    </div>
    <div class="form-group">
      <label for="recipeDescription">Recipe Description:</label>
      <textarea class="form-control" id="recipeDescription" rows="3" placeholder="Enter a recipe description"></textarea>
    </div>
    <button type="submit" class="btn btn-primary btn-block btn-lg" id="submit">Submit</button>
    <!-- End Form -->

  </div>
</div>

CONTROLLER:

public function store(Request $request)
{
    $this->validate($request, [
      'name' => 'required|max:255',
      'description' => 'required'
    ]);

    $recipe = new Recipe;

    $recipe->name = $request->name;
    $recipe->description = $request->description;
    $recipe->user_id = auth()->user()->id;

    $recipe->save();

    return Response::json(array(
      'success' => true,
      'data'   => $data
    )); 
}

I can't workout what it is that I'm missing.

I'm learning AJAX on the fly (I'm learning all of it on the fly if I'm honest!), but as I say, it's writing to the db successfully, just need to notify the user of it.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douwen5985 2018-05-24 20:32
    已采纳

    Changing the following in the controller works correctly!

    ...
    $recipe->save();
    $data = [
      'success' => true,
      'message'=> 'Your AJAX processed correctly'
    ] ;
    
    return response()->json($data);
    
    点赞 评论
  • doulaozhang0238 2018-05-24 20:04

    SCRIPT

      $("#submit").click(function() {
            $("#msg").show();
            var name = $("#recipeName").val();
            var description = $("#recipeDescription").val();
    
            $.ajax({
                type: "post",
                data: {name:name,description:description,'_token':'{{csrf_token()}}'}, 
                 dataType:'json',
                url: "{{ route('recipes.store') }}",
                success:function(data){
                    $("#msg").html("Recipe Saved");
                    $("#msg").fadeOut(2000);
    
                }
            });
        });
    

    HTML

    change the the type of submit button from submit to button

     <div class="row">
     <div class="col">
      <p class="alert alert-success" id="msg"></p>
      </div>
     </div>
    <div class="row">
     <div class="col">
    
    <!-- Start Form -->
    <input type="hidden" name="csrf" value="{{csrf_token()}}" id="token">
    <div class="form-group">
      <label for="recipeName">Recipe name:</label>
      <input type="text" class="form-control" id="recipeName" aria-describedby="emailHelp" placeholder="Enter recipe name">
      <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
    </div>
    <div class="form-group">
      <label for="recipeDescription">Recipe Description:</label>
      <textarea class="form-control" id="recipeDescription" rows="3" placeholder="Enter a recipe description"></textarea>
    </div>
    <button type="button" class="btn btn-primary btn-block btn-lg" id="submit">Submit</button>
    <!-- End Form -->
    

    Controller

    you must identify $data variable

      public function store(Request $request)
      {
       $this->validate($request, [
       'name' => 'required|max:255',
      'description' => 'required'
    ]);
    
    $data = 'some data';
    $recipe = new Recipe;
    
    $recipe->name = $request->name;
    $recipe->description = $request->description;
    $recipe->user_id = auth()->user()->id;
    
    $recipe->save();
    
    return Response::json(array(
      'success' => true,
      'data'   => $data
    )); 
    }
    
    点赞 评论

相关推荐 更多相似问题