I register using ajax и json .

But $_POST['reg-name'] and other empty values. But when outputting in console.log (data) with an ajax request, the data is displayed.


If you uncomment the conditions in the signup.php file, nothing happens at all. ajax у словия в success: ... not work ajax у словия в success: ...


include / signup.php:

 <?php session_start(); if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { require_once $_SERVER['DOCUMENT_ROOT'] . '/include/db.php'; header('Content-Type: application/json; charset=utf-8'); $connect = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname); $_SESSION['logged'] = false; $haserror = false; if (!$connect) die(); $name = $_POST['reg-name']; $surname = $_POST['reg-surname']; $email = $_POST['reg-email']; $pass = $_POST['reg-pass']; $date = date('Ymd H:i:s'); file_put_contents( 'debug' . time() . '.log', var_export( print_r($_POST), true)); // Здесь все условия я позначил как комментарии, чтобы посмотреть в чем дело. Оказалось, что переменные с данными о пользователе пустые, по-этому и не срабатывал preg_match(); //if (preg_match("/^([a-z0-9_\.-]+)@([a-z0-9_\.-]+)\.([az\.]{2,6})$/", $email)){ //if (preg_match("/^[А-ЯІЇ]{1}[А-яії'-]{2,}$/u", $name)){ //if (preg_match("/^[А-ЯІЇ]{1}[а-яії'-]{2,}$/u", $surname)){ // if (preg_match("/([A-z0-9-_']{6,})/i", $pass)){ // echo json_encode("success-in"); $sql = "SELECT * FROM `users` WHERE `email` = $email"; $res = mysqli_query($connect, $sql); $count = mysqli_num_rows($res); if ($count == 0){ $sql = "INSERT INTO `users` (`email`, `password`, `name`, `surname`, `date`) VALUES ('$email', '$pass', '$name', '$surname', '$date')"; mysqli_query($connect, $sql); $_SESSION['user-id'] = mysqli_insert_id($connect); $_SESSION['user-name'] = $name; $_SESSION['user-surname'] = $surname; $_SESSION['user-email'] = $email; $_SESSION['logged'] = true; echo json_encode("success"); } else echo json_encode("id-error"); // } else $haserror = true; // } else $haserror = true; //} else $haserror = true; // } else $haserror = true; if ($haserror) echo json_encode("value-error"); mysqli_close(); exit; } else { include_once $_SERVER['DOCUMENT_ROOT'].'/include/error/404.php'; } ?> 

A piece of index.php :

  <div class="col-md-4 col-md-offset-1"> <div class="place-error"></div> <form id="reg-form"> <div class="form-group"> <input type="text" class="form-control" name="reg-name" placeholder="Ім'я" pattern="^[А-ЯІЇ]{1}[А-яії'-]{2,}$" required> </div> <div class="form-group"> <input type="text" class="form-control" name="reg-surname" placeholder="Прізвище" pattern="^[А-ЯІЇ]{1}[А-яії'-]{2,}$" required> </div> <div class="form-group"> <div class="input-group margin-bottom-sm"> <span class="input-group-addon"><i class="fa fa-envelope-o fa-fw"></i></span> <input name="reg-email" class="form-control" type="email" placeholder="Email" pattern="^([a-z0-9_\.-]+)@([a-z0-9_\.-]+)\.([az\.]{2,})$" required> </div> </div> <div class="form-group"> <input id="register1" type="password" class="form-control" name="reg-pass" placeholder="Пароль" pattern="([A-z0-9-_']{6,})" required> </div> <div class="form-group"> <input id="register2" type="password" class="form-control" name="reg-pass-sec" placeholder="Повторіть пароль" pattern="([A-z0-9-_']{6,})" required> </div> <div class="checkbox"> <label> <input id="checkbox1" type="checkbox" required> Я згідний з правилами проекту </label> </div> <button id="reg-btn" type="submit" class="btn btn-success">Створити профіль</button> <button type="reset" class="btn btn-danger"><i class="fa fa-trash-o"></i></button> </form> </div> 

Well, the Ajax itself:

 <script> $(document).ready(function($) { // register $('#reg-form').submit(function (e) { var isCheck = $('#checkbox1').prop('checked'); if (isCheck) { e.preventDefault(); var data = $("#reg-form").serialize(); $.ajax({ url: 'include/signup.php', type: 'POST', dataType: 'json', data: data, success: function (data) { if (data == "value-error") $('.place-error').html('<p>Ви ввели невірні дані.</p>'); else if (data == "id-error") $('.place-error').html('<p>Такий профіль уже існує.</p>'); else if (data == "success") location.reload(); else if (data == "success-in"){ console.log("SUCCESS-IN"); } console.log("Nothing was happen 2"); } }); } }); }); </script> 

Where is the mistake?

  • one
    At the moment, your signup.php gives the following: "success-in""success""success"true . Use echo json_encode ($ result) only once, at the very end, and in $ result, transfer the necessary values ​​depending on your logic. - P. Fateev
  • @ P.Fateevb Yes, I noticed it. But did not pay enough attention. Hurray, it worked!) Give a complete answer and I will receive it as true :) Thank you. - user242433

3 answers 3

In the signup.php file, you use echo json_encode() in several places. Since these places are not mutually exclusive everywhere, you may not get exactly what you expect at the exit.

Use echo json_encode($result) only once, at the very end, and in $result transfer the necessary values ​​depending on your logic.

    You did not specify the method of sending data, try this

     <form action="" id="reg-form" method="post"></form> 
    • I indicated this in an ajax-запросе . I tried and so .. No, it did not help! - user242433
    • You have no buttons defined, that is, you have to assign a name to the button and use the isset to check whether the button was pressed and then receive the values ​​from the form. - verstala
    • Once done without it, it worked without isset. But now I will try - user242433

    Your code works, the post array is filled. $ _POST ['reg-name'] is full, see for yourself:

     http://jsfiddle.net/xQmYH/ 

    The i nclude / signup.php file contains the condition if (!$connect) die(); Check, you are not confused

     require_once $_SERVER['DOCUMENT_ROOT'] . '/include/db.php'; 

    with

     require_once $_SERVER['HTTP_HOST'] . '/include/db.php'; 

    ?

    • No, not confused. I look here, in the base tag I changed the path to the site, because wrote in PHPStorm, on <head><base href="http://localhost/"></head> . And he started working, although he does not return json- строки . Look, I threw it on the hosting - inbusiness.zzz.com.ua - user242433