The code posts two variables to a MySQL table. The code seems to work perfectly - the only thing that doesn't work is the echo statements. What would cause this?
I'm testing the file locally using MAMP, and the PHP version is up to date. I can't think of anything else that might be causing the problem. The SQL "insert" statements are working perfectly, and every other aspect of the code seems to go off without a hitch.
HTML
<body>
<div>
First Name: <input type="text" id="fname" name="fname" />
<button id="submitMe" onclick="postData()">Click Here</button>
</div>
</body>
JS
function postData(){
//HTML variable
var fname = document.getElementById("fname").value;
//Javascript Variable
var sname = "Second Name";
var http = new XMLHttpRequest();
var url = "index.php";
var params = "fname="+fname+"&sname="+sname;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200){
//alert(http.responseText);
alert("Request recieved");
}
}
http.send(params);
}
PHP
<?php
if(!empty($_POST)){
$fname = $_POST['fname'];
$sname = $_POST['sname'];
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "tutorials";
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("Connection failed".$conn->connect_error);
}
$sql = "insert into tutorials_tbl(firstname, lastname) values('".$fname."', '".$sname."')";
if($conn->query($sql) === TRUE){
echo "New Record created successfully";
}else{
echo "Error: ".$sql."<br/>".$conn->error;
}
$conn->close();
}
?>