I have such a problem that when sending the registration form via ajax, the name and login become "undefined" and, accordingly, cannot be added to the database. If you use only PHP, then everything works fine.

Tell me what could be the matter.

array(2) { ["name"]=> string(9) "undefined" ["login"]=> string(9) "undefined" } 

Form to send.

 <div class="transparent"> <div class="reg"> <p id="login">Регистрация</p> <form action="registration_test.php" method="post" id="formlogin"><br /> Введите имя:<br /> <input type="text" name="name" maxlength="20"> Введите логин: <input type="text" name="login" maxlength="20" required="required"> <input type="submit" value="Готово" name="send" id="submit"></p> <div id="success"></div> </form> </div> </div> 

File with ajax request.

 $(document).ready(function(){ $("#submit").click( function(){ var name = $(name).val(); var login = $(login).val(); var data= "name=" + name + "&login=" + login; $.ajax({ method: "post", url: "registration_test.php", data: data, success: function(data){ $("#success").html(data); } }); $("#formlogin").submit( function() {return false;} ); }); }); 

PHP handler.

 <?php /*session_start(); /* Создание сессий */ define("Server","localhost"); define("User","root"); define("Pass","12345"); define("DBname","registration"); require_once 'ConnectDB.class.php'; //создаём подключение $connect = ConnectDB::Connect(Server, User, Pass, DBname); $header = $connect->query("SET NAMES utf8"); $name = trim($_POST['name']); $login = trim($_POST['login']); echo '<pre>'; var_dump($_POST); echo '</pre>'; echo ($_POST['name']); if(!$login){ echo "Не заполнено обязательное поле"; } else{ $check = $connect->query("SELECT 'id' FROM users WHERE username='$login'"); $row = $check->fetch_array(); //Выбирает одну строку из результирующего набора и помещает ее в ассоциативный массив, обычный массив или в оба if (!empty($row["id"])) { echo "Извините, введённый вами логин уже зарегистрирован.<a href='reg.php'> Введите другой логин</a>."; } else{ $result = $connect->query("INSERT INTO users (username,name,whitelist) VALUES ('$name','$login', '1')") or die ( "Error : ".mysql_error() ); // Если все нормально то выводим сообщение. if($result){ //header("Location: index.php"); echo 'Успешная регистрация!'; ConnectDB::CloseConnect(); } else echo 'No'; }} ?> 
  • one
    var name = $(name).val(); here you wrap the name variable you just declared into the jquery object, and not the desired element. The selector can be replaced by $('[name="name"]') and similarly for login $('[name="login"]') - Grundy
  • Add the attributes id="name" & id="login" to the input and in the ajax request transfer the data : { name : $("#name").val(), login: $("#login").val() } - teran
  • use var data = $form.serialize() and the whole value with input will be written in json format in the variable data . - x_ror

1 answer 1

At event submit . For several years now I have been using similar code.

 $("#formlogin").submit(function(event) { // Prevent default posting of form - put here to work in case of errors event.preventDefault(); // Abort any pending request if (request) { request.abort(); } // setup some local variables var $form = $(this); // Let's select and cache all the fields var $inputs = $form.find("input"); // Serialize the data in the form var serializedData = $form.serialize(); // Let's disable the inputs for the duration of the Ajax request. // Note: we disable elements AFTER the form data has been serialized. // Disabled form elements will not be serialized. $inputs.prop("disabled", true); // Fire off the request to /form.php request = $.ajax({ url: "/form.php", type: "post", data: serializedData }); // Callback handler that will be called on success request.done(function(response, textStatus, jqXHR) { // Log a message to the console console.log("Hooray, it worked!"); }); // Callback handler that will be called on failure request.fail(function(jqXHR, textStatus, errorThrown) { // Log the error to the console console.error( "The following error occurred: " + textStatus, errorThrown ); }); // Callback handler that will be called regardless // if the request failed or succeeded request.always(function() { // Reenable the inputs $inputs.prop("disabled", false); }); });