简体   繁体   中英

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?

毕竟它是一个外部组的中间件,它正在重定向请求-.-

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')
    }
 });

add this code:

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

after this:

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

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) {
   }
});

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM