Thursday, April 13, 2017

how to fetch posts in laravel using ajax?

I managed to successfully add ajax into laravel, the following code adds a post via ajax, without page refresh, adds it to the database, however im a bit clueless on how to fetch the posts that i submitted via ajax.

Any Suggestions, no error shows up, i just cant fetch the post via 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 );
      }
  }


}

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></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="" name="_token">
                </form>
                



                @foreach($posts as $post)
                        <article class="post">
                         <h4></h4>
                            <p class="post-bod">
                                
                            </p>
                            <div class="info">
                               made on 
                            </div>
                   </article>


                @endforeach


            </div>


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

@endsection

and here is the route

Route::post('/createpost',[

    'uses' => 'PostController@postCreatePost',
    'middleware' => 'auth'

]);



via Owl Man

Advertisement