14

I am trying to add comment using AJAX technology but I have an error: Failed to load resource: http://localhost:8888/blog/public/comment/add the server responded with a status of 500 (Internal Server Error) Here is my code: View:

{{ Form::open(array('method'=>'post','class'=> 'col-md-6','url' => '/comment/add', 'id'=>'comment')) }}
                        <input type="hidden" name="post_id" value="{{$id}}">
                        <div class="row">
                            <div class="inner col-xs-12 col-sm-12 col-md-11 form-group">
                                {{Form::label('name', 'Imię')}}
                                {{Form::text('username', null, array('class'=>'form-control', 'id'=>'name', 'name'=>'name'))}}
                            </div>
                            <div class="inner col-xs-12 col-sm-12 col-md-12 form-group">
                                {{Form::label('message', 'Wiadomość')}}
                                {{Form::textarea('message', null, array('class'=>'form-control', 'id'=>'message', 'name'=>'message', 'rows'=>'5'))}}
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-xs-12 col-md-12 submit form-group">
                                {{Form::submit('Wyślij', array('name'=>'submit', 'class'=>'btn btn-orange'))}}
                            </div>
                        </div>

                    {{ Form::close() }}

Controller:

public function addComment()
{
        $this->layout = null;
        //check if its our form
        if(Request::ajax()){
            $name = Input::get( 'name' );
            $content = Input::get( 'message' );

            $comment = new Comment();
            $comment->author =  $name;
            $comment->comment_content = $content;
            $comment->save();

            $postComment = new CommentPost();
            $postComment->post_id = Input::get('post_id');
            $postComment->comment_id = Comment::max('id');
            $postComment->save();

            $response = array(
                'status' => 'success',
                'msg' => 'Setting created successfully',
            );
            return 'yea';
        }else{
            return 'no';
        }
}

AJAX:

    jQuery( document ).ready( function( $ ) {

    $( '#comment' ).on( 'submit', function(e) {
        e.preventDefault();

        var name = $(this).find('input[name=name]').val();

        $.ajax({
            type: "POST",
            url: host+'/comment/add',
        }).done(function( msg ) {
            alert( msg );
        });

    });
});

And the last one routes:

Route::post('comment/add', 'CommentController@addComment');

Anyone have an idea where is the problem and why I can't submit my form?

6
  • value of host in javascript ? Commented Dec 7, 2014 at 18:29
  • <script> var host = "{{URL::to('/')}}"; </script> so it has http://localhost:8888/blog/public Commented Dec 7, 2014 at 18:32
  • A 500 error means there's likely to be a useful error message in your Laravel log. Check there. Commented Dec 7, 2014 at 18:32
  • You don't need the host, just try it like url: '/comment/add' Commented Dec 7, 2014 at 18:33
  • 1
    have you checked laravel log ? Commented Dec 7, 2014 at 18:34

2 Answers 2

29

You are not posting any data,

    $.ajax({
        type: "POST",
        url: host+'/comment/add',
    }).done(function( msg ) {
        alert( msg );
    });

The error you are getting is that the columns in DB cannot be null.

Try to change your ajax call to this:

    $.ajax({
        type: "POST",
        url: host+'/comment/add',
        data: { name:name, message:message, post_id:postid }, 
        success: function( msg ) {
            alert( msg );
        }
    });

Change this

var name = $(this).find('input[name=name]').val();

to

var name = $('#name').val();

and fetch the message and the post id:

var message = $('#message').val();
var postid = $('#post_id').val();

Complete ajax block:

   $('#comment').on('submit', function(e) {
       e.preventDefault(); 
       var name = $('#name').val();
       var message = $('#message').val();
       var postid = $('#post_id').val();
       $.ajax({
           type: "POST",
           url: host+'/comment/add',
           data: {name:name, message:message, post_id:postid}
           success: function( msg ) {
               alert( msg );
           }
       });
   });

And finally, add an ID to the hidden field:

<input type="hidden" name="post_id" id="post_id" value="{{$id}}">

Send data back from Laravel controller, eg.

    // ........

        $response = array(
            'status' => 'success',
            'msg' => 'Setting created successfully',
        );
        return Response::json($response);  // <<<<<<<<< see this line
    }else{
        return 'no';
    }
}

This will send the data in your response back to your ajax request.

Then, alter your ajax success function:

 // .......
 success: function( msg ) {
     $("body").append("<div>"+msg+"</div>");
 }

 // ..........

You will now see that a new div was created in your <body> including the created response. If you want to show the newly created post, just create it as the ajax response and append it to any element in your page.

Sign up to request clarification or add additional context in comments.

9 Comments

It works I dont have any errors but I have to refresh page to see new comment. Do you know why?
Because you only pass data to the controller, if you want to see the new comment directly, you need to send it back to your ajax request, catch it in the success function and output it. I will edit my post with a little example, I'm sure you will figure it out with that, give me a second. @Zobo . Please accept the answer if it has helped you
I've edited it. @Zobo try if you have success, if not feel free to ask again!
Ok I've got it but I have one more question. This is my SinglePostController pastebin.com/jfKU1dKy where I have relationship between comments and single post. How can I send back to ajax content of added comment and add +1 to comments that are belong to this post?
I think if you send your data this way, you will need to take care of csrf token also.
|
17

Just modifying the ajax block of baao's answer. You can pass data as serialized.

$('#comment').on('submit', function(e) {
    e.preventDefault(); 
    $.ajax({
        type: "POST",
        url: host+'/comment/add',
        data: $(this).serialize(),
        success: function(msg) {
        alert(msg);
        }
    });
});

All the field values of the form can be passed using the serialize() function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.