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'; }} ?>
var name = $(name).val();here you wrap thenamevariable 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"]')- Grundyid="name"&id="login"to the input and in the ajax request transfer thedata : { name : $("#name").val(), login: $("#login").val() }- teranvar data = $form.serialize()and the whole value withinputwill be written injsonformat in the variabledata. - x_ror