i'm trying to do an api call using ajax on admin page, but it keeps returning "Invalid form key"
<script type="text/javascript">
require([
 "jquery"
], function ($){
 let url = window.location.href;
 url = url.split('/');
 url = url.slice(2,4);
 url = url.join('/');
 console.log("URL -> "+(url+"/rest/V1/orders"));
 $('#button').on('click', function(){
 $.ajax({
 url: url+"/rest/V1/orders",
 data: {
 "entity":{
 "entity_id": <?php echo $order_id; ?>,
 "status":"processing",
 "state":"processing"
 }
 },
 type: 'POST',
 headers: {
 "Content-Type": "application/json",
 "Authorization": "Bearer "+ '" + <?php echo $token; ?> + "'
 },
 success: function(response){
 console.log(response);
 },
 error: function (xhr, status, errorThrown) {
 console.log('Error happens. Try again.');
 }
 });
 });
});
Tried this way, but also didn't work.
<script>
 var settings = {
 // "url": "http://"+url+"/rest/V1/orders",
 "url": url+"/rest/V1/orders",
 "method": "POST",
 "timeout": 0,
 "headers": {
 "Content-Type": "application/json",
 "Authorization": "Bearer "+token
 },
 "data": JSON.stringify(
 {
 "entity":{
 "entity_id": order_id,
 "status":"processing",
 "state":"processing"
 }
 }
 ),
 };
 jQuery.ajax(settings).done(function (response) {
 console.log(response);
 }); 
update So i found out that, the token string parse was wrong, i fixed it, but know my problem is other, its returning Bad Request, Decoding error: \nUnable to unserialize value. Error: Syntax error...
So i created another question: Ajax api call returning Bad Request decoding error
- 
 Did you checked the ajax by calling a simple controller?Mehran– Mehran2021年12月11日 07:41:15 +00:00Commented Dec 11, 2021 at 7:41
- 
 @Mehran, no i didn't, how could i check it ?Rafael Fagundes– Rafael Fagundes2021年12月13日 11:35:16 +00:00Commented Dec 13, 2021 at 11:35
- 
 Are you in phtml file or in js file?Mehran– Mehran2021年12月13日 11:45:35 +00:00Commented Dec 13, 2021 at 11:45
- 
 @Mehran, phtml file.Rafael Fagundes– Rafael Fagundes2021年12月13日 12:28:23 +00:00Commented Dec 13, 2021 at 12:28
- 
 1Instead of Window.location.href get the base url by this way $block->getBaseUrl(); and then check. or $block->getUrl('rest/V1/orders') .Mehran– Mehran2021年12月13日 12:35:23 +00:00Commented Dec 13, 2021 at 12:35
2 Answers 2
I don't know how much this will help you but try passing form_key: window.FORM_KEY in your data part
Thanks
- 
 1It returns the same error: "Invalid Form Key. Please refresh the page."Rafael Fagundes– Rafael Fagundes2021年12月13日 11:36:15 +00:00Commented Dec 13, 2021 at 11:36
- 
 Try using this "Magento\Backend\App\Action" as your ajax controller extendsNilesh Dubey– Nilesh Dubey2021年12月13日 20:38:20 +00:00Commented Dec 13, 2021 at 20:38
You need to add form_key to the data you upload data:
{
 ""form_key"": window.FORM_KEY
 ""entity"":{
 ""entity_id"": <?php echo $order_id; ?>,
 ""status"":""processing"",
 ""state"":""processing""
 }
 },