views:

1417

answers:

1

I have a form which has a input textbox and submit button.

On submission of the form the textbox value should get pass to an php script and check the values whether it exists in the Mysql Database. If it exists then we need to show an alert box stating that "Entered Value is already exists, Try something new". If the value not exists the form can be submitted to the php script which is in the form action.

I tried with the jquery and the code is below:

 $(document).ready(function() {

        $("#form_add").submit(function () {
        var pval = $("#name").val(); 
        var datastring = 'pname'+pval;
        $.post("unique_valid.php", {pname:pval }, function (data){
          alert('duplicate');
         });
         return false;
        }); 
});


Problem with this code is It shows alert box on every case but its not allowing to submit the form if the values is not exists in the database.

Php code :

$pname = $_POST['pname'];
if( $pname == $row['name']){
     echo "success";
    }else{
     echo "failure";
    }

Suggest the better solution for this problem.

+2  A: 

That's because you're alerting 'duplicate' no matter what the PHP output is. Try checking the value of data before alerting, like this:

$(document).ready(function() {

        $("#form_add").submit(function () {
        var pval = $("#name").val(); 
        var datastring = 'pname'+pval;
        $.post("unique_valid.php", {pname:pval }, 
                   function (data){
                        if(data == 'failure'){
                            alert('duplicate');
                        }else{
                            alert('not a duplicate'); 
                        }
                });
                return false;
        }); 
});

And I'm assuming your PHP code will actually be saving the record if it's not a duplicate (your code doesn't indicate as much, though)?

inkedmn
Thanks,iam getting alert message but the form not submitting when alert('not a duplicate '). Once the form submit i save the records in the database using php scripts.
boss