I'm trying to figure out why this function isn't being called after the form is submitted. The "checkForm()" JS function works fine when the form is submitted, but I can't seem to get the checkDates() function working. I tried moving it above the PHP code and no alert message showed up. Any help is greatly appreciated, thank you!
Here's the pseudo code version of my file:
<?php
if(isset($_POST['next'])){
// Some PHP code
echo "<script> checkDates(); </script>";
}
?>
<form name="form1" id="form1" method="post" action="<?php print $thispage;?>" onsubmit="return checkForm()">
// Some HTML code
</form>
<script>
var isDateTimeValid = true;
function checkDates() {
alert("Hello");
isDateTimeValid = false;
}
function checkForm () {
if (isDateTimeValid == true) {
return true;
}
else {
return false;
}
}
</script>
try this it will work.
here your php code must be last in your file then it will work. otherwise not.
<form name="form1" id="form1" method="post" action="#" onsubmit="return checkForm()">
// Some HTML code
<input type="hidden" name="next" value="sd">
<input type="submit">
</form>
<script>
var isDateTimeValid = true;
function checkDates() {
alert("Hello");
isDateTimeValid = false;
}
console.log(isDateTimeValid);
function checkForm () {
if (isDateTimeValid == true) {
return true;
}
else {
return false;
}
}
</script>
<?php
if(isset($_POST['next'])){
echo "<script> checkDates(); </script>";
}
?>
I think you should first do this in your javascript function
<form method="post" action="" id="form">
<!-- some html code -->
</form>
<script>
// your all code
$("#form").submit(function(e) {
e.preventDefault();
if (isDateTimeValid == true) {
$.post(
// post logic with proper url
);
}
else {
// return some error message
}
});
</script>
try putting the javascript at the top. since you are calling the function which might have not been defined yet in the DOM
the problem was your variable and function scoping all the identifiers must be declared. If you run your code with "browser console output" opened, you will see an "Uncaught ReferenceError: checkDates is not defined" after your form submit. If you put the php code after the javascript function deceleration it will work.
<form name="form1" id="form1" method="post" action="#" onsubmit="return checkForm()">
// Some HTML code
<input type="submit" name="next">
</form>
<script>
var isDateTimeValid = true;
function checkDates() {
alert("Hello");
isDateTimeValid = false;
}
console.log(isDateTimeValid);
function checkForm () {
console.log(isDateTimeValid);
if (isDateTimeValid == true) {
return true;
}
else {
return false;
}
}
</script>
<?php
if(isset($_POST['next'])){
// Some PHP code
echo "<script> checkDates(); </script>";
}
?>
see the browser console output.