Emiliano Emiliano - 2 months ago 17
Javascript Question

How to use $.ajax(); function in laravel

I need add new object via ajax, but I don't know how to use $.ajax() function in laravel.

My form in blade templete is:

{{Form::open(array('url'=>'expense/add', 'method' => 'POST', 'class' => 'form-signin', 'id' => 'expenseForm'), array('role'=>'form'))}}
{{Form::select('period_id', $data['period'], null, array('class' => 'form-control'))}}
{{Form::select('expense_category_id', $data['categories'], null, array('class' => 'form-control'))}}
{{Form::text('date_expense', null, array('placeholder' => 'Fecha', 'class' => 'form-control'))}}
{{Form::text('amount', null, array('placeholder' => '¿cuanto fue?', 'class' => 'form-control'))}}
{{Form::hidden('user_id', Auth::user()->id)}}
<br />
{{Form::button('Add expense', array('class'=>'btn btn-lg btn-primary btn-block', 'id' => 'btnSubmit'))}}
{{Form::close()}}


My code in the controller is:

public function addExpense(){
$expense = new Expense;
$data = Input::all();

if ($expense->isValid($data)) {
$expense->fill($data);
$expense->save();
//Recargar la tabla gastos
return Redirect::to('expense/index')->with('success', 'El gasto ha sido agregado correctamente.');
}

return Redirect::back()->withInput()->withErrors($expense->errors);
}


And my js is:

$("#btnSubmit").click(submitExpenses);


this is my function submitExpenses

var submitExpenses = function(){
console.log("Llega aquí :O");
$("form#expenseForm").submit(function(){
$.ajax({
type: 'post',
cache: false,
dataType: 'json',
data: $('form#expenseForm').serialize(),
beforeSend: function() {
//$("#validation-errors").hide().empty();
},
success: function(data) {
console.log("Success!");
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
});
};


Thanks for help! :D

Answer

You need to change your ajax request and add a URL in which to submit the POST data to:

$.ajax({
    url: '/your/route/to/addExpense/method'
    type: 'post',
    cache: false,
    dataType: 'json',
    data: $('form#expenseForm').serialize(),
    beforeSend: function() { 
        //$("#validation-errors").hide().empty(); 
    },
    success: function(data) {
        console.log("Success!");
    },
    error: function(xhr, textStatus, thrownError) {
        alert('Something went to wrong.Please Try again later...');
    }
});

But thats not all

It looks like you built the form so that it would also accommodate non-javascript submissions. That's great, however, when you click the button not only will the ajax request get sent off, but the form will be submitted. Change your submitExpenses function to accept the event object as a parameter so that you can cancel the default action when you click the button:

var submitExpenses = function(e){
    e.preventDefault();
    ...

One more thing

When you submit a request via ajax, you'll receive a response back. In your controller you're actually redirecting the user, which you don't want to do when issuing an ajax request. In your request you're specifying that you want some return data to be sent back to you in json format. You need to change these lines in your controller:

return Redirect::to('expense/index')->with('success', 'El gasto ha sido agregado correctamente.');

and

return Redirect::back()->withInput()->withErrors($expense->errors);

To return some type of json object indicating success/failure.

However,

Like I said before, your form is capable of being submitted without Javascript enabled, so if you do change those lines in your controller you'll just have made it so those users will only see the json objects whenever they submit the form. The answer to that issue is to detect in your controller whether or not the submission was sent via ajax or not, and format the response appropriately:

public function addExpense(){
    $expense = new Expense;
    $data = Input::all();
    //$isAjax = Request::ajax();
    // It is probably better to use Request::wantsJson() here, since it 
    // relies on the standard Accepts header vs non-standard X-Requested-With
    // See http://stackoverflow.com/a/28606473/697370
    $isAjax = Request::wantsJson();

    if ($expense->isValid($data)) {
        $expense->fill($data);
        $expense->save();
        //Recargar la tabla gastos
        if($isAjax) {
            // Return your success JSON here
        } 

        return Redirect::to('expense/index')->with('success', 'El gasto ha sido agregado correctamente.');
    }

    if($isAjax) {
        // Return your fail JSON here
    } 
    return Redirect::back()->withInput()->withErrors($expense->errors);
}