K
K
Konstantin Birzhakov2012-07-17 13:25:34
PHP
Konstantin Birzhakov, 2012-07-17 13:25:34

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>

I do validation with jquery:
$(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>

The validation itself is performed by the ajax.php file
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>

The question is: is it possible to combine the two technologies? Validate data using ajax, and send data and insert into the database on server.php? Of course, all validation is duplicated in my server.php, but I would like to make the script more user-friendly, without reloading the page in case of errors.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
P
pxx, 2012-07-17
@KonstRuctor

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');
  }
});

V
Vyacheslav Golovanov, 2012-07-17
@SLY_G

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.

W
winbackgo, 2012-07-17
@winbackgo

Use prebuilt form validation solutions like bassistance.de/jquery-plugins/jquery-plugin-validation/ .

A
Alex Shinkevich, 2012-07-17
@aleXoid

The first thing that comes to mind, instead of:
// ???? Here I need to submit the form to server.php
add
return true;

S
Sergey, 2012-07-17
Protko @Fesor

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 question

Ask a Question

731 491 924 answers to any question