Ratan Kumar
Ratan Kumar

Reputation: 1650

preventing the form submission with javascript and php

I am working on a project , the situation is , the client has to enter the details , and after he enters the details , with java script ( confirm dialogue ) , i m showing all the important details for verification , then when he press ok, the form get submitted.

this is what i have made , but seems it is not working... need help ...

( after pressing cancel .. the dialog box keeps on coming .. and worst part is finally the form get submitted even if i have selected cancel )

( i have removed other details ...)

   <script type="text/javascript">
function validateMyForm()
{
    var X=confirm("ARE DETAILS CORRECT ??");
  if(!X)
  { 
    alert("validation failed false");
    returnToPreviousPage();
    return false;
  }
else
 {alert("validations passed");
  return true;}
}
</script>





<form name="frm" action=<?php print "new_update_attendence.php"; ?> method="POST"    
id="content" onsubmit="return validateMyForm();">

Upvotes: 2

Views: 240

Answers (3)

Mihai Iorga
Mihai Iorga

Reputation: 39724

capitalization matters ALOT!

var x=confirm("ARE DETAILS CORRECT ??");
if(!X) // change to if(!x)

you could do, for second part of your question:

<script type="text/javascript">
    function validateMyForm()
    {
        var X=confirm("ARE DETAILS CORRECT ??");
        if(!X)
        { 
            setTimeout((function(){ window.location.reload(); }), 500);
            return false;
        }
        else
        {
            return true;
        }
    }
</script>

Upvotes: 4

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76408

I gather you've used jQuery in the past. In jQuery return false would prevent the form from being submitted all together. That's because jQuery catches that return value (false) and translates it into eventObject.preventDefault(); eventObject.stopPropagation(); whereas return false, without jQuery only does the first (preventing the default action of that event). The event still bubbles/propagates.

change your HTML to onsubmit="return validateMyForm(event);"> to get access to the event object. Then, in JavaScript:

function validateMyForm(e)//e should hold the event
{
    e = e || window.event;//except for older IE versions(?), which we correct here
    //do whatever, if the form shouldn't be submitted:
    if (!confirm("ARE DETAILS CORRECT ??"))
    {
        if (e.preventDefault)
        {//chrome, FF, opera, ...
            e.preventDefault();
            e.stopPropagation();//<-- important line here
            return false;
        }//cruddy IE clients
        e.returnValue = false;
        e.cancelBubble = true;//<-- stop event in its tracks
        return false;
    }
}

That should do it.

Upvotes: 1

mgraph
mgraph

Reputation: 15338

X must be in lowerCase :

 if(!x)
  { ...

Upvotes: 3

Related Questions