Answer the question
In order to leave comments, you need to log in
Is it possible to do form validation in jquery and submit in php?
For example, there is such a form, with a field of type file:
<div id="my_error"></div><br>
<form id="my_form" action="server.php" enctype="multipart/form-data" method="post"><br>
Ваш НИК <input type="text" name="username"><br>
Ваш E-mail <input type="text" name="email"><br>
Прикрепите файл <input type="file" name="userfile"><br>
<input type="hidden" name="action" value="sendform"><br>
<input type="submit" name="OK"><br>
</form><br>
$(document).ready(function(){<br>
$('#my_form').submit( function (e){<br>
e.preventDefault();<br>
var str = $(this).serialize();<br>
$.ajax({<br>
type: "POST",<br>
url: "/ajax.php",<br>
data: str,<br>
success: function(msg) {<br>
$("#my_error").ajaxComplete(function(event, request, settings) {<br>
if ( msg == 'OK' ) {<br>
// ???? Здесь мне надо отправить форму на server.php<br>
}<br>
else {<br>
$(this).html(msg);<br>
}<br>
});<br>
}<br>
});<br>
return false;<br>
});<br>
});<br>
if ( $_POST['action'] && $_POST['action'] == 'sendform' ) {<br>
$error = '';<br>
// опустим очистку переменной $_POST['username'] от мусора, это не важно в данном случае<br>
if ( !$_POST['username'] ) $error .= "<li>Не заполнен НИК</li>";<br>
if ( $_POST['username'] ) {<br>
// тут коннектимся к базе, проверяем занятость ника, может ли юзер вообще посылать файлы и так далее и так далее<br>
}<br>
if ( !$error ) echo "OK";<br>
else echo "<div class=\"err\">Ошибка! ".$error."</div>";<br>
}<br>
Answer the question
In order to leave comments, you need to log in
It is possible like this:
$('#my_form').submit( function (e, data){
if (data == 'silent') return true;
e.preventDefault();
...
if (valid) {
$('#my_form').trigger('submit', 'silent');
}
});
If I understand the question correctly, then you can first receive a response from ajax.php through Ajax.
If it is, say, “OK”, then we send POST to server.php
Otherwise, we issue the result of ajax.php to the browser.
Use prebuilt form validation solutions like bassistance.de/jquery-plugins/jquery-plugin-validation/ .
The first thing that comes to mind, instead of:
// ???? Here I need to submit the form to server.php
add
return true;
First of all, yes you can.
Secondly, there is a whole mountain of ready-made plugins for jQuery.
Thirdly, to make it all good, google about the required attribute and input type="email" for more convenient validation in modern browsers. There are fallback scripts for IE.
Validation of files directly is possible if the browser supports the FileAPI. Tobish all major versions of browsers (IE7-9 is not supported, the 10th is not sure, but it seemed to be in the tablets).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question