Я создал форму, которая записывает адрес электронной почты в файл CSV и отправляет через AJAX (используя jquery.form.js ) с некоторыми сообщениями проверки JSON.
Я успешно протестировал форму на своем локальном сервере, а также на корневом сервере моего сайта. Однако при переносе формы внутри темы WordPress форма застревает с сообщением «загрузка ...»
Удаление следующего кода заставляет форму отправлять A-OK, но побеждает цель, поскольку она ничего не записывает в CSV без этого кода. Я установил права доступа ко всем задействованным файлам (emails.csv, submit.php, а также содержащим папки WP) на 777, но кажется, что WordPress вызывает некоторую ошибку, связанную с 'fopen'
Также обратите внимание, что в настоящем файле я использую абсолютный URL-адрес для файла .CSV, но намеренно пропустил его здесь - я уже подтвердил, что он указывает на нужный файл.
Код проблемы:
//open the file
$file = "emails.csv";
$fh = fopen($file, 'a') or die('fail:noFile');
//remove any commas from the input and save to file with a preposition ","
$em = preg_replace('/,/', ' ', $_POST['email']);
$li = '
'.$em;
if (fwrite($fh, $li)) {
}
//close the file
fclose($fh);
Код Submit.php
<?php
if ($_POST) {
// response hash
$response = array('type' => '', 'message' => '');
try {
// do some sort of data validations, very simple example below
$required_fields = array('email-address');
foreach ($required_fields as $field) {
if (empty($_POST[$field])) {
throw new Exception('Required field "' . ucfirst($field) . '" missing input.');
}
}
// ok, field validations are ok
// now add to data to DB, Send Email, ect.
// let's assume everything is ok, setup successful response
$response['type'] = 'success';
$response['message'] = 'Thank-You for submitting the form!';
//open the file
$file = "emails.csv";
$fh = fopen($file, 'a') or die('fail:noFile');
//remove any commas from the input and save to file with a preposition ","
$em = preg_replace('/,/', ' ', $_POST['email']);
$li = '
' . $em;
if (fwrite($fh, $li)) {
}
//close the file
fclose($fh);
}
catch (Exception $e) {
$response['type'] = 'error';
$response['message'] = $e->getMessage();
}
// now we are ready to turn this hash into JSON
print json_encode($response);
exit;
}
?>
Пользовательский файл JS
function setupAjaxForm(form_id, form_validations) {
var form = '#' + form_id;
var form_message = form + '-message';
// en/disable submit button
var disableSubmit = function (val) {
$(form + ' input[type=submit]').attr('disabled', val);
};
// setup loading message
$(form).ajaxSend(function () {
$(form_message).removeClass().addClass('loading').html('Loading...').fadeIn();
});
// setup jQuery Plugin 'ajaxForm'
var options = {
dataType: 'json',
beforeSubmit: function () {
// run form validations if they exist
if (typeof form_validations == "function" && !form_validations()) {
// this will prevent the form from being subitted
return false;
}
disableSubmit(true);
},
success: function (json) {
$(form_message).hide();
$(form_message).removeClass().addClass(json.type).html(json.message).fadeIn('slow');
disableSubmit(false);
if (json.type == 'success') $(form).clearForm();
}
};
$(form).ajaxForm(options);
}
$(document).ready(function () {
new setupAjaxForm('newsletterForm');
});
HTML
<form method="post" action="<?php bloginfo('wpurl'); ?>/submit.php" id="newsletterForm">
<div class="inner">
<div id="newsletterForm-message"></div>
<p class="tagline">get quarterly tlm updates</p>
<div class="input-box">
<input type="text" name="email-address" />
</div>
<div class="submit">
<input type="submit" value=" " />
</div>
</div>
</form>