Bryce
Bryce

Reputation: 447

JQuery $.post() issue, nothing is performed

I am having a small problem with my jQuery function, and below is the code:

function registerUser()
{
    var formData = $('#registerForm').serialize();
    var dataPost = $.post('classes/login.php', {type:'register', data: formData} ,function (data)
    {
        console.log(data);
    });
};

Then my login.php file looks like:

$type = $_POST['type'];
$email = $_POST['data']['0'];
$password = $_POST['data']['1'];

function register_user($email, $password)
{
 global $db;
//lets add some code to register user
    $stmt = $db->prepare("INSERT INTO user (email, password, role, banned) VALUES (:email, :password, 'level1', 'N')");
    $stmt->execute(array(':email'=> $email, ':password'=> $password));
    $rowCount  = $stmt->rowCount();
   if($rowCount > 0)
   {
    // Success
    //  set session data and etc.
    return "success";
   }
   else
   {
    //  Failed
    return "Error, please try again!";
   }
}
$result = register_user($email, $password);

When I executed it I did not get any errors or anything but a simple blank line that does not show any data and the data does not get inserted into the database?

Upvotes: 1

Views: 61

Answers (2)

jagad89
jagad89

Reputation: 2643

You want to post extra parameter with form serialization.

function registerUser()
{
    var formData = $('#registerForm').serializeArray();
    formData.push({name: 'type', value: 'register'});
    var dataPost = $.post('classes/login.php', formData ,function (data)
    {
        console.log(data);

    });
};

Now Server side update

$type = $_POST['type'];
$email = $_POST['LoginEmail'];
$password = $_POST['LoginPassword'];

function register_user($email, $password)
{
 global $db;
//lets add some code to register user
    $stmt = $db->prepare("INSERT INTO user (email, password, role, banned) VALUES (:email, :password, 'level1', 'N')");
    $stmt->execute(array(':email'=> $email, ':password'=> $password));
    $rowCount  = $stmt->rowCount();
   if($rowCount > 0)
   {
    // Success
    //  set session data and etc.
    return "success";
  }
  else
  {
//  Failed
    return "Error, please try again!";
  }
}
$result = register_user($email, $password);

Reference: click here

Upvotes: 3

chrisjacob
chrisjacob

Reputation: 170

You are not calling that function, it's just there. You need to put

register_user($email, $password);

at the bottom of your .php page.

And even better: update your function to return true or false instead of "success" and "Error, please try again!". And then you can have the following

if(register_user($email, $password)){
    echo "success";
} else {
    echo "failure";
}

Upvotes: 1

Related Questions