vendredi 27 juillet 2018

Laravel 5 App - AJAX Post Request not accepting the token and throwing a 500 internal server error

So, I've been looking on here for the better part of 3 hours as to why my code isn't working. I don't think my ajax request is detecting my CSRF token even though i've tried multiple ways to implement it. New to AJAX requests so go easy.

Goal: Submit an ajax POST request to /email/subscribe/ and add the email address provided by the user to the email_subscribers table.

I've tried adding the following to my code to get the token to show up:

The meta tag and the Ajax Setup.

Top of the file

<meta name="csrf-token" content="">

In the script tag INSIDE the jquery $(document).ready() function

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

Hidden input field

I've also added a hidden input field and tried to insert the token inside the data object inside the ajax post.

HTML

<input type="hidden" id="token" value="">

Javascript tag

var token = $('#token').val();
// var token = $('meta[name="csrf-token"]').attr('content'); //Tried this way

$.ajax({
    type: 'POST',
    url: '/email/subscribe/',
    dataType: 'json',
    data: {
        email: email,
        '_token': token,
        // "_token": "", //Tried this way as well
        "_method": 'POST',
    },
    success: function (data) {
        // Check Server Side validation
        if($.isEmptyObject(data.errors)){
            console.log(data['success']);
        }else{
            // Validation Failed Display Error Message
            console.log(data.errors);
        }

    },
    error: function (data) {
        console.log(data);
    }
}); // End Ajax POST function

Here is my web.php file

// Email Routes
Route::prefix('email')->group(function() {

    // Create Post Route for subscribing
    Route::post('/subscribe', 'EmailSubscriptionsController@subscribe')->name('email.subscribe');

});

and my EmailSubscriptionsController

class EmailSubscriptionsController extends Controller
{
    // Store the Email into the database
    public function subscribe(Request $request) {

        // Validate the request
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
        ]);

        // If the validation fails
        if($validator->fails()) {
            return response()->json([
                'errors' => $validator->errors()->all(),
            ]);
        }

        // New Section Object
        $subscription = new EmailSubscription;

        // Add Name into Section Object
        $subscription->email = $request->email;

        // Save the Section
        $subscription->save();

        // Return The Request
        return response()->json([
            'success' => 'Record has been saved successfully!'
        ]);
    } // End Subscribe

} // End Controller

Whats really weird is the fact that when i submit the request with NOTHING but the following in my subscribe() function inside my controller:

// Return The Request
    return response()->json([
        'success' => 'Record has been saved successfully!'
    ]);

It doesn't return an error.... Just passes the success message to the console. I'm not sure what i'm doing wrong as I have this working (an ajax post request) in another portion of my site.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2LLpP6M
via IFTTT

Aucun commentaire:

Enregistrer un commentaire