2

I am trying to use jquery to perform ajax call to a magento rest api from a custom backend (admin) module. For some reason, every time I perform ajax call, the query parameter isAjax=true automatically gets appended to the url, and &form_key=mJRSj3FScbiIKWsl automatically gets appended to my request payload. Is there any way I can prevent this?

  • The form_key param needed to prevent csrf. The isAjax in most cases used to determine type of content for response. – joni jones Jun 14 '16 at 20:28
6

Magento 2 adds the form key and the isAjax by using jQuery's beforeSend handler. to remove it override the beforeSend handler with and empty function for example. You can also put the form_key in the url to prevent csrf:

echo $block->getUrl('destination/path/index', ['form_key' => $block->getFormKey()]);

Here is an example to send JSON data:

jQuery.ajax({
    url: destinationUrl,
    method: 'post',
    data: JSON.stringify(data),
    contentType: 'application/json; charset=UTF-8',
    showLoader: true,
    beforeSend: function(xhr){
        //Empty to remove magento's default handler
    }
}).done(function (resp) {
    //handle success scenario
}).fail(function (resp) {
    //handle failure scenario
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.