Nikolay Naydenov
Nikolay Naydenov

Reputation: 113

How to send ajax requests in laravel

I am trying to create a form that adds content to my database and then displays it without the page being refreshed (using laravel 4.2). However, I can't figure out how exactly to do it. When I submit the form I get to a blank page but the data is stored in the database.

here are my routes:

Route::get('/question/{id}', function($id){
$question=Question::getQuestion($id); //a model that retreives data from db
$answer=Question::getAnswers($id); //a model that retreives data from db
return View::make('question')->with('question',$question)->with('answer',$answer);
});

Route::post('/question/{id}','QuestionController@post_answer');

My controller:

public static function post_answer()
    {
        $data=Input::all();

        return Question::postAnswer($data);
    }

The form:

<form class="post_ans" action="{{'/question/'.$question[0]->question_id}}"         method="post">
 <textarea name="answer_content" rows="12"></textarea>
 <input type="hidden" name="this_question" value="{{$question[0]-     >question_id}}">
 <input type="submit" id="post_answer" value="Добави">

 </form>

My Jquery script:

$(document).ready(function(){    
    $('form.post_ans').on('submit',function(event){
        post_answer();
    });
});

function post_answer()
{
    var data={
        to_question:$('#this_question').val(),
        content:$('#answer_content').val()
    };
    console.log(data);
    var url= window.location.href;
    console.log(url);
    $.ajax({
        type:"POST",
        url:url,
        data:data
    }).done(function(){
        console.log("success!");
    }).fail(function(){
        console.log("Fail");
    }).always(function(){
        console.log("always");
    });
}

I get this in the console no matter whether I use preventDefault() or not:

Object {to_question: undefined, content: "<p>Teeeeeest</p>"}
http://laravel.dev/question/11
POST http://laravel.dev/question/11 500 (Internal Server Error)
    m.ajaxTransport.send
    m.extend.ajax
    post_answer
    (anonymous function)
    m.event.dispatch
    m.event.add.r.handle

Fail
always

I want my form to store data in the db and then immediately display it without the page being refreshed. Any suggestions?

Upvotes: 0

Views: 2459

Answers (2)

Kalhan.Toress
Kalhan.Toress

Reputation: 21901

because your submitting the form in to URL window.location.href; but i think you need to submit it to public static function post_answer(), I dont know why you append a parameter to a route like /question/1, you can pass as a POST parameter

so you need to change the URL of ajax,

CHANGE THE FORM DEFINITION

<form class="post_ans" action="{{ URL::to('/question') }}"  method="post">

OR

use laravel form builder which is much cleaner like,

Form::open(array('method' => 'POST', 'class' => 'post_ans','action' => 'QuestionController@postAnswer'))

OR

{{ Form::open(array('method' => 'POST', 'class' => 'post_ans','url' => 'question')) }}

CHANGE THE ROUTE

Route::post('question','QuestionController@postAnswer');

CHANGE THE JAVASCRIPT

$(document).ready(function(){    
    $('form.post_ans').on('submit',function(event){
        post_answer($(this).attr('action')); // pass the form action
        return false;
    });
});

function post_answer(action)
{
    var data={
         to_question:$('#this_question').val(),
         content:$('#answer_content').val()
    };
    console.log(data);
    var url= action;   // set the url to form action
    console.log(url);
    $.ajax({
        type:"POST",
        url:url,
        data:data
    }).done(function(){
        console.log("success!");
    }).fail(function(){
        console.log("Fail");
    }).always(function(){
        console.log("always");
   });
}

CONTROLLER FUNCTION

public function postAnswer()
{
    $data=Input::all();

    return Question::postAnswer($data);
}

Upvotes: 0

lukasgeiter
lukasgeiter

Reputation: 152860

The problem here is that even though the submit event gets triggered, right after it the page still refreshes because a "normal" submit happens. You can stop the default submit from actually happening by using preventDefault():

$('form.post_ans').on('submit',function(event){
    event.preventDefault();
    post_answer();
});

Upvotes: 1

Related Questions