2

I am creating a program and am having trouble passing user credentials into a database. I am using the AJAX .post function and for some reason, the data is not being passed into the PHP script.

The submitInfo() function seems to completely bypass the .post function nested inside, as the page does notify me with the successful sign in alert after pressing submit.

Here is the HTML/JS file, (doesn't show the implementation of jQuery along with an imported MD5 function I'm utilizing to hash the password):

<h2>First name:<h2>
<input id="firstNameInput" type="text" maxLength="20">

<h2>Last name:<h2>
<input id="lastNameInput" type="text" maxLength="20">

<h2>Create a username:<h2>
<input id="createUserInput" type="text" maxLength="20">

<h2>Create a password:<h2>
<input id="createPassInput" type="text" maxLength="20">
</br>
</br>
<input id="submitCredsButton" type="submit" onclick="submitInfo()">

<script>
function submitInfo()
{
var postData = [{
  firstName : document.getElementById("firstNameInput"),
  lastName : document.getElementById("lastNameInput"),
  username : document.getElementById("createUserInput"),
  hashPass : MD5((document.getElementById("createPassInput")).value)
}];

$.ajax({
  type: "POST",
  url: "phpScripts/signup.php",
  data: "postData",
  dataType: "text",
});

alert("Sign up Successful! Please log in to enter.");
window.open("login.php", "_self");
}
</script>

And here is the PHP script, in a separate file:

<?php
$servername = "*****";
$username   = "*****";
$password   = "*****";
$dbname     = "*****";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);    
  }

//posts data to db
$stmt = $data->('INSERT INTO userlist 
(firstName,lastName,username,hashedPass)
        VALUES (:firstName, :lastName, :username, :hashPass)');

$stmt->execute($data);
?>

-edit- Figured it all out, one simple but overlooked mistake I had was where I had placed the single and double quotes. Thanks to all users that helped with the JS issues I was having!

HTML/JS:

<h2>First name:<h2>
<input id="firstNameInput" type="text" maxLength="20">

<h2>Last name:<h2>
<input id="lastNameInput" type="text" maxLength="20">

<h2>Create a username:<h2>
<input id="createUserInput" type="text" maxLength="20">

<h2>Create a password:<h2>
<input id="createPassInput" type="text" maxLength="20">
</br>
</br>
<input id="submitCredsButton" type="submit" onclick="submitInfo()">

<script>
function submitInfo()
{
    var fName =  document.getElementById("firstNameInput").value;
    var lName =  document.getElementById("lastNameInput").value;
    var uName =  document.getElementById("createUserInput").value;
    var pPass =  document.getElementById("createPassInput").value;
    var hPass =  MD5((document.getElementById("createPassInput")).value);

if(fName.length <= 0 || lName.length <= 0 || uName.length <= 0 || pPass.length <= 0)
{
  alert("Please verify all fields have been filled out.");
}
else
{
  $.ajax
  ({
    type: "POST",
    url: "phpScripts/signup.php",
    data: {firstName: fName, lastName: lName, userName: uName, hashPass: hPass},
    dataType: "text",
    success: function(response)
      {
        alert("Sign up Successful! Please log in to enter.");
        window.open("login.php", "_self");
      }
  });
}




}
</script>

PHP Script:

<?php


$servername = "******";
$username = "******";
$password = "******";
$dbname = "******";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error); }

?>


<?php
//posts data to db
$fName = $_POST["firstName"];
$lName = $_POST["lastName"];
$uName = $_POST["userName"];
$hPass = $_POST["hashPass"];

$sql = "INSERT INTO userlist ( firstName,lastName,username,hashedPass )
        VALUES ( '$fName', '$lName','$uName','$hPass' )" ;

$result = $conn->query($sql);

if($result){
echo "true";
}
else{
echo "false";
}


?>
3
  • 2
    Change - data: "postData", - to - data: postData, and remove [ ] in your postData value. Commented May 29, 2018 at 5:37
  • document.getElementById returns DOM element. You should get the values of input. Try giving name attribute to input fields and then get their value as $('input[name="input-name"]').val(); using jQuery. Commented May 29, 2018 at 5:39
  • Show success message inside success callback of ajax. As it is asynchronous. Commented May 29, 2018 at 5:43

7 Answers 7

3

You have written "postData" in double quote, so it will consider as string, but actually it is variable.

Try :

$.ajax({
  type: "POST",
  url: "phpScripts/signup.php",
  data: postData,
  dataType: "text",
});
Sign up to request clarification or add additional context in comments.

1 Comment

exactly this is simple.
1

The problem is that you are using "postData" which is just a string but you need to use postData because it already has definition.

