9951 explained code solutions for 126 technologies


jqueryHow do I use a jQuery x-csrf-token?


Using a jQuery x-csrf-token requires setting the x-csrf-token header for each AJAX request. The token can be obtained from the server and stored in a variable.

// Get the x-csrf-token from the server
var csrfToken = $.get('/api/csrf-token');

// Set the x-csrf-token header for each AJAX request
$.ajaxSetup({
    headers: {
        'x-csrf-token': csrfToken
    }
});

To use the token, it must be set as a header in each AJAX request. The code above shows how to get the token from the server and set it as a header.

The following code shows an example of an AJAX request with the x-csrf-token header set:

$.ajax({
    type: 'POST',
    url: '/api/user',
    data: { name: 'John' },
    headers: {
        'x-csrf-token': csrfToken
    },
    success: function(data) {
        console.log(data);
    }
});

The code above sets the x-csrf-token header in the AJAX request. This allows the server to authenticate the request and process it correctly.

Helpful links

Edit this code on GitHub