0

I have a form submission page, call a function at the time of form submission.Include an ajax.Form submission occur or not according to the condition in ajax.Ajax msg have two values 1 and 0,one value at a time.My requirement is when msg==1 form not submit and msg==0 submit form.But now in both cases form is not submitting.

My code is given below.Anybody give any solution?

main page

<form action="addCustomer_basic.php" method="post"
name="adFrm" id="myform" >
<input name="name" type="text"   
 class="txtfld" id="name"    
 value=">" style="width:250px;"/>
<input name="email" type="text" 
class="txtfld" id="email" value=""  style="width:250px;"/>
<input name="submit" type="submit" value="Submit" />
</form>

 <script language="JavaScript">
 $(function() {

 $("#myform").submit(function(e) {
    var $form = $(this);
    var cust_name = $form.find('[name="name"]').val();
       e.preventDefault();// prevent submission
    var email = $form.find('[name="email"]').val();
    $.ajax({
      type: "POST",
      url: 'ajx_customer_mailid.php',
      data:'cust_name='+cust_name + '&email=' + email,
      success: function(msg) 
         { 
         alert(msg);
         if(msg==1) 
            {
            alert("Email Id already excist in database");
               return false;     
          }
          else 
           {
          self.submit();
          }
      }
   });


 });

 });
</script>

ajx_customer_mailid.php

<?php
 require_once("codelibrary/inc/variables.php");
 require_once("codelibrary/inc/functions.php");
 $cust_id=$_POST['cust_name'];
 $email=$_POST['email'];
 $se="select * from customer where name='$cust_id' and email='$email'";
 $se2=mysql_query($se);
 if($num>0)
  {
    echo $status=1;    
  }
 else
 {
   echo $status=0;  
 }
 ?>
