Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Send Data to Controller via AJAX Without Form

I need to send data via JS to a Laravel controller on a button click. I'm not using any form because the data is being created dynamically. Every time i try to send the data, i get an Internal Server Error (500), but unable to catch that exception in the controller or the laravel.log file.

Here's what i'm doing:

Route:

Route::post('section/saveContactItems', 'SectionController@saveContactItems');

Controller:

public function saveContactItems($id, $type, $items, $languageID = "PT"){ ... }

JS:

$('button').on("click", function (evt) {

    evt.preventDefault();

    var items = [];
    var id = $("#id").val();
    var languageID = $("#languageID").val();
    var data = { id: id, type: type, items: JSON.stringify(items), languageID: languageID };

    $.ajax({
        url: "/section/saveContactItems",
        type: "POST",
        data: data,
        cache: false,
        contentType: 'application/json; charset=utf-8',
        processData: false,
        success: function (response)
        {
            console.log(response);
        }
    });
});

What am i doing wrong? How can i accomplish this?

UPDATE: Thanks to @ShaktiPhartiyal's answer (and @Sanchit's help) i was able to solve my issue. In case some else comes into a similar problem, after following @Shakti's answer i wasn't able to access the data in the controller. So, i had to stringify the data before sending it to the server:

data: JSON.stringify(data),
like image 917
Ricky Avatar asked Apr 04 '17 17:04

Ricky


1 Answers

You do not need to use

public function saveContactItems($id, $type, $items, $languageID = "PT"){ ... }

You have to do the following:

public function saveContactItems()
{
    $id = Input::get('id');
    $type = Input::get('type');
    $items = Input::get('items');
    $languageID = Input::get('languageID');
}

and yes as @Sanchit Gupta suggested you need to send the CSRF token with the request:

Methods to send CSRF token in AJAX:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

If you use this approach you need to set a meta tag like so:

<meta name="csrf-token" content="{{csrf_token()}}">

or

data: {
        "_token": "{{ csrf_token() }}",
        "id": id
        }

UPDATE

as @Sanchit Gupta pointed out use the Input facade like so:

use Input;
like image 150
Shakti Phartiyal Avatar answered Oct 21 '22 06:10

Shakti Phartiyal