I have this code that sets my ajax request :
function sendAjaxRequest() {
ajax.open("post", "form.php", false);
ajax.setRequestHeader("Content-Type", "application/json");
ajax.onreadystatechange = gotResponseFromServer();
ajax.send(jsonObject);
}
And this one php that executes the request :
<?php
require_once "database_connection.php";
con = mysqli_connect($host, $user, $password,$db) OR die("Failed to connect to MySQL: " . mysqli_connect_error());
$data = file_get_contents("php://input");
$decodedData = json_decode($data);
//$verifyCode = md5(rand()."");
$name = $decodedData->{'name'};
$surname = $decodedData->{'surname'};
$email = $decodedData->{'email'};
$phone = $decodedData->{'phone'};
$birthDate = $decodedData->{'birthDate'};
$studies = $decodedData->{'studies'};
$work = $decodedData->{'work'};
$married = $decodedData->{'married'};
$skills = $decodedData->{'skills'};
$hobby = $decodedData->{'hobby'};
$city = $decodedData->{'city'};
$gender = $decodedData->{'gender'};
$baptized = $decodedData->{'baptized'};
$suggestions = $decodedData->{'suggestions'};
$sql = "INSERT INTO Voluntari (_name, _surname, _email, _phone, _birthDate, ".
"_studies, _work, _married, _skills, _hobby, _city, _gender, _baptized, _suggestions) ".
"VALUES ('$name', '$surname', '$email', '$phone', '$birthDate', '$studies', '$work', '$married',".
"'$skills', '$hobby', '$city', '$gender', '$baptized', '$suggestions' );";
if(!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
} else {
//sendConfirmationMail();
echo "added";
}
mysqli_close($con);
?>
The problem is that I can't make the ajax request asynchronously and I don't know why. If I do it synchronously, the form data gets added to the database but if I do in in an asynchronous way, the ajax.status
is always 0 and ajax.readyState
is 1.
To change the request from asynchronous to synchronous I put false
in here :
ajax.open("post", "form.php", false);
^^^^^
What am I doing wrong? And how can I keep my request asynchronous and make my script work?