Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid page reload when submitting form using ajax with laravel

I'm completely stuck trying to process a form submit using ajax instead of laravel to avoid page reload etc. But it isn't working and I don't know why. I've searched the wonderful web going through example after example but nothing seems to be working for me. This is the closest I can get. My knowledge is limited but my ambitions are high. Please take a moment and look through my code, beacuse I'm at the edge of mental breakdown right now.

Here is my jquery:

$(document).ready(function() {
    $('#ajax').submit(function(event){
        $.ajax({
            type: 'POST',
            url: 'comments',
            data: $('form#ajax').serialize(),
            dataType: 'json',
        })

        .done(function(data) {
            console.log(data); 
        });

        event.preventDefault();
    });
});

And here is my form in blade view:

{{ Form::open(array('url'=>'comments', 'id' => 'ajax')) }}
        {{ Form::hidden('parent_id', null) }}
        {{ Form::hidden('author', Auth::user()->username) }}
        {{ Form::textarea('content', null, array('placeholder' => 'Enter your comment here:', 'onfocus' => 'this.placeholder=""')) }}<br/>
        {{ Form::submit('Comment', array('class'=>'submit')) }}
    {{ Form::close() }}

And here is my controller:

public function createComment() {
        //fixa här så man inte kan kommentera tom kommentar
        $validate = array('content' => 'required');

        $validator = Validator::make(Input::all(), $validate);

        if($validator->fails()) {
            return Redirect::to('comments')->withErrors($validator)->withInput(Input::all());
        }
        else {
            $comment = new Comment();
            $comment->parent_id = Input::get('parent_id');
            $comment->author = Input::get('author');
            $comment->content = Input::get('content');
            $comment->save();  
        }
}

public function postComment() { 
    if(Request::ajax()) {
            $this->createComment();
            return Response::json(Input::all());
    }
}

public function getCommentsAndForm() {
        $comments = Comment::orderBy('id')->get();
        return View::make('comment')->with('comments', $comments);

}

And here is my routes:

Route::get('comments', array('uses' => 'CommentController@getCommentsAndForm'));

Route::post('comments', array('uses' => 'CommentController@postComment'));

When I submit the form it dissapears and nothing displays. If I remove if(Request::ajax()) the comments get posted but the form still dissapears and instead of an empty page I get the posted comment in JSON. And when I reload the page the comments shows as I want to. What is the problem? What am I doing wrong? I only want the posted comment to display above my form without reloading the page, is there a solution?

like image 207
user3446358 Avatar asked Mar 23 '14 14:03

user3446358


People also ask

How to submit Form using Ajax without page refresh or page reload?

We will discuss how to submit a form using ajax without page refresh or page reload, we will use jquery submit handler with jquery validation rules for ajax form submission. We will also use csrf token in ajax form submission. And also work with laravel 5.8 version. In this step, we will create one model and migration name Contact.

How to restrict page reload in Laravel welcome page?

But we will use laravel default welcome page. So open welcome page and paste the following code. Here e.preventDefault (); use to restrict page reload. You can catch all the data using jQuery serialize () method. Now this is ready to work. Hope it will work for you.

How to add CSRF token in Ajax request in Laravel?

We can do this easily by laravel ajax form submit. So here we can submit the form by using jquery and also without the whole page refresh. So when we submit an ajax form in laravel application, then we will add csrf token in ajax request.

How to prevent the browser from reloading when a form is submitted?

Let’s say what we need to achieve is when the user submits this HTML form, we handle the submit event on client side and prevent the browser to reload as soon as the form is submitted Now, the easiest and the most reliable way of doing so is by tweaking our ValidateEmail () function to include the following line right at the top of its definition −


1 Answers

$(document).ready(function() {
    $('#ajax').submit(function(event){
        event.preventDefault();
        $.ajax({
            type: 'POST',
            url: 'comments',
            data: $('form#ajax').serialize(),
            dataType: 'json',
        })

        .done(function(data) {
            console.log(data); 
        });
        //just to be sure its not submiting form
        return false;
    });
});

the important here is to prevent form from submiting. You can try to change submit to button.

like image 155
katsarov Avatar answered Sep 28 '22 09:09

katsarov