Jquery and ajax submit if condition


#1

Hello, I would like to submit a for if credit is greater thand tcoin and display confirmation aler, otherwise if credit < tcoin not submit the form and show different alert. this is my code, it shows same alert on both cases

<script type="text/javascript">
    $(document).ready(function(){
         $("button#tombins1").click(function(){

    var amountLoaded = "<?php echo $partnum ?>";
    var credit = "<?php echo $balance0 ?>";
    var tcoin= "<?php echo $tcoin ?>";
    if(credit<tcoin)
    {
    alert("Please Fill All Fields");
    }
    else
    {
    // AJAX Code To Submit Form.
    $.ajax({
    type: "POST",
    url: "ajaxthat.php",
    data: 'triggerPHP',
    cache: false,
    success: function(result){
    alert("you are in");
    }
    });
    }
    return false;




         });
        });

    </script>

#2

Hi there @elmehdielfahmi183 and welcome to the forums.
I'm not sure about the problem you are facing right now but I know about other problems you will encounter through your current approach.
First of all I would suggest not to add an event listener on the click of the submit button... this is bad practice as forms can be submitted not only by clicking submit but also by hitting the enter key. It is for this reason that the event should be set to the 'form' node instead of the submit input node and with the event name 'submit' instead of 'click'. That way you're always ensuring you're capturing the form submit event.
The second thing is that you should not rely on JavaScript entirely for validation. The reason is that someone can just disable JavaScript and submit your form skipping your validation. Ideally that validation happens server side so that there is no way around it... and then you could mimic the same validation in JavaScript client side to offload the server and prevent sending invalid data.

Hope that helps


#3

<form method="post" name="myForm" id="myForm">
  
  <input type="name" value="Amit Arya">
    <input type="email" value="amitpahday182@gmail.com">

  <button type="submit">Submit</button>
  
</form>

<script type="text/javascript">
    $(document).ready(function(){
         $("#myForm").submit(function(e){
		e.preventDefault();
    var amountLoaded = 50000;
    var credit = 1000;
    var tcoin= 3000;
    if(credit<tcoin)
    {
    alert("Please Fill All Fields");
    }
    else
    {
    // Make a ajax call
		alert('make a ajax call');
    }
    return false;
    });
    });
</script>

check : FIDDLE


#4

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.