最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Avoid page reload when submitting form using ajax with laravel - Stack Overflow

programmeradmin1浏览0评论

I'm pletely 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: 'ments',
            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'=>'ments', 'id' => 'ajax')) }}
        {{ Form::hidden('parent_id', null) }}
        {{ Form::hidden('author', Auth::user()->username) }}
        {{ Form::textarea('content', null, array('placeholder' => 'Enter your ment 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('ments')->withErrors($validator)->withInput(Input::all());
        }
        else {
            $ment = new Comment();
            $ment->parent_id = Input::get('parent_id');
            $ment->author = Input::get('author');
            $ment->content = Input::get('content');
            $ment->save();  
        }
}

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

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

}

And here is my routes:

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

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

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

I'm pletely 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: 'ments',
            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'=>'ments', 'id' => 'ajax')) }}
        {{ Form::hidden('parent_id', null) }}
        {{ Form::hidden('author', Auth::user()->username) }}
        {{ Form::textarea('content', null, array('placeholder' => 'Enter your ment 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('ments')->withErrors($validator)->withInput(Input::all());
        }
        else {
            $ment = new Comment();
            $ment->parent_id = Input::get('parent_id');
            $ment->author = Input::get('author');
            $ment->content = Input::get('content');
            $ment->save();  
        }
}

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

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

}

And here is my routes:

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

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

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

Share Improve this question edited Mar 23, 2014 at 15:24 user3446358 asked Mar 23, 2014 at 14:46 user3446358user3446358 711 silver badge4 bronze badges 13
  • Since you are using done() in your js, i think you should also return a status code return Response::json(Input::all(),200); – Dimitrios Kontoulis Commented Mar 23, 2014 at 14:54
  • @DimitrisKontoulis I tried what you said but still the same problem. – user3446358 Commented Mar 23, 2014 at 14:57
  • but you are doing nothing with the returned json. i can see that you are logging it in the console and nothing else. – Dimitrios Kontoulis Commented Mar 23, 2014 at 15:01
  • @DimitrisKontoulis Ok, and what should I do with the returned json? It's beyond my knowledge. – user3446358 Commented Mar 23, 2014 at 15:05
  • you have to parse it and display it as you wish. right now you are getting a json object, you can't expect it to show in your html on its own :P – Dimitrios Kontoulis Commented Mar 23, 2014 at 15:10
 |  Show 8 more ments

1 Answer 1

Reset to default 2
$(document).ready(function() {
    $('#ajax').submit(function(event){
        event.preventDefault();
        $.ajax({
            type: 'POST',
            url: 'ments',
            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.

发布评论

评论列表(0)

  1. 暂无评论