0

I'm trying to add ajax to my method laravel. This method is creating a reply under a discussion page. It was working before the Ajax, now i want to add the ajax to make the reply very fast ! i'm stack because i tried a lot of method to pass the $id (discussion_id) but no one works !

i'm using laravel 5.6

my route is :

Route::post('/discussion/reply/{id}', [
    'uses' => 'DiscussionsController@reply',
    'as' => 'discussion.reply'
]);

my function controller is :

   public function reply($id)
{
    $this->validate(request(), [
        'reply' =>'required',
    ]);

    $d = Discussion::find($id);

    $reply = Reply::create([
        'user_id' => Auth::id(),
        'discussion_id' => $id,
        'content' => request()->reply
    ]);


    Session::flash('success', 'Votre réponse a été enregistrer avec success');

    //return redirect()->back(); // this is what i was doing doing before the ajax



    return response()->json(['success'=>'réponse ajouter']);
}

my JavaScript Ajax :

jQuery.ajax({
      url: "/discussion/reply/",
      method: 'post',
      data: {
        reply: jQuery('#reply').val(),
      },
      dataType: 'json',
      success: function(data){
              jQuery.each(data.errors, function(key, value){
                jQuery('.alert-danger').show();
                jQuery('.alert-danger').append('<p>'+value+'</p>');
            });
        }
    });

and finally my form blade html :

<form action="{{ route('discussion.reply', ['id' => $d->id]) }}" method="POST">
                        {{ csrf_field() }}

                        <div class="form-group">
                            <label for="reply">Laisser une réponse...</label>
                            <textarea name="reply" id="reply" cols="30" rows="10" class="form-control"></textarea>
                        </div>

                        <div class="form-group">
                            <button class="btn pull-right" id="submit">Répondre</button>
                        </div>
                    </form>
Noureddine
  • 31
  • 2
  • 7
  • You are calling the wrong url in the javascript `url: "/discussion/reply/"` – NULL Jun 30 '18 at 12:28
  • i call this url : {{ URL::route('discussion.reply', ['id' => $d->id]) }} but i got errors in my js file ! – Noureddine Jun 30 '18 at 12:29
  • is your script in the same blade.php file or is it in separated js file? – NULL Jun 30 '18 at 12:31
  • yes my script is loaded and everything work i have only the problem to figure out how the url will be in the ajax method – Noureddine Jun 30 '18 at 12:34
  • As you said your script is loaded then you should be able to fix your error. it the error related with `{{ }}` then convert it to ``, if `$d` not defined the put the right one. Any level of developer should be able to figure it out. – NULL Jun 30 '18 at 12:45
  • Secondly as this is a post req, you have to pass the `csrf_token` too otherwise the req won't reach the controller method – NULL Jun 30 '18 at 12:46
  • the problem is in the js, i pass the csrf_token : this is the error i got in my console : Uncaught SyntaxError: Unexpected identifier – Noureddine Jun 30 '18 at 12:54
  • see this one https://stackoverflow.com/questions/32738763/laravel-csrf-token-mismatch-for-ajax-post-request – NULL Jun 30 '18 at 12:58

1 Answers1

0

you can use this code .test please:

Ajax :

<script>
_token="{{csrf_token()}}";

$("form").submit(function(e){
    e.preventDefault();
    $.post("{{route('discussion.reply',['id' => $d->id])}}",
        {

            reply: $('#reply').val(),
            _token:_token
        },
        function(data, status){
            if(status=="success")
            {
                alert('success')
            }
            else
            {
                alert('show error')
            }

        });
});
</script>

DiscussionsController :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class DiscussionsController extends Controller
{
    public function reply(Request $request,$id)
    {
        $validator = Validator::make($request->all(), [
            'reply' => 'required',
        ]);

        if ($validator->fails())
        {
            return response()->json(['errors'=>$validator->errors()->all()]);
        }


        $d = Discussion::find($id);

        $reply = Reply::create([
            'user_id' => Auth::id(),
            'discussion_id' => $id,
            'content' => request()->reply
        ]);


        return response()->json(['success'=>'réponse ajouter'],200);
    }
}
Alihossein shahabi
  • 4,034
  • 2
  • 33
  • 53