jQuery работает с PHP, но полученные данные не будут выполняться в нужном блоке
Благодаря комментариям я также добавил скрипт PHP - и отредактировал текст эха, благодаря другому комментарию:)
Это последнее утверждение здесь, так как я добился того, чего хотел. Объяснение в разделе комментариев, и я добавил новый код ниже. Спасибо!
У меня серьезные проблемы, потому что мой код работал до того, как я решил изменить "макет проекта" с помощью jQuery и некоторого Bootstrap. Мой jQuery ($.post()) в PHP работает нормально, это считается, потому что я получаю ответ - данные вставлены, проверка не пройдена или ошибка сервера. Основным вопросом здесь является ответ, который получает JQ. Ниже приведен фрагмент кода, но позвольте мне подчеркнуть, что здесь происходит.
Это 3 варианта (ответа), которые я ожидаю от PHP, которые возвращаются в виде строки типа данных - обратите внимание на текст в кавычках:
A) "revise_input" - недействительный адрес электронной почты или только a-zA-Z для имен и т. Д. B) "failed_insert" - технические ошибки сервера SQL || PHP. C) Этот ответ представляет собой строку, относящуюся к теме, выбранной пользователем в случае успеха. Для ясности пользователь отправляет сообщение с темой обратной связи, а взамен PHP выдает "Спасибо за отправку отзыва......" вместо "Спасибо за сообщение об ошибке" и т. Д. Это успешно - после вставки -> Идентификатор установлен - текст с переключателем. A и B - оба успешных выполнения с PHP, но они должны быть соответствующим образом выполнены jQuery.
После этого jQuery не выполнит правильный блок кода - он работал до изменений, и я тупо забыл сохранить файл резервной копии.
$(document).ready(function(){ // I've refrained from adding additional code above, but this where the trouble starts
$.post('php/validate_input2.php', { nm : nm, lnm : lnm, em : em, um : um, jh : jh, us : us, cb : cb}, function(data, status)
{
if(status === "success")// it will enter this code block without fault
{
if(data == "failed_insert" || data == "revise_input")// heed the comparison operators. I've tried === too but to no avail. jQuery will ignore this block of code even when I know the data echo'd is either 1.
{
if(data == "failed_insert")// as above with === I've tried it
{
alert("Server technical issues: " + data + " " + status); // I've left out all the fancy jQ magic for now if "failed_insert", but for testing I want to see this response here "as is".
}
else
{
alert("Fields have failed validation: " + data + " " + status); // I don't see this code block getting executed neither
}
}
else
{
alert("Data has been inserted: " + data + " " + status); // this is where EVERYTHING gets executed. This should only be shown if its not "revise_input" || "failed_insert" but one of various messages upon success of insert.
}
}
else
{
alert("Failed or other data response; irrelevant for now");//as the alert suggests, no issue here.
}
});
Как видите, здесь не должно быть проблем. Я даже протестировал типы, которые отправляются туда и обратно между PHP и jQ = string. Это то, что я получаю, но заменить? с "revise_input" || "failed_insert" || "Спасибо, что отправили что-то бла-бла-бла...." - окно предупреждения Windows:
На странице localhost написано: "Данные были вставлены:" Успех "
Вот скрипт PHP:
if($is_set === false){
echo "revise_input"; // this code block is executed if email isn't valid - of type string right?
}else{
switch($us){ // what to send back, after the script differentiates the users subject
case 'general':
$is_stored = "Great, your message was submitted successfully. You may receive an email response if a valid email was used.";
break;
case 'feedback':
$is_stored = "Thank you for your feedback. We appreciate all submissions, and may respond if necessary.";
break;
case 'ideas':
$is_stored = "Thank you for submitting your idea. Have you read about our terms on submitting <a href='privacy.php?from=contact_centre.php&subject=ideas&message=success#disclosure' alt='Privacy: Submittions'>ideas?</a>";
break;
case 'fault':
$is_stored = "Thank you for reporting a fault. We will endeavour to respond to this issue as soon as possible, if necessary.";
break;
default:
$is_stored = "Great, thank you for contacting us. You may receive an email response if a valid email was used.";
}
// everything below works fine, as I can see in my database using PHPMYADMIN during development
$vi_stmt = $con->prepare('INSERT INTO contact_centre (contact_name, contact_lastname, contact_email, contact_subject, contact_body, contact_news, contact_ip, contact_uua, contact_time, response_status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
$vi_stmt->bind_param('sssssissis', $nm, $lnm, $em, $us, $um, $cb, $ip, $ua, $dt, $st);
if($vi_stmt->execute() && $vi_stmt->insert_id){
if($cb == 1){
$vi_stmt = $con->prepare('SELECT e_id FROM e_news WHERE e_mail = ? LIMIT 1');
$vi_stmt->bind_param('s', $em);
$vi_stmt->execute();
$vi_stmt->store_result();
if($vi_stmt->num_rows < 1){
$vi_stmt = $con->prepare('INSERT INTO e_news (e_known, e_mail, e_name, e_lastname, e_confirm, e_token, e_string, e_ip, e_time, e_ua) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
$vi_stmt->bind_param('isssssssis', $cb, $em, $nm, $lnm, $st, $et, $es, $ip, $dt, $ua);
$vi_stmt->execute();
}else{
$vi_stmt->bind_result($id);
$vi_stmt->fetch();
$vi_stmt = $con->prepare('UPDATE e_news SET e_known = ?, e_name = ?, e_lastname = ?, e_confirm = ? WHERE e_id = ?');
$vi_stmt->bind_param('isssi', $cb, $nm, $lnm, $vst, $id);
$vi_stmt->execute();
}
}
if($us !== 'fault'){
$start_end = time() . '_' . strtotime('+6 hours', time());
setcookie('secure', $start_end, time() + 10800, '/'); // expires in +6 hours from execution; denies spamming, robots etc - fault reports allowed
}
echo $is_stored; // if insert is successful, it will echo the specific thank you
}else{
// else it will echo failed_insert - as in no insert, or execution etc
echo "failed_insert";
}
} ?>
Что-нибудь пошло не так? Заранее спасибо.
// все ниже было успешно, это просто фрагмент того, что было изменено. Это файл js:
$.post('php/validate_input.php', { nm : nm, lnm : lnm, em : em, um : um, jh : jh, us : us, cb : cb}, function(data){
if(data !== '3' && data !== '2'){
$('#hbContact').css('color', 'green').html(data);
}else{
if(data === '2'){
$('#hbContact').css('color', '#ff0000').html('Oops something went wrong. If the problem persists, please do try again later.');
}else{
$('#hbContact').css('color', '#ff0000').html('Oops something went wrong. Double check your email address; heed it\'s alphabet characters only for name.');
}
}
});
Вы можете представить мое разочарование, потому что это кажется слишком простым для создания; Я уверен, что это как-то связано с операторами сравнения и типами данных. Эхо PHP: 3 || 2 || "текстовая строка". "Текст" имеет тип string, а числа - целое число. Я позволил JS претендовать на число "строка", чтобы облегчить жизнь после использования данных typeof.