I am trying to upload file using ajax in yii2. but it browser console it shows 400 Bad Request in my site_url what is my mistake.. Please help anyone.
var site_url = '<?php echo Url::to (['formdata/movefile','id'=>'']); ?>' + unic ;
var file_data = $('#formdata-'+ form + '-' + component + '-c_data').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: site_url, // point to server-side PHP script
dataType: 'TEXT', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: { form_data:form_data,_csrf : '<?=Yii::$app->request->getCsrfToken()?>'},
type: 'POST',
success: function(php_script_response){
alert(php_script_response);
}
});
I think you need to set contentType to json, as you are sending json data
contentType: "application/json"
So your ajax request will be something like this
$.ajax({ url: site_url, dataType: 'TEXT', cache: false, contentType: "application/json", processData: false, data: { form_data:form_data,_csrf : '<?=Yii::$app->request->getCsrfToken()?>'}, type: 'POST', success: function(php_script_response){ alert(php_script_response); }
You can also get 400 Bad request
error if you are not sending the data to server as described in its documentation. ( usually missing certain parameters or headers )
i found my mistake..
There was csrf token mistake in my controller action.. so i add this following code in controller
public function beforeAction($action)
{
if (in_array($action->id, ['movefile'])) {
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}
Now its working perfectly
Thanks to all :-)))))))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.