That's what comes up Good afternoon, dear experts! Unfortunately, I don’t know much about programming and please help. I have a feedback form on the site, ajax + php, I also added the entry of the entered values ​​into the SQL database, but sometimes the values ​​come empty, although all the required fields, in the SQL database, empty records also sometimes appear. I can not localize the problem, how many times I did not try to send letters - everything is ok.

Here is my code

<form action="javascript:void(null);" id="form" class="form" name="FORM"> <input type="text" name="contact" required="required" id="input1" class="input" placeholder="E-mail или телефон" maxlength="30"> <textarea type="text" name="question" required="required" id="input2" class="input" placeholder="Напишите Ваш вопрос" maxlength="300"></textarea> <input type="submit" class="btn btn-success" value="Отправить"> </form> $(document).ready(function () { $("#form").submit(function () { //устанавливаем событие отправки для формы с id=form var form_data = $(this).serialize(); //собераем все данные из формы $.ajax({ type: "POST", //Метод отправки url: "php/mail.php", //путь до php фаила отправителя data: form_data, success: function () { //код в этом блоке выполняется при успешной отправке сообщения alert("Спасибо! Ответим, как только сможем :)"); show('none'); }, error: function (xhr, str) { alert('Error: ' + xhr.responseCode); } }); }); }); <? [![введите сюда описание изображения][1]][1]require 'c.php'; var_dump($_POST); { //Проверка отправилось ли наше поля $to = 'example@mail.ru'; //Почта получателя, через запятую можно указать сколько угодно адресов $subject = 'Обратный звонок'; //Загаловок сообщения $message = ' <html> <head><meta http-equiv="Content-Type" content="text/html; charset=utf8"> <title>'.$subject.'</title> </head> <body> <p>'.$_POST['contact'].'</p> <p>'.$_POST['question'].'</p> </body> </html>'; //Текст нащего сообщения можно использовать HTML теги $headers = "Content-type: text/html; charset=utf8 \r\n"; //Кодировка письма $headers .= "From: <contact@example.ru>\r\n"; //Наименование и почта отправителя mail($to, $subject, $message, $headers); //Отправка письма с помощью функции mail }; //соединение с базой $result = "INSERT INTO clients (mail) values('$contact')"; mysql_query($result); mysql_close($mysql); ?> 

I will attach two examples that SOMETIMES arrive in the mail and entered into the SQL database. Wiped addresses from detractors :)

  • And where is the code from this line: Проверка отправилось ли наше поля ? - lolbas
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky
  • I deleted it because was not sure of its correctness: ( - MaxiteMall
  • The problem was localized, data from iPhones does not come! - MaxiteMall

2 answers 2

You need to validate the data either on the server side or on the client side, but in general it is better both there and there,

On the server, we need to do validation because:

  • all your code on the client side - the client can simply disable or change to any code of his own at will.

on the client it is necessary to do validation because:

  • it makes no sense to send data to the server and carry out validation there, if not loading the server, validate it on the client. (they will not even ignore your validation on the client)

client side validation:

this

 $("#form").submit(function () { 

replaced by

 $("#form").submit(function () { if ($("#input1").val() && $("#input2").val()) { 

Well, add a closing bracket accordingly where necessary}

server side at the very beginning of the file:

 if (($_POST['contact'] == '') || ($_POST['question'] == '')) { //редирект назад с сообщением о ошибке валидации например так echo "<script>document.location='index.php?error=1';</script>"; } 
  • Thank you, does validation imply protection against SQL injection? In your example, we just check if the values ​​are not empty, right? - MaxiteMall
  • Yes, it was only about validation for fullness. - Lesiuk Alexey
  • Aha, it’s done, but I still don’t understand why empty values ​​came after all ... - MaxiteMall
  • There may be many variations ... you know how many browsers in the world? .... not only the main chrome firefox IE ... but there are many strange ones .... they just may not know the required tag - Lesiuk Alexey
  • That's the sad thing is that require nothing to do with it. On the other same form, selected checkboxes sometimes come, but without contact details, soon the carpet will start to eat from misunderstanding - MaxiteMall

The problem was that Safari does not understand the required and some inattentive users stupidly press "Send", did so https://stackoverflow.com/questions/23261301/required-attribute-not-work-in-safari-browser

  • with this solution, it is still possible to bypass the validation and you will again get the same result because testing only on the client side ... - Lesiuk Alexey
  • The point is not that someone has bypassed validation, but that, unknowingly, users could click the "order" button, misleading the site administration, which received empty requests. Scratching in the most indecent places when you lose customers because of such things :) - MaxiteMall