shilna mk
  • 25
  • 3
  • Maybe add a input type submit inside the form will help :D4 – Marco Mura Nov 13 '14 at 08:28
  • In my code intput type is submit,ie ,,,please ook my code – shilna mk Nov 13 '14 at 08:34
  • Your code will cause the submit event to be repeatedly fired if the conditions are met, because you are calling submit again within the submit event itself. But the submission will not go through as you have prevented it from doing so by binding `e.preventDefault()` to all submit events of the form. – Terry Nov 13 '14 at 08:39
  • with out the self.submit() code,submit code is not working in both cases. – shilna mk Nov 13 '14 at 08:44
  • Have you tried seeing what the php returns? Maybe try $form.submit(); and not self.submit() – Marco Mura Nov 13 '14 at 09:00
  • **Danger**: You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). You are also **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that a modern API would make it easier to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Nov 13 '14 at 09:36
  • @shilnamk Have you tried the jsfiddle I posted below? It's working in jsfiddle, you just need to change the ajax url. – artm Nov 13 '14 at 10:40
  • @ artm with that code jsfiddle,form submitting in both cases – shilna mk Nov 13 '14 at 10:50
  • @artm need any changes in ajx_customer_mailid.php with that code? – shilna mk Nov 13 '14 at 11:01
  • @shilnamk You just return 1 or 0 in php, in that case you don't need `json.msg`, instead you can use `msg` – artm Nov 13 '14 at 11:04
  • @shilnamk You just need to modify `msg: 0` to `msg: 1` to stop submit, it's working. – artm Nov 13 '14 at 11:05
  • @artm Tired,but no change,always submit form,,,i give an alert() before echo() ie$("#myform").submit(function(event) { alert("msg"); echo(); these alert is not working, i think control dont go to form submision – shilna mk Nov 13 '14 at 11:20
  • @shilnamk Are you talking about the fiddle or your own code? Fiddle's working fine for me, if I use `msg: 1` at the top where `data` is set, it alerts and doesn't submit after 1 second. http://jsfiddle.net/x7r5jtmx/1/ – artm Nov 13 '14 at 11:39
  • @shilnamk The fiddle's working fine then? – artm Nov 13 '14 at 11:55
  • @artm these alert is not working $("#myform").submit(function(event) { alert("msg"); – shilna mk Nov 13 '14 at 12:00
  • @shilnamk Double check the element ids I've used in fiddle (which is a copy of your original question) and the code you have on your site. Fiddle works fine, if you've adopted it to your site and it doesn't work, it's probably because ids don't match, or misspelled, etc. – artm Nov 13 '14 at 12:02
  • @artmMy data code is var data = { json: JSON.stringify({ msg: 1 }), delay: 1 } is it correct? – shilna mk Nov 13 '14 at 12:07
  • @artm now control is entered into the submit function,but value of msg is null – shilna mk Nov 13 '14 at 12:20
  • @shilnamk `var data { json:...` is only valid for the jsfiddle for testing, you still need to use your ajax code as in `data:'cust_name='+cust_name + '&email=' + email,`. On `success` try `alert(msg)` to see if you're getting the correct value from the server. – artm Nov 13 '14 at 12:25
  • ok,,,i am leaving from office,then i will check tomorrow...i think you will help me tomorrow... – shilna mk Nov 13 '14 at 12:32
  • @shilnamk Please put a comment under my answer. – artm Nov 13 '14 at 12:40

2 Answers2

0

I've checeked your code, without ajax, and just set directly the msg to 1 or to 2. See my code, now you can simulate it:

    $("#myform").submit(function(e) {
        var $form = $(this);
        e.preventDefault();// prevent submission
        var msg = 2; 
        if (msg === 1) {
            alert("Email Id already excist in database");
            return false;
        } else {
            $form.submit(); //This causes Too much recursion
        }
    });

There are some errors in it.

So, self.submit(); is bad:

TypeError: self.submit is not a function
   self.submit();

You need to rewrite it to $form.submit();

But in that case, if the form needs to submit, you will get an error in your console:

too much recursion

This is because, if it success, then it fires the submit again. But, because in the previous case it was succes, it will be success again, what is fires the submit again, and so on.

UPDATE: Let's make it more clear what happens here. When you submit the form, after you call e.preventDefault() what prevents the form to submit. When ajax need to submit the form, it triggers the submit(), but you prevent it to submit, but ajax condition will true again, so you submit again, and prevent, and this is an inifinte loop, what causes the too much recursion.

NOTE:

if($num>0) Where the $num is come from? There are no $num anywhere in your php file. You also do not fetch your row of your sql query.

  • Use mysqli_* or PDO functions instead mysql_* since they are deprecated.

  • Avoid sql injection by escaping your variables.

So you need to use like this:

$se = "select * from customer where name='$cust_id' and email='$email'";
$se2 = mysql_query($se);
$num = mysql_num_rows($se2); //NEED THIS!
if ($num > 0) {
    echo $status = 1;
} else {
    echo $status = 0;
}

But i am suggest to use this:

$se = "SELECT COUNT(*) AS cnt FROM customer WHERE name='".mysql_real_escape_string($cust_id)."' and email='".mysql_real_escape($email)."'";
$se2 = mysql_query($se);
$row = mysql_fetch_assoc($se2); //NEED THIS!
if ($row["cnt"] > 0) {
    echo $status = 1;
} else {
    echo $status = 0;
}
vaso123
  • 12,347
  • 4
  • 34
  • 64
0

By the time your ajax call finishes, submit handler already finished so the submit continues, it's async you know, so the function makes the ajax call and continues executing. You can do something like this http://jsfiddle.net/x7r5jtmx/1/ What the code does is it makes the ajax call, then waits until the ajax success updates the value of a variable, when the value is updated, if the value is 1, no need to do anything, as we already stopped the form from submittin. If the value is 0, then trigger a click on the button to re-submit the form. You can't call submit inside the submit handler, but you can trigger click on the button. You obviously need to change the ajax call, just set msg inside your success.

var data = {
        json: JSON.stringify({
            msg: 0 //change to 1 to not submit the form
        }),
        delay: 1
}

var msg = null;

var echo = function() {    
    return $.ajax({
        type: "POST",
        url: "/echo/json/",
        data: data,
        cache: false,
        success: function(json){
            msg = json.msg;
        }
    });
};

$( "#myform" ).submit(function( event ) {
    echo();

    var inter = setInterval(function(){
        console.log("waiting: " + msg);
        if (msg != null){
            clearInterval(inter);
        }
        if (msg == 0){
            $( "#myform" ).off();  //unbind submit handler to avoid recursion
            $( "#btnn" ).trigger("click"); //submit form
        }
    }, 200);

   return false; //always return false, we'll submit inside the interval
});
artm
  • 8,554
  • 3
  • 26
  • 43