I have a text field and a button on the HTML page. There is also a para tag which will display the error on validation.
If the field is empty it will be changed to
Name must be filled out
and it is changing to that on validation.
Now when I input a string and press the submit button....the value should be passed to PHP page and check the condition and print the message accordingly on the HTML page...but when I click submit the message is printed out on the index.php page itself.
How should I use the AJAX code so it prints the message on the para tag with id error?
Please Help. Thanks in advance.
HTML CODE
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<script type="text/javascript" src="java123.js"></script>
</head>
<body>
<form action="index.php" method="post" onsubmit="return validateForm()">
<input type="text" name="name" id="name">
<input type="submit">
</form>
<p id="error"></p>
</body>
</html>
PHP CODE
<?php
$name = $_POST['name'];
if($name == "thistext"){
$arr = array("sth"=>"hello");
echo json_encode($arr);
}else{
$arr = array("sth"=>"User does not exist");
echo json_encode($arr);
}
?>
JAVASCRIPT CODE
var invalid = 0;
function validateForm() {
/* WHERE SHOULD I PUT THIS CODE
$.ajax({
url: "index.php",
type: "POST",
dataType: "json",
success: function(response) {
$("#error").html(response.sth);
}
});
*/
invalid = 0;
name = document.getElementById("name").value;
if(name == ""){
document.getElementById('error').innerHTML = "Name must be filled out";
invalid = 1;
}else{
document.getElementById('error').innerHTML = "";
}
if(invalid != 0){
return false;
}else{
return true;
}
}