Created
March 27, 2017 06:52
-
-
Save clodal/b5cb40ceb89a1980ba1c09fe72bb6ccd to your computer and use it in GitHub Desktop.
Yii ajax post to php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
return $.ajax({ | |
context: this, | |
type: 'post', | |
dataType: 'json', | |
url: this.$element.attr('action'), | |
data: $form.serializeArray(), // send data as a serialized array | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.'); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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