I have html form with input fields. Data from the form will be sent throght the ajax function in php and php returns the result in html. Although not all fields are filled php executes and returns the result. If all fields are filled not get a result from php.
Can anyone help me to solve the problem?
Thanks in advance
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<script type="text/javascript" src="ajax.js"></script>
</head>
<body>
<div id="inputform">
<form>
Name:<br>
<input type="text" id="firstname" required><br>
Surname:<br>
<input type="text" id="lastname" required ><br>
<input type="submit" value="submit" onclick='ajax()'>
<div id="ajaxDiv"></div>
</form>
</div>
javascript
function ajax() {
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
var answer = document.getElementById('ajaxDiv');
answer.innerHTML = ajaxRequest.responseText;
}
};
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
var queryString = "?firstname=" + firstname + "&lastname=" + lastname;
ajaxRequest.open("GET", "test.php" + queryString, true);
ajaxRequest.send(null);}
php
<?php
$firstname=$_GET['firstname'];
$lastname=$_GET['lastname'];
echo $firstname;
?>
You use ajax to send form data to server and you call method ajax()
on form submit. So, there is no need in <form>
tag, because when you click on button, you call ajax()
function and form is submitting automatically.
Remove <form>
and change:
<input type="submit" value="submit" onclick='ajax()'>
to
<input type="button" value="submit" onclick='ajax()'>