Before for submitting I want to send the request to an action. But in return I get 404 not found
. The action is obviously there. Also got it in the filters of the controller.
JS:
$('#home-contact').on('beforeSubmit', function(){
$.ajax({
method: 'post',
url: '/site/send-contact',
data: new FormData($(this))[0],
success: function(data){
console.log(data)
}
})
return false
})
Controller filters:
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'signup', 'send-contact'],
'rules' => [
[
'actions' => ['signup', 'send-contact'],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
And the action also :
public function actionSendContact()
{
Yii::$app->response->format = Response::FORMAT_JSON;
$model = new Contact();
if($model->load(Yii::$app->request->post()) && $model->save()){
return $data['success'] = Yii::t('app', 'Successfully sent message.');
}
return $data['error'] = Yii::t('app', 'Something went wrong. Please try again.');
}
The scenario happens in the frontend if that matters somehow. Thank you!
URL in JavaScript seems to be not fully specified.
The valid way would be:
But this works only if your
index.php
is in root folder.To make it work with any situation (e.g., index.php is not in root), then you have different solutions. I personally like to use this:
action
andid
in your form:Example:
Example:
This should work in all cases, whenever your files are.
Hope that helps!
Not sure about the
404
you are having as the url in the request is correct and the url that would be generated for the ajax request will be likehttp://example.com/site/send-contact
but only if you are using the'enablePrettyUrl' => true,
for theurlManager
component, otherwise it should be likeindex.php?r=site/index
that could only be the reason behind the404
, a better way is to get the url from the formaction
attribute.Apart from above,
You are using the
new FormData()
to send the data with the request likewhich isn't correct and won't send any
FormData
with the request as it will returnundefined
, you can check theconsole
or by using theprint_r($_POST)
inside the actionsendContact
once you are done with the404
, it should beyou need to get the form via
$(this)[0]
and pass to thenew FormData()
.But this is not enough you have to set the
contentType
andprocessData
to befalse
to correctly submit theFormData
or you will get the exception in consoleSo your code should be like
EDIT
Note: Above all you should use
data:$(form).serialize()
simply rather than usingnew FormData()
until unless you are planning to upload files along with the form using ajax.did you add
'enableAjaxValidation' => true
or add action name in active form?