Laravel Ajax Call to Controller

2019-07-30 18:44发布

I am pretty new with Laravel and I am having an issue with accessing a specific method in my Controller. I am trying to change a Database value (language) based on a dropdown menu.

settings.profile.blade

<select id="accountLanguage" class="form-control" method="GET">
    <option value="en" {{ ($strLanguage == 'en') ? 'selected = "selected"' : "" }} >English</option>
    <option value="es" {{ ($strLanguage == 'es') ? 'selected = "selected"' : "" }} >Español</option>
    <option value="he" {{ ($strLanguage == 'fr') ? 'selected = "selected"' : "" }} >French</option>
</select>

ProfileController

public function index() {

    $objUser = Auth::User();

    $strLanguage = $objUser->lang;

    return view("application.settings.profile",[
        'objUser' => $objUser,
        'strLanguage' => $strLanguage
    ]); 

}   

// THE METHOD I NEED ACCESS TO
function update( $strLang ) { 

    $objUser = Auth::User();

    // UPDATE LANGUAGE
    $bolUpdated = $objUser->updateLanguage( $strLang );

    // RETURN
    return response()->json( $bolUpdated );
 }

Route

Route::namespace( 'Settings' )->prefix( 'settings' )->group( function () {

    ...

    // PROFILE
    Route::resource( 'profile', 'ProfileController', ['only' => ['index','update']] );
    Route::get('test', 'ProfileController@update');
});

settings.profile.js

function initProfileManager() {

    // GET ELEMENTS
    var domUpdateLanguage = $('#accountLanguage');

    var updateLanguage = function() {

        // MAKE AJAX CALL
        $.ajaxq( {
            // url:'/settings/profile',
            url:'./test',
            method:'GET',
            success: function( bolUpdated ) { 
                if( bolUpdated ) { 
                    alert('OK');
                }   
            },  
            fail: function() {
                alert('NO');
            }   
         }); 
         location.reload();
    };  
    domUpdateLanguage.on( 'change', updateLanguage );

The way it currently is, I get this error Too few arguments to function App\Http\Controllers\Settings\ProfileController::update(), 0 passed and exactly 1 expected. I understand the error, but not sure how to pass the argument.

If I uncomment the url line from the JS, I never get into the update method and I just end up running index twice.

Any help would be appreciated.

EDIT 1

Strange. I tried defining a random value and it would still give me that error. I think you might be right and it is a syntax issue. Can't see why it would happen though.

function initProfileManage(strLang) {

    // GET ELEMENTS
    var domUpdateLanguage           = $('#accountLanguage');

    var updateLanguage = function() {

        // MAKE AJAX CALL
        $.ajaxq({
            // url:'/settings/profile',
            url:'./test',
            method:'POST',
            data: { 
                    strLang: newLang,
            }   
            success: function( bolUpdated ) { 
                if( bolUpdated ) { 
                    alert('OK');
                }   
            },  
            fail: function() {
                alert('NO');
            }   
         }); 
         location.reload();
    };  

    // UPATE LANGUAGE EVENT
    domUpdateLanguage.on( 'change', updateLanguage );
}

3条回答
地球回转人心会变
2楼-- · 2019-07-30 19:28

This is a complete answer to your question

Use a POST request instead of GET

Because you are updating the user's language it's more secure to use a POST request

// MAKE AJAX CALL
$.ajax( {
    // url:'/settings/profile',
    url:'./test',
    method:'POST',
    data: {
       strLang: newLang
    },
    success: function( bolUpdated ) { 
        if( bolUpdated ) { 
            alert('OK');
        }   
    },  
    fail: function() {
        alert('NO');
    }   
}); 

and don't forget to pass the strLang in your post request via the data attribute.

Protect against CSRF attacks

Store the csrf token in a HTML meta tag:

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

Automatically add the token to all request headers:

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

Create a route to handle your ajax request:

Route::post('test', 'ProfileController@update');

Get strLang via the $request object in your controller:

function update( $request ) { 

    $objUser = Auth::User();

    // UPDATE LANGUAGE
    $bolUpdated = $objUser->updateLanguage( $request->strLang );

    // RETURN
    return response()->json( $bolUpdated );
}

If you are using HTML5, your settings.profile.blade should look like this:

<select id="accountLanguage" class="form-control" method="GET">
    <option value="en" {{ ($strLanguage == 'en') ? 'selected' : '' }} >English</option>
    <option value="es" {{ ($strLanguage == 'es') ? 'selected' : '' }} >Español</option>
    <option value="he" {{ ($strLanguage == 'fr') ? 'selected' : '' }} >French</option>
</select>

In your index method, $objUser already contains the lang property

public function index() {

    $objUser = Auth::User();

    return view("application.settings.profile",[
        'objUser' => $objUser
    ]); 

}  

Getting the new lang from select element:

$('#accountLanguage').change(function () {
     initProfileManager(this.value);
});
查看更多
倾城 Initia
3楼-- · 2019-07-30 19:30

You should define language in the route

Route::get('test/{strLang}', 'ProfileController@update');` 

as well as pass it as a variable to the url in js code: '/test/' + strLang

查看更多
Summer. ? 凉城
4楼-- · 2019-07-30 19:32

Change your route to:

Route::post('test', 'ProfileController@update');

and your ajax object:

method:'POST',

You have to actually pass $strLang somehow, too (since the update() method expects this, as the error message states).

Oh, and you really don't need the method attribute in your select HTML ;)

查看更多
登录 后发表回答