1

I'm trying to submit a form using AJAX. If I'm using the submit button it saves it, but if I'm using AJAX the form isn't saved.

This works (the form is saved into the DB)

<!DOCTYPE html>
<html>
<head>
<meta content="text/html" />
<meta charset="utf-8" />

<title>HotSpot</title>

</head>
<body>

     <form accept-charset="utf-8" name="mail" action="http://10.30.20.30:8080/Site/anti-xss.php" method="post" id="mail">
        <h1>Hotspot</h1>
        <h2>To gain internet access, enter your email.</h2>
        <br />
        <input type="text" id="email" name="email" autofocus="autofocus" />
        <br />
        <input type="submit" value="Submit" id="submit_ok" name="submit_ok" /> <br />
    </form>
</body>
</html>

This does not work (the data isn't saved into the DB), but the console.log writes:

Start AJAX!

Success!

You'r email is something@some.one.

XHR2 4

XHR2 200

AJAX sent!

<!DOCTYPE html>
<html>
<head>
<meta content="text/html" />
<meta charset="utf-8" />

<title>HotSpot</title>

</head>
<body>
     <form accept-charset="utf-8" name="mail" onsubmit="return false;" method="post" id="mail">
        <h1>Hotspot</h1>
        <h2>To gain internet access, enter your email.</h2>
        <br />
        <input type="text" id="email" name="email" autofocus="autofocus" />
        <br />
        <input type="button" value="Submit" id="submit_ok" name="submit_ok" /> <br />
    </form>

<script>

document.getElementById("submit_ok").addEventListener("click", sendAjax);

async function sendAjax() {
    console.log("Start AJAX!");
    let ax2 = await Ajax2 ("POST", "http://10.30.20.30:8080/Site/anti-xss.php")
    console.log("AJAX sent!");
}

function Ajax2 (method, url){
    return new Promise (function (resolve, reject){
        let xhr2 = new XMLHttpRequest();
        xhr2.open('POST', 'http://10.30.20.30:8080/Site/anti-xss.php', true);
        xhr2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr2.onload = function(){
            if(this.status >= 200 && this.status < 300){
                resolve(xhr2.response);
                console.log("Success!");
                console.log("You'r email is " + useremail + ".");
                console.log("XHR2 " + xhr2.readyState);
                console.log("XHR2 " + xhr2.status);
            }else{
                reject({
                    status: this.status,
                    statusText: xhr2.statusText
                });
            }
        };
        xhr2.onerror = function (){
            reject({
                status: this.status,
                statusText: this.statusText
            });
        };
        let useremail = document.getElementById("email").value;                 
        xhr2.send("Email="+encodeURIComponent(useremail));
    });
}

</script>   

</body>
</html>

PHP - connect.php

<?php
header('Access-Control-Allow-Origin: *');
$host = "localhost";
$userName = "root";
$password = "";
$dbName = "baza";
// Create database connection
    $DB = new mysqli ($host, $userName, $password, $dbName);
    //$conn = new mysqli($host, $userName, $password, $dbName);
// Check connection
    if ($DB->connect_error) {
        die("Connection failed: " . $DB->connect_error);
    }
?>

PHP - anti-xss.php

<?php

    require ('connect.php');

    $clean_email = "";
    $cleaner_email = "";


    if(isset($_POST['email']) && !empty($_POST['email'])){
        //sanitize with filter
        $clean_email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
        //sanitize with test_input
        $cleaner_email = test_input($clean_email);
        //validate with filter
        if (filter_var($cleaner_email,FILTER_VALIDATE_EMAIL)){
            // email is valid and ready for use
            echo "Email is valid";  
            //Email is a column in the DB
            $stmt = $DB->prepare("INSERT INTO naslovi (Email) VALUES (?)");
            $stmt->bind_param("s", $cleaner_email);
            $stmt->execute();
            $stmt->close();
        } else {
            // email is invalid and should be rejected
            echo "Invalid email, try again";
        } 
    } else {
    echo "Please enter an email";
    }

    function test_input($data) {
      $data = trim($data);
      $data = stripslashes($data);
      $data = htmlspecialchars($data);
      return $data;
    }

    $DB->close();   
?>

Thank you for the help.

DrDoom
  • 297
  • 2
  • 10
  • What do you mean by `"this does not work"`? Does the form data not get placed in your database? – Ryan Wilson Jan 10 '20 at 15:12
  • Yes, thats what I mean. If you look at the 1st example, the data gets saved into the DB. In the 2cnd example it does not get saved into the DB. – DrDoom Jan 10 '20 at 15:13
  • code looks ok. check your anti-xss.php most likely the problem is somewhere there – qiAlex Jan 10 '20 at 15:14
  • but the php works for a normal submit (it is saving into the DB). I'll also upload the php... – DrDoom Jan 10 '20 at 15:14
  • What does the server log reports to the requests? – nologin Jan 10 '20 at 15:17
  • @DrDoom Your name attribute in the first example is: `email` for the form field which is being posted, in your second example you have `xhr2.send("Email="+encodeURIComponent(useremail));`, does it need to be lowercase? `xhr2.send("email="+encodeURIComponent(useremail));` – Ryan Wilson Jan 10 '20 at 15:17
  • @nologin I've never checked the server logs. don't know where to check it... I'm using XAMPP. – DrDoom Jan 10 '20 at 15:18
  • @RyanWilson Email is the filed/column inside the DB, and I think it needs to be upper case – DrDoom Jan 10 '20 at 15:19
  • @DrDoom It looks like that may be the problem, in your `.php` -> `if(isset($_POST['email']) && !empty($_POST['email'])){` it's looking for lowercase – Ryan Wilson Jan 10 '20 at 15:20
  • thanks. I'll change it, give it a try and report back. – DrDoom Jan 10 '20 at 15:21
  • @DrDoom by default it should be located at \xampp\apache\logs\error.log – nologin Jan 10 '20 at 15:21
  • @RyanWilson Changed it, still the same :( – DrDoom Jan 10 '20 at 15:25
  • @nologin all right, thanks. I'll check it now. – DrDoom Jan 10 '20 at 15:25
  • @nologin It saies: `Undefined index: email in C:\\xampp\\htdocs\\Site\\anti-xss.php on line 11, referer: http://localhost/Site/justAform3.html` – DrDoom Jan 10 '20 at 15:27
  • Changed `$clean_email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);` to `$clean_email = filter_var($_POST['Email'], FILTER_SANITIZE_EMAIL);` and now it works! thanks for the help. nologin, make an anwser, and i'll accept it =) – DrDoom Jan 10 '20 at 15:29
  • now check why email is undefined...: I guess you evaluate your parameter with $_POST['email']? see: https://stackoverflow.com/questions/33112630/i-am-getting-an-undefined-index-error – nologin Jan 10 '20 at 15:31
  • 1
    @DrDoom thx. no need :) Best – nologin Jan 10 '20 at 15:35

1 Answers1

2

I think it seems to be a variable Issue . You have misspelled

$clean_email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); 

to

$clean_email = filter_var($_POST['Email'], FILTER_SANITIZE_EMAIL);
Amit Sharma
  • 1,712
  • 2
  • 10
  • 18