2017-04-14 19 views
0

ajaxをlaravelに追加できました。次のコードでは、ページをリフレッシュせずにajax経由で投稿を追加してデータベースに追加しますが、ajax経由で投稿した投稿を取り出す方法は少しわかりません。ajaxを使用してlaravelで投稿を取得する方法は?

任意の提案エラーが現れていない、私はちょうど、AJAX経由

app.js

$.ajaxSetup({ 
    headers: { 
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') 
    } 
}); 



    $('#add').click(function(){    
    $.ajax({ 
     url: 'createpost', 
     type: "post", 
     data: {'body':$('textarea[name=body]').val(), '_token': $('input[name=_token]').val()}, 
     success: function(data){ 
     $('#new-post').val(''); 

     } 
    });  
    }); 

PostController.php

<?php 

namespace App\Http\Controllers; 

use Illuminate\Http\Request; 
use App\Post; 
use App\User; 
use Illuminate\Support\Facades\Auth; 
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) { 
     $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; 
     $request->user()->posts()->save($post); 
     return response()->json($post); 
     } 
    } 


} 

ダッシュボードポストをフェッチカント.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="new-post" rows="5" placeholder="Your Post"></textarea> 
        </div> 
        <button type="button" id="add" class="mybtn2">Create Post</button> 
        <input type="hidden" value="{{ Session::token() }}" name="_token"> 
       </form> 
       {{ csrf_field() }} 



       @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> 

@endsection 

、ここでルート

Route::post('/createpost',[ 

    'uses' => '[email protected]', 
    'middleware' => 'auth' 

]); 
+0

に付加することにより、バックポストを埋めることができ、あなたは、AJAXを経由して、すべての記事を検索しますか? – linktoahref

+0

@linktoahref、whats up man、あなたは私を少し前に助けてくれました。まあまあですが、私はそれに限界を置くことができると確信しています。 – BARNOWL

+0

Onsuccessは取得したデータをdivに追加します。 – Bugfixer

答えて

1

postcontroller.php

$post = new Post(); 
$post->body = $request->body; $request->user()->posts()->save($post); 

//Retrieve Posts 
$responsePosts = Post::all(); // or limit here how many posts you would like to send back 

return response()->json($responsePosts); 

をapp.js

あなたがそれらを保存したら、投稿を取得し、アヤックスに戻ってそれを返します

投稿d ATAは

success: function (data) { 
    var posts = JSON.parse(data); 
    var temp = ''; 
    $.each(posts, function(prop, value) { 
    temp += "<h4>"+posts['username']+"</h4>"+ 
      "<p class='post-body'>"+posts['body']+"</p>"+ 
      "<div class='info'>made on"+posts['created_at']+"</div>"; 
    }); 
    $("article.post").html(temp); 

で利用できるようになりますそして、あなたは

<article class="post"></article> 
+0

私はObject、Object、Objectを取得し、console.log(data)を参照します。 – BARNOWL

+0

'var posts = JSON.parse(data);'を使用して応答を解析します。各投稿をループして各投稿情報を取得します。 – linktoahref

+0

成功:関数(データ){ var posts = JSON.parse(data); $( '#new-post')。val( ''); コンソール。ログ(投稿); }は動作しません:JSONの位置が予期しないトークンo – BARNOWL

1

であるあなたは(jqueryのAJAXを使用して、ポスト関連のデータやビューを取得することができます)laravelで非常に簡単のように:

jQueryのAJAX():

$.ajax({ 
    url: 'url('/fetchposts')', 
    type: "get", 
    data: { 
     key: value // pass the data here if you have any like: 
     //postId: postId, 
     //name: name 
    }, 
    success: function(data){ 

}); 

のroutes.php:

Route::get('/fetchposts',[ 
    'uses'=>'[email protected]' 
]); 

YourController.php:

public function fetchPosts() 
{ 
    // From this function either return the entire view with corresponding data into it 
     $posts = Post::orderBy('created_at', 'desc')->get(); 

    // Or return the JSON array and make the view in success of ajax and appedn it to your html 
     return response()->json($posts); 
} 
+0

私はキーのセクションで何を渡すのですか? – BARNOWL

+0

更新された回答を確認してください –

+0

私はちょうどそれをチェックしました。私のダッシュボードにあるものと同じ形式の投稿を出力することができます。 – BARNOWL

関連する問題