Just replace "postData"

with postData

Ajax

    $.ajax({
   type: "POST",
   url: "phpScripts/signup.php",
   data: postData,
   dataType: "text",
});

Comments

0

First problem. You are not passing a string to the $.ajax. You have to pass the variable which is an object: data: postData,.

Second problem. Your postData is an array but it has to be an object:

var postData = {
  firstName : document.getElementById("firstNameInput"),
  lastName : document.getElementById("lastNameInput"),
  username : document.getElementById("createUserInput"),
  hashPass : MD5((document.getElementById("createPassInput")).value)
};

Third problem. Your are passing DOM objects as postData instead of their values. Just use .value property:

var postData = {
  firstName : document.getElementById("firstNameInput").value,
  lastName : document.getElementById("lastNameInput").value,
  username : document.getElementById("createUserInput").value,
  hashPass : MD5((document.getElementById("createPassInput")).value)
};

Fourth problem. The $.ajax is asynchronous so you have to provide a success callback, so the callback will be run just after the finish of the request:

$.ajax({
    type: "POST",
    url: "phpScripts/signup.php",
    data: postData,
    dataType: "text",
    success: function () {
        alert("Sign up Successful! Please log in to enter.");
        window.open("login.php", "_self");
    }
});

Complete solution:

function submitInfo()
{
    var postData = {
      firstName : document.getElementById("firstNameInput").value,
      lastName : document.getElementById("lastNameInput").value,
      username : document.getElementById("createUserInput").value,
      hashPass : MD5((document.getElementById("createPassInput")).value)
    };

    $.ajax({
        type: "POST",
        url: "phpScripts/signup.php",
        data: postData,
        dataType: "text",
        success: function () {
            alert("Sign up Successful! Please log in to enter.");
            window.open("login.php", "_self");
        }
    });
}

3 Comments

Thank you for your help! This has helped me tremendously, however I am still not able to get the data posted. I have edited some of the PHP code for testing, where I hardcode strings (such as "testFirstName", "testLastName") into the database, and that works, however whenever I try and pull the variables that were supposed to be posted, it does not work
@A.Teoxon can you paste here what do you have in the $_POST variable when you submit the form?
I've actually figured it out! I'll edit the original post to show all the code that works. Thanks for your help!
0

$.ajax() in an asynchronous function. You need to use its success(result,status,xhr) callback to show actual success message.

What you are doing is show the success alert outside Ajax call.

The code should be:

$.ajax({
  type: "POST",
  url: "phpScripts/signup.php",
  data: postData,
  dataType: "text",
  success: function(html){
    $("#results").append(html);
  }
});

Comments

0

Your postData is an object does not need to so round in quotes "" and include a success call back and in success call back try to redirect on login page. Try this:

<script>
function submitInfo()
{
var postData = [{
  firstName : document.getElementById("firstNameInput"),
  lastName : document.getElementById("lastNameInput"),
  username : document.getElementById("createUserInput"),
  hashPass : MD5((document.getElementById("createPassInput")).value)
}];

$.ajax({
  type: "POST",
  url: "phpScripts/signup.php",
  data: postData,
  dataType: "text",
  success: function(response){
      alert("Sign up Successful! Please log in to enter.");
      window.open("login.php", "_self");
  }
});
}
</script>

3 Comments

A good answer includes an explanation of why the OP should try the code. What have you changed? Why?
@MagnusEriksson you can check my answer :)
Edited please check.
0

Basically you needs to get value of textboxs. And also in Ajax function you need to pass as a Object (Currently you are passing as String)

<script>
function submitInfo()
{
var postData = [{
  firstName : document.getElementById("firstNameInput").value,
  lastName : document.getElementById("lastNameInput").value,
  username : document.getElementById("createUserInput").value,
  hashPass : MD5(document.getElementById("createPassInput").value)
}];

$.ajax({
  type: "POST",
  url: "phpScripts/signup.php",
  data: postData,
  dataType: "text",
});

alert("Sign up Successful! Please log in to enter.");
window.open("login.php", "_self");
}
</script>

2 Comments

document.getElementById returns single DOM element of matching id, why are you treating its output as an array? It will throw an error.
@A. Teoxon Could you please take a look
0

You need to change

data: "postData",

With

data: postData,

And add success variable after dataType: "text",

success: function(res){
    if(res=="true"){
        alert("Sign up Successful! Please log in to enter.");
    }
    else{
        alert("something went wrong.");
    }
}

and add this line in your php script after $stmt->execute($data);

$result=$stmt->execute($data);
if($result){
    echo "true";
}
else{
    echo "false";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.