doujie4787 2017-04-13 02:15
浏览 56
已采纳

laravel ajax没有发布到数据库

i'm trying to add a post without the page refreshing the using the simplest way by using jquery ajax.

Its not posting to my mysql database, and i don't know why.

i was following along this tutorial

Vue.js Looks like something i can use in the future but i just cant wrap my head around it

Any Suggestions ?

Dashboard.blade.php

@extends('layouts.layout')

@section('title')
Dashboard
@endsection

@section('content')

<div class="dashboard eli-main">
    <div class="container ">
        <div class="row">
            <div class="col-md-6 col-md-12">
                <h1>{{$user->username}}</h1>

                <h4>What do you have to say?</h4>
                <form>
                    <div class="form-group">
                        <textarea class="form-control" name="body" id="body" rows="5" placeholder="Your Post"></textarea>
                    </div>
                    <button type="submit" id="add" class="mybtn2">Create Post</button>
                    <input type="hidden" value="{{ Session::token() }}" name="_token">
                </form>


                @foreach($posts as $post)


                <article class="post">
                    <h4>{{ $post->user->username }}</h4>
                    <p class="post-bod">
                        {{ $post->body }}
                    </p>
                    <div class="info">
                        made on {{ date('F d, Y', strtotime($post->created_at)) }}
                    </div>
                </article>

                @endforeach

            </div>


        </div>
    </div>
</div>

App.js

$("#add").click(function() {

    $.ajax({
        type: 'post',
        url: '/addItem',
        data: {
            '_token': $('textarea[name=_token]').val(),
            'name': $('textarea[name=body]').val()
        },
        success: function(data) {
            if ((data.errors)) {
                $('.error').removeClass('hidden');
                $('.error').text(data.errors.name);
            } else {
                $('.error').remove();
                $('#table').append("<tr class='item" + data.id + "'><td>" + data.id + "</td><td>" + data.name + "</td><td><button class='edit-modal btn btn-info' data-id='" + data.id + "' data-name='" + data.name + "'><span class='glyphicon glyphicon-edit'></span> Edit</button> <button class='delete-modal btn btn-danger' data-id='" + data.id + "' data-name='" + data.name + "'><span class='glyphicon glyphicon-trash'></span> Delete</button></td></tr>");
            }
        },
    });
    $('#body').val('');

});

PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;
use App\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests;
use Validator;
use Response;
use Illuminate\Support\Facades\Input;

class PostController extends Controller
{


      public function getDashboard()
       {
           $posts = Post::orderBy('created_at', 'desc')->get();
           $cookie = cookie('saw-dashboard', true, 15);
           $users = User::all();
           $user = new User();
   //        return view('dashboard', array('user'=> Auth::user()), compact('users'))->withCookie($cookie);

           return view('dashboard',array('user'=> Auth::user(), 'posts' => $posts,  compact('users')))->withCookie($cookie);
       }

    // public function postCreatePost(Request $request)
    // {
    //  $this->validate($request,[
    //      'body' => 'required|max:1000'
    //  ]);

    //  $post = new Post();
    //  $post->body = $request['body'];
    //  $message = 'There was an error';

    //  if($request->user()->posts()->save($post)){
    //      $message = 'Post Successfully Created';
    //  }

    //     return redirect()->route('dashboard');

    // }

       public function postCreatePost(Request $request) {
           $rules = array (
                   'body' => 'required|max:1000'
           );
           $validator = Validator::make ( Input::all (), $rules );
           if ($validator->fails ())
               return Response::json ( array (

                       'errors' => $validator->getMessageBag ()->toArray ()
               ) );
               else {
                   $post = new Post();
                   $post->body = $request->body;
                   $post->save();
                   return response ()->json( $post );
               }
       }

}

And the route is

Route::post ( '/addItem', 'PostController@postCreatePost' );
  • 写回答

1条回答 默认 最新

  • dsfds2353 2017-04-13 04:47
    关注

    You are accessing the body in the request, when it's actually the name that you are sending

    Change your controller code as below

    public function postCreatePost(Request $request) {
        $rules = array(
             'name' => 'required|max:1000'
        );
    
        $validator = Validator::make(Input::all(), $rules);
    
        if ($validator->fails()) {
           return Response::json (array(
                   'errors' => $validator->getMessageBag()->toArray()
           ));
        } else {
           $post = new Post();
           $post->body = $request->body;
           $post->save();
           return response()->json( $post );
        }
    }
    

    You need to add an preventDefault functionality to your click or change the button type of add

    So in your app.js, make the changes as

    $("#add").click(function (e) {
    
        e.preventDefault();
    
        //rest of the code
    
    });
    

    or

    change this

    <button type="submit" id="add" class="mybtn2">Create Post</button>
    

    to

    <button type="button" id="add" class="mybtn2">Create Post</button>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 主要进行描述非满管状态下,管路的摩阻系数是怎么变化的,在管路长度方向上是怎么分布的(标签-matlab)
  • ¥15 动态多目标优化,求解定义的问题的POF和POS公式
  • ¥30 实验 :UML2.0 行为建模
  • ¥15 设计一种优化调度算法并结合论文中的案例给出调度计划
  • ¥15 py文件打包exe报错TypeError:expected str,bytes or os.PathLike object,not_io.BytesIO
  • ¥15 Java编写学籍信息管理系统
  • ¥15 IPXE网刻客户机找不到服务端
  • ¥15 小贝360-4 配二个 华772S 设置WⅰFi5G 连接
  • ¥15 vs2022的QT报错,好像是缺少winextras
  • ¥15 怎么看 cst中一个面的功率分布图