miago
miago

Reputation: 119

Laravel Ajax POST Request does not work: 302 found

I'm trying to push some data via ajax in Laravel. Unfortunally it does not work. When I was watching at the network traffic, i found this:

Request Method:POST
Status Code:302 Found

I'm trying to get data from a JSGrid, which works fine. The data-object is filled. I checked it. For testing I just returned a short message in my controller. But it's not even called when I send the POST request...

Here is my code

Javascript:

$.ajaxSetup({
    headers: {'X-CSRF-Token': $('meta[name=token]').attr('content')}
});
$('#save_list').click(function (e) {
    e.preventDefault();
    var url = '{{ route("account.save_accounts_to_user") }}';
    var post = {};
    post.account_list = $("#jsGrid").jsGrid("option", "data");

    $.ajax({
        type: "POST",
        url: url,
        dataType: 'JSON',
        data: post,
        cache: false,
        success: function (data, textStatus, jqXHR) {
            console.log(textStatus + " - " + data);
            return data;
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(jqXHR.responseText + textStatus + " - " + errorThrown);
        }
    });
    return false;
});

Route:

Route::post('save_accounts_to_user', ['as' => 'account.save_accounts_to_user', 'uses' => 'AccountController@saveAccountsToUser']);  //ajax request   

Controller:

/**
 * Save all used accounts for a user.
 *
 * @param  \Illuminate\Http\Request $request
 * @return \Illuminate\Http\Response
 */
public function saveAccountsToUser(Request $request)
{
    $response = array();
    $response["status"] = "ok";
    $response["message"] = trans('account.accounts_saved');

    return \Response::json($response);
}

I was expecting that I will get the JSON text from the controller method as the responsemessage. But instead i get redirected without calling the wanted method. I don't know what happens there. There is no middleware assigned to this route, which could be the reason for this redirect.

Do you have an ideas?

Upvotes: 2

Views: 15926

Answers (4)

Yasin Patel
Yasin Patel

Reputation: 5731

Use headers in AJAX call

Example:

$.ajax({
   type: "POST",
   url: link, // your link
   data: DataObject, // data to pass
   headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
   },
   success: function (result) {
   }
});

Upvotes: 0

Shahrukh Hussain
Shahrukh Hussain

Reputation: 21

add this code:

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

after this:

var url = '{{ route("account.save_accounts_to_user") }}';

Upvotes: 0

miago
miago

Reputation: 119

After all it was a middleware of an outter group which was redirecting the request -.-

Upvotes: 6

JoshulSharma
JoshulSharma

Reputation: 173

May be 'X-CSRF-Token' used by you instead of 'X-CSRF-TOKEN' mentioned in Laravel docs is the issue here? Try to follow the Laravel docs completely.Please refer below link.

https://laravel.com/docs/5.3/csrf

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

Upvotes: 1

Related Questions