0

I have a form that is to be used to input information and register an account. The information is entered on the website and when the button 'register' is pressed it is validated by an external JavaScript method and afterwards, a PHP method is called using ajax which should take the information from the text boxes and enter it into the database. I can't seem to get the PHP getting the information working.

<?php
$mysqli = new mysqli('localhost:8080', 'root', null, 'salmonhouse');
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
$sql = "INSERT INTO clients (name, surname, email, address, password)
    VALUES (?,?,?,?,?)";

$name = $_POST['name'];
$surname = $_POST['surname'];
$email= $_POST['email'];
$address= $_POST['Address'];
$pass= $_POST['Password'];

$stmt = $mysqli->prepare($sql);
$stmt->bind_param("sssss", $name, $surname, $email, $address, $pass);
$stmt->execute();

?>

HTML textboxes

<form class="quote">

    <div class = inliner>
        <label>Name</label>
        <input id="name" type="text" placeholder="Name">
    </div>
    <div class = inliner>
        <label>Surname</label>
        <input id="surname" type="text" placeholder="Surname">
    </div>

    <div>
        <label>Email</label><br>
        <input id="email" type="email" placeholder="Email Address"><br>
    </div>

    <div>
        <label>Address</label><br>
        <input id="Address" type="email" placeholder="Home Address"><br>
    </div>


    <div class = inliner>
        <label>Password</label>
        <input id="Password" type="text" placeholder="Password">
    </div>
    <div class = inliner>
        <label>Verify Password</label>
        <input id="vPassword" type="text" placeholder="Password">
    </div>
    <br><button class="button_1" type="button" onclick="Validate()">Register</button>

</form>

Calling javascript file from html page

<script type= "text/javascript">
          var name = document.getElementById("name").value;
          var surname =document.getElementById("surname").value;
          var email =document.getElementById("email").value;
          var pass=document.getElementById("Password").value;
          var passV =document.getElementById("vPassword").value;
          var address=document.getElementById("Address").value;
      </script>
            <script type= "text/javascript" src="asset/js/my_javascript.js"></script>

Actual javascript file


/* eslint-env browser */
/*jslint devel: true */
/* eslint-disable */
function Validate(){
    name = document.getElementById("name").value;
    surname =document.getElementById("surname").value;
    email =document.getElementById("email").value;
    pass=document.getElementById("Password").value;
    passV =document.getElementById("vPassword").value;
    var error = "";

    document.getElementById("name").style.borderColor = "white";
    document.getElementById("surname").style.borderColor = "white";
    document.getElementById("email").style.borderColor = "white";
    document.getElementById("Password").style.borderColor = "white";
    document.getElementById("vPassword").style.borderColor = "white";



    var count= 0;
    if(name.length == 0){
        document.getElementById("name").style.borderColor = "red";
        count =1;
        error = error + "Name cannot be empty\n"

    }
    if(surname.length == 0 ){
        document.getElementById("surname").style.borderColor = "red";
        count =1;
        error = error + "Surname cannot be empty\n"
    }
    if(email.length == 0 ){
        document.getElementById("email").style.borderColor = "red";   
        count =1;
        error = error + "Email cannot be empty\n"
    }
    if(!(email.includes("@"))){
        document.getElementById("email").style.borderColor = "red";   
        count =1;
        error = error + "Email needs to contain an @ symbol\n"
    }
    if(!(email.includes("."))){
        document.getElementById("email").style.borderColor = "red";   
        count =1;
        error = error + "Email needs to comtain a .com or similar\n"
    }

    if(pass!==passV){
        document.getElementById("Password").style.borderColor = "red";
        document.getElementById("vPassword").style.borderColor = "red";
        count =1;
        error = error + "Passwords do not match\n"

    }
    if(!(pass.match(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%&*()])[0-9a-zA-Z!@#$%&*()]{8,}$/))){
        document.getElementById("Password").style.borderColor = "red";
        document.getElementById("vPassword").style.borderColor = "red";
        count =1;
        error = error + "Password must be atleat 8 long and contain a LowerCase, UpperCase, Number and a symbol."
    }
    if(false){
        alert("Please correct the following errors highlighted in red\n"+error);
    }
    else{
        alert("Name: " + name + "\nSurname: "+ surname + "\nEmail: "+ email+"\nPassword: "+pass+"\n Succesful Registration");
         xmlhttp = new XMLHttpRequest();
        var url = "asset/php/inserting.php";
        xmlhttp.open("GET",url,true);
        xmlhttp.send();

    }
}
/* eslint-enable */

This PHP file is a separate file with just this code. I have tested and if I manually set the variables instead of trying to retrieve them the data is successfully inserted into the database. So from my testing it is simply the retrieval not working. I also tried $_REQUEST['name']

This is the ajax/xmlhttprequest code.

xmlhttp = new XMLHttpRequest();
var url = "asset/php/inserting.php";
xmlhttp.open("POST",url,true);
xmlhttp.send();
12
  • $name = $_POST0['name']; can't be correct. Should be $_POST not $_POST0. What errors are you getting? Why not show the HTML? Commented Aug 4, 2019 at 14:12
  • Sorry That was a miss type. It is $name = $_POST['name']; Commented Aug 4, 2019 at 14:14
  • I don't see you sending any actual data with your call to send. Commented Aug 4, 2019 at 14:16
  • I am not sending any data. I would like the php to just get the information from the html boxes directly. I was insure of how to send the data. Is it not possible this way? Should I be sending it? Commented Aug 4, 2019 at 14:20
  • PHP can't read HTML form data directly. HTML form data is available at browser side and PHP executes at server side. Read HTML form data using Javascript and send PHP page using AJAX or just use an HTML form that posts data to the target PHP page. In your example, I do not see you are passing any data in the Ajax POST call. Commented Aug 4, 2019 at 14:25

2 Answers 2

1

My advice would be to use the jQuery library rather than XMLHttpRequest. You will need to include in the <head> section of your HTML a <script> tag to load the jQuery library from some CDN (Content Delivery Network). Also add id="f" to your <form> tag. Then your Ajax call can be as simple as:

$.ajax({
    type: "POST",
    url: 'asset/php/inserting.php',
    data: $('#f').serialize(), // serializes the form's elements.
    success: function(msg)
    {
        alert(msg); // show response from the php script.
    }
});
Sign up to request clarification or add additional context in comments.

4 Comments

Will I need to declare f in the javascript file as it is currently external?
Ok I combined what you said and Swati data: "name=" + name + "&surname=" + surname + "&email=" + email + "&Address=" + address + "&Password=" + pass, sends the variables and it is now working.
<form> => <form id="f">. No need to declare f.
@Tristan If you are not using my $('#f').serialize() code to serialize the form, then you better use data: "name=" + encodeURIComponent(name) + etc ..." as I indicated in an earlier comment or you might one day encounter data this will not work. This is why your version is not an improvement (and imagine if the form had 100 input fields).
1

You can attached the variable in ajax call, which you need to get in your php page using & for separating variable and = for assigning value .i,e :

 //attaching values to pass
    var data = "name=" + name + "&email=" + email + "&surname=" + surname + "&Address=" + Address + "&Password=" + Password;
    if (window.XMLHttpRequest) {

      request = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
      request = new ActiveXObject("Microsoft.XMLHTTP");
    }


    request.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
       //if success do something here 
  alert("save");
      }
    };

    var url = "asset/php/inserting.php";
    request.open("POST", url, true);
    //send data to php page
    request.send(data);

5 Comments

I would recommend passing each form element through a call to encodeURIComponent in case the values contain problematic characters. Also missing is an onreadystatechange handler.
I have now tried this. For some reason its just not working. I check that all the variables names are correct. The request is made but the php just is not getting the information into the variables.
Did you got any error ? Check your console , also check ajax request in network tab
var data = "name + encodeURIComponent(name) + &email= .... etc. "; because what happens if there is, for example, a '&' or '?' or some character that is not in the ASCII character set in one of the form values?
I check the console and did not find error, thanks anyway though. It is now working with jquery.

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.