I'm struggling very hard to get this to work and I don't know what I'm doing wrong. I have a register page that I want to take the data inserted into the form and INSERT it to the database with jQuery and AJAX. I'm not very experienced with AJAX AND jQuery so be gentle! :P I will show you the files that I have...

sign_up.php

<?php
    include 'connect.php';
    include 'header.php';

    echo '<h2>Register</h2>';

    if($_SERVER['REQUEST_METHOD'] != 'POST')
    {
        echo '<br/>';
        echo '
        <div class="container">  
        <form id="submit" method="post" action="">  
        <fieldset>  
        <legend> Enter Information </legend>  
        <br/>
        <label for="user_name">Your username: </label>
        <br/>
        <input id="user_name" class="text" name="user_name" size="20" type="text">
        <br/>
        <br/>
        <label for="user_pass">Your password: </label>
        <br/>
        <input id="user_pass" class="text" name="user_pass" size="20" type="password">  
        <br/>
        <br/>
        <label for="user_pass_check">Confirm password: </label>
        <br/>
        <input id="user_pass_check" class="text" name="user_pass_check" size="20" type="password">
        <br/>
        <br/>
        <label for="user_email">Email: </label>
        <br/>
        <input id="user_email" class="text" name="user_email" size="20" type="email">
        <br/>
        <br/>
        <button class="button positive" type="submit"> <img src="like.png" alt=""> Register </button>  
        </fieldset>  
        </form>  
        <div class="success" style="display: none;"> You are now a registered user!</div>  
        </div>';
    }
    else {
        $errors = array();
        //Checks the errors
        if(isset($_POST['user_name']) == NULL)
        {
                $errors[] = 'Please enter your username.';
        }   

        //Checks the password
        if(isset($_POST['user_pass']) == NULL)
        {
                $errors[] = 'Please enter your password.';
        }
        else
        {
                if($_POST['user_pass'] != $_POST['user_pass_check'])
                {
                    $errors[] = 'The two passwords did not match.';
                }
        }

        if(!empty($errors)) //Checks for empty fields
        {
                echo 'Please check that all the fields are filled in.<br /><br />';
                echo '<ul>';
                foreach($errors as $key => $value) //walk through the array so all the errors get displayed
                {
                        echo '<li>' . $value . '</li>'; //this generates a list with errors
                }
                echo '</ul>';
        }
 }
?>

in my header.php (which I include in every page) I included

$(document).ready(function(){  
        $("form#submit").submit(function() {

        // we want to store the values from the form input box, then send via ajax below  
        var user_name = $('#user_name').val();  
        var user_email = $('#user_email').val();
        var user_pass= $('#user_pass').val();

        //$user_name = $('#user_name').val();
        //$user_email = $('#user_email').val();
        //$password = $('#password').val();

        alert(user_name);

            $.ajax({  
                type: "POST",  
                url: "ajax.php",  
                data: "user_name="+ user_name +"&user_email="+ user_email +"$user_pass=" + user_pass,  
                success: function(){  
                    $('form#submit').hide(function(){$('div.success').fadeIn();});  
                }  
            });

            //alert("ji");

        return false;  
        });  
});

and then my ajax.php that gets the data and must insert it into the database but it doesn't! :(

<?php
        include 'connect.php';
        include 'header.php';

        // CLIENT INFORMATION  
        $user_name  = $_POST['user_name'];  
        $user_email   = $_POST['user_email'];  
        $user_pass   = $_POST['user_pass'];  

        mysql_query("INSERT INTO
                      users(`user_name`, `user_pass`, `user_email` , `user_date` , `user_level`)
                VALUES('$user_name', '$user_pass', '$user_email', NOW() , 0)" OR trigger_error(mysql_error())); 
?>

The PROBLEM here is that it does not INSERT the values into my users table

Dani AI

Generated

Nice catch by on the parameter delimiter; that explains why $_POST['user_pass'] was empty. Building on that and @diafol/’s debugging ideas, make the request and response more robust and you’ll save time tracking issues. Two quick client tips: prevent the native submit and serialize the form so you do not hand‑assemble query strings, and expect JSON back so you can branch on success vs. error cleanly. See jQuery’s .serialize() description for why this avoids missing fields and encoding bugs. (api.jquery.com)

Example client script (distinct from code above):

$('#submit').on('submit', function (e) {
  e.preventDefault();
  $.ajax({
    url: 'ajax.php',
    type: 'POST',
    data: $(this).serialize(),
    dataType: 'json'
  }).done(function (res) {
    if (res.ok) { $('#submit').hide(); $('div.success').fadeIn(); }
    else { console.error(res.error || 'Insert failed'); }
  }).fail(function (xhr) {
    console.error('AJAX error:', xhr.status, xhr.responseText);
  });
});

On the server, do not include layout output (e.g., header.php) in ajax.php; return JSON only. Also, the old mysql_* API is long deprecated/removed, so switch to PDO (or MySQLi) with prepared statements and hash the password before storing. (php.net)

Minimal PDO example:

<?php
require 'connect.php'; // create $pdo (PDO) with ERRMODE_EXCEPTION
header('Content-Type: application/json');

if (!isset($_POST['user_name'], $_POST['user_email'], $_POST['user_pass'])) {
  http_response_code(400);
  echo json_encode(['ok' => false, 'error' => 'Missing fields']); exit;
}

$username = trim($_POST['user_name']);
$email    = filter_var($_POST['user_email'], FILTER_VALIDATE_EMAIL);
$hash     = password_hash($_POST['user_pass'], PASSWORD_DEFAULT); // bcrypt/Argon2

if (!$email || $hash === false) {
  http_response_code(422);
  echo json_encode(['ok' => false, 'error' => 'Invalid input']); exit;
}

$stmt = $pdo->prepare(
  'INSERT INTO users (user_name, user_pass, user_email, user_date, user_level)
   VALUES (:u, :p, :e, NOW(), 0)'
);
$stmt->execute([':u'=>$username, ':p'=>$hash, ':e'=>$email]);

echo json_encode(['ok' => true]);

password_hash() chooses a strong algorithm by default; verify with password_verify() on login. (php.net)

Recommended Answers

All 3 Replies

Member Avatar for Member #120589
success: function(data){
   alert(data);

If you use that you'll catch any error from the ajax.php file if it outputs an error to the screen. *I think*.

check the order of the final statement in your ajax file. It should read

mysql_query("INSERT INTO
                      users (`user_name`, `user_pass`, `user_email` , `user_date` , `user_level`)
                VALUES('$user_name', '$user_pass', '$user_email', NOW() , 0)") or trigger_error(mysql_error());

Or my personal preference is as follows for query structure.

mysql_query("INSERT INTO users SET 
`user_name`='$user_name', 
`user_pass`='$user_pass', 
`user_email`='$user_email', 
`user_date`=NOW(), 
`user_level`=0") or trigger_error(mysql_error());

ON your actual ajax call I am not familiar with this format. I personally use Javascript to run my ajax calls.

your original code(ajax code):

        $.ajax({  
            type: "POST",  
            url: "ajax.php",  
            data: "user_name="+ user_name +"&user_email="+ user_email +"$user_pass=" + user_pass,  
            success: function(){  
                $('form#submit').hide(function(){$('div.success').fadeIn();});  
            }  
        });

changing to :

$.ajax({
type: "POST",
url: "ajax.php",
data: "user_name="+ user_name+ "&user_email="+ user_email +"&user_pass=" +user_pass,
success: function(data){
    //alert(data);
$('form#submit').hide(function(){$('div.success').fadeIn();});

}
});

your query code:

mysql_query("INSERT INTO
users(`user_name`, `user_pass`, `user_email` , `user_date` , `user_level`)
VALUES('$user_name', '$user_pass', '$user_email', NOW() , 0)" OR trigger_error(mysql_error())); 

channging to :

mysql_query("INSERT INTO users(`user_name`, `user_pass`, `user_email`, `user_date`, `user_level`) VALUES('{$user_name}', '{$user_pass}', '{$user_email}', NOW() , 0)"); 

Note:
-YOu already use wrong data passing $user_pass= , should use &user_pass , that's y cant pass the value to the ajax.php.

-Please include the bracket with the variable passing into the query also.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.