Skip to content

Instantly share code, notes, and snippets.

@clodal
Created March 27, 2017 06:52
Show Gist options
  • Save clodal/b5cb40ceb89a1980ba1c09fe72bb6ccd to your computer and use it in GitHub Desktop.
Save clodal/b5cb40ceb89a1980ba1c09fe72bb6ccd to your computer and use it in GitHub Desktop.
Yii ajax post to php
return $.ajax({
context: this,
type: 'post',
dataType: 'json',
url: this.$element.attr('action'),
data: $form.serializeArray(), // send data as a serialized array
});
public function actionHandleForm()
{
if (Yii::app()->request->isAjaxRequest) {
/**
* Get post data of `FooForm`
* Form should be set up with fields as such:
* @example:
* <input name="FooForm['field1']" />
* <input name="FooForm['field2']" />
*/
$data = Yii::app()->request->getPost('FooForm');
if ($data) {
return $data;
} else {
throw new CHttpException(400, 'Invalid request.');
}
} else {
throw new CHttpException(403, 'Forbidden.');
}
}
return $.ajax({
context: this,
type: 'post',
dataType: 'json',
url: this.$element.attr('action'),
data: { myData: $form.serialize() }, // <<< notice we are using object wrapper with key `data` and serialize() method instead
});
public function actionHandleForm()
{
if (Yii::app()->request->isAjaxRequest) {
/**
* Get post data without naming form
* In this method, inputs don't have to share a common name
* @example
* <input name="field1" ... />
* <input name="field2" ... />
* Native php function `parse_str` converts a serialized string
* into the object in the second argument. In this case `$data`.
*/
parse_str(Yii::app()->request->getPost('myData'), $data);
if ($data) {
return $data;
} else {
throw new CHttpException(400, 'Invalid request.');
}
} else {
throw new CHttpException(403, 'Forbidden.');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment