Create post with ajax and laravel

2

Greetings to all, I have an inconvenience with ajax and I am quite new with js, I have a comment system in laravel, I have already managed to edit the comments through ajax but now I have a problem when creating them, this is my code.

Here comments "including new ones" are displayed and edited or deleted.

<article class="row">
                        <div class="col-md-3 col-sm-3 hidden-xs">
                          <figure class="thumbnail">
                            <img class="img-responsive" src="/uploads/avatars/{{ $comment->user->profilepic  }}" />
                            <figcaption class="text-center">{{ $comment->user->name }}</figcaption>
                          </figure>
                        </div>
                        <div class="col-md-8 col-sm-8">
                          <div class="panel panel-default arrow left">
                            <div class="panel-body">
                              <header class="text-left">
                                <div class="comment-user"><i class="fa fa-user"></i> {{ $comment->user->name }}</div>
                                <time class="comment-date" datetime="{{ $comment->created_at->diffForHumans() }}"><i class="fa fa-clock-o"></i> {{ $comment->created_at->diffForHumans() }}</time>
                              </header>
                              <div id="comment-post" data-commentid="{{ $comment->id }}">
                                  <p id="display-comment"{{ $comment->id }} class="store-comment">{{ $comment->comment }}</p>
                              </div>
                            </div>

                            <div class="panel-footer list-inline comment-footer">
                              @if(Auth::guest())

                              No puedes responder ningún comentario si no has ingresado.

                              @else

                              @if(Auth::user() == $comment->user)
                                <a href="#" data-toggle="modal" data-target="edit-comment" class="edit-comment">Editar</a> <a href="#" data-toggle="modal" data-target="delete-comment" class="delete-comment">Eliminar</a>
                              @endif

                              @if(Auth::user() != $comment->user)
                                <a href="#">Responder</a>
                              @endif

                              @endif
                            </div>

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

                    </section>
                    @endforeach
                  </div>

Controller, store method:

public function store(Request $request, $post_id)
{

  $this->validate($request, [
  'comment' => 'required'
  ]);
  $post = Post::find($post_id);
  $comment = new Comment();
  $comment->comment   = $request->comment;
  $comment->approved  = true;
  $comment->user_id   =   auth()->id();
  $comment->post_id   = $request->post_id; // only if included
  $comment->save();
  return response()->json(['data'=> $comment->comment, $post->slug], 200);

}

JS:

First the code that I am using to create the comment:

var urlCreate = {{ url('comments/store') }};

$('.send').submit(function(){
  var comentario = $('#add-comment').val();
  $.ajax({
        type:'post',
        url: urlCreate,
        data: {
                comentario: comment,
            },
        success:function(data){
              $('#comment-post').append("<p class='store-comment" + data.comentario + "'>" + data.comentario + "</p>");
        },
          error: function(data){
             alert("Error Submitting Record!");
          }
   });
  });

Now to clarify any doubts I will publish the JS that I use to edit the comments, I put it by the variables created and the id's used:

var urlEdit = '{{ url('comments/update') }}';

$('.edit-comment').click(function(event){
  event.preventDefault();
  divcomment = this.parentNode.parentNode;
  commentId = $("#comment-post", event.target.parentNode.parentNode).data('commentid');
  var commentBody = $(divcomment).find('#display-comment').text();
  $('#comment').val(commentBody);
  $('#edit-comment').modal();
});

$('#modal-save').on('click', function(){
    var $btn = $(this).button('loading');
    var comment = $('#comment').val();
    $(this).button('loading');
    $.ajax({
        method: 'PUT',
        url: urlEdit,
        data: {
            comment: comment,
            commentId: commentId,
            _token: token,
            _method: 'PUT',
         },
        dataType: 'json'
    })
    .done(function (msg){
        if (msg.success === true) {
            $(divcomment).find('#display-comment').text(comment);
        }
        $btn.button('reset');
        $('#edit-comment').modal('hide');
        success('Comentario editado.', '.alert .alert-success', {timeOut: 5000});
    });
});

This also belongs to the JS to edit but I put it here because the code editor does not let me accommodate it:

var commentId = 0;

var divcomment = null;

Currently when I press the button to create the comment, it is sending me to localhost: 8000 / comments / id where "id" is the number of the comment and it throws me the content that was created in the following way:

{"data":"controller","0":"intel-anuncia-core-i9-extreme-edition-el-procesador-de-escritorio-mas-extremo-con-18-nucleos"}

Beforehand "intel-announce-core-i9-extreme-edition-the-desktop-processor-more-end-with-18-core" is the slug of the post where the comment is, on the basis of data is not reflected but it leaves me in the relation in which the post is found by means of the "post_id".

    
asked by Juan Rincón 11.06.2017 в 06:41
source

1 answer

0

First you must define the route you will receive data with post

It's simple just declare your route in the following way

Route::post('nombre_de_la_ruta',"tu_controlador_laravel@tu_función");

After you have defined the route you have to modify your function in the controller to receive the data

    public function generateReportXML()
    {

    if($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        $data = file_get_contents('php://input'); //Caputura los datos envidos. (recibios)  es un arreglo de datos
        $requestJSON = json_decode($data); // se convierte la cadena a json para poderla manipular.
//$data es el nombre puesto en la consulta
    }
//Esta es la respuesta json
        $response = 
        [
            'status' => true,
            'answer'  => 'El reporte a sido guardado correctamente' 
        ];

        return response()->json($response);
    //}
}

Once you have your driver defined and your route continues to ask.

Laravel requires a security token to send the data, this token here you can read more about this token link

You add it to your html as an input that can not be seen

<input type="hidden" name="_token" value="{{csrf_token()}}"></input>

this way you will have the security validation that laravel demands, and now the query

My query example will be with http (it's a special angularjs service that does the same as an ajax request, so it will not be a problem for your project)

 $http({
//Defines el metodo o como se enviara
            method: 'POST',
//la estructura del envio (esto es para definirlo como json)
            dataType: 'JSON',
//Tu url (la que definiste previamente)
            url: 'generateXML',
//Y tus datos, es importante que les des un nombre y que en el controlador lo leas de la misma forma
            data:
            {
//Separas cada dato con una coma, exceptuando el ultimo
                datos: "Hola mundo",
                name: "Como estas?"
            }
        })

And since you already have your ajax query, it is important that you define the route in your Route.php file, and that you define the function in your laravel driver

I wish you luck and if you have a problem or errror, do not hesitate to ask me.

Greetings

    
answered by 12.06.2017 в 18:09