jquery - Get Ajax PHP response for file upload form -
i've created upload form text fields create custom posts frontend in wordpress.
the requst working, can't response message in ajax when file uploaded. if no file uploaded , text field set response.
here ajax form:
//upload-form.js _submit: function (event) { event.preventdefault(); this.$submitbutton.prop('disabled', true); var $formdata = false; var $form = this.$form; if (window.formdata) { $formdata = new formdata(); } var $files_data = this.$upload; if ($files_data.val() == '') { $formdata.append('fields', $form.serialize()); } else { $.each($($files_data), function (i, obj) { $.each(obj.files, function (j, file) { $formdata.append('files[' + j + ']', file); $formdata.append('fields', $form.serialize()); }) }); } $formdata.append('action', 'upload_form_submit'); $formdata.append('nonce', upload.form_nonce); $.ajax({ url: upload.ajaxurl, type: 'post', data: $formdata, datatype: "json", async: false, success: this._success.bind(this), error: this._error.bind(this), cache: false, contenttype: false, processdata: false }); return false; }, _success: function (jsonresponse) { var response = jsonresponse; if (response.type == 'success') { // clear fields this.$fields.val(''); this.$submitbutton.prop('disabled', true); // show message if (response.message) { $('.response-success').text(response.message); } } else { this._error(response.message); } return jsonresponse; }, _error: function (error) { this.$submitbutton.prop('disabled', false); // show message if (error) { if (typeof error === 'object') { $('.response-success').text(error.statustext); } else { // custom error $('.response-success').text(error); this.$form.find('*[required]').each(function (i, elem) { var $elem = $(elem); if (!$elem.val()) { $elem.parent().addclass('empty-field'); } }); } } }
my php response
/** * callback validate ajax request */ public function ajax_submit_form() { check_ajax_referer( 'form_submit', 'security' ); if ( !isset( $_post['fields'] ) ) { return; } $json = array(); // parse $.serialize() parse_str( $_post['fields'], $this->_post_fields ); // check if required fields not empty if ( $this->is_valid_data() ) { // save posts if ( $this->handle_frontend_new_post_form_submission() ) { $json['type'] = 'success'; $json['message'] = $this->_notices['post_sent']; } else { $json['type'] = 'error'; $json['message'] = $this->_notices['post_not_sent']; } } else { $json['type'] = 'error'; $json['message'] = $this->_notices['empty_fields']; } die( wp_json_encode( $json ) ); }
Comments
Post a Comment