Hello, I have an issue with my ajax script. Basically I want to be able to stop a php script from executing when I click on the Cancel button of the Confirm Dialog box. Here are the code snippets for my application:

policy.html:

....
$(document).ready(function(){
$('#process').click(print_check);
});

function print_check(){ 
var policy = $('#policy').val();


if(policy == ""){
alert("Enter Policy Number");
}else{

//Ajax function

 jQuery.ajax({
   type: "POST",
   url: "loyalty.php",
   data: 'policy='+ policy,
   cache: false,
   success: function(response){
if(response == 1){
     var r=confirm('Document has already been printed, reprint?')
            if (r==true)
            {

                $("form").submit();
                return true;

            } else {
                // Insert something here???
                return false;
            }


    }// end Ajax function
    ....
    <form method = "post" action = "printloyalty.php">
    <input type="text" name="policy" id="policy" size="30" />
    <input type="button" name="process" id="process" value="Print Card" class="bigbutton" />
    ....

And loyalty.php:

....
$policy = mysql_real_escape_string($_POST['policy']);


     mysql_query( "SET AUTOCOMMIT = 0" );
     mysql_query( "START TRANSACTION" );

     //Select Query
     $sql = "SELECT policyNumber FROM policydetails WHERE policyNumber = '".$policy."' AND policyNumber LIKE 'CB%' AND     LCardPrinted = 'Y' ";

    $result = mysql_query($sql) or die($sql."<br/><br/>".mysql_error());

    $num = mysql_num_rows($result);

    //Insert Query
    mysql_query("INSERT INTO tblloyaltycardaudit (policyNumber, userID)  

    VALUES( '$policy', {$_SESSION['loggedUserID']} )");

    $num1 = mysql_affected_rows();


    if($num == 1 && $num1 == 1){

    mysql_query("COMMIT");  

    echo $num;

    }

    else{
        mysql_query("ROLLBACK");
    }
    .....

In the above code I am inserting a record into one table and selecting from another at the same time using Transactions. The value of echo $num will be returned to the policy.html ajax function for the response. So when I click on the Print Card button, a confirm box appears with two buttons, OK and Cancel.
The problem is that when I click the Cancel button, it still inserts records into the table but I want that to only happen when I click the Ok button. Any help or alternatives would be greatly appreciated.

I'm not sure if you're cutting it out of your code or not, but the end of your jQuery seems to be missing some curly braces.

It should be this.

                    return false;
                } //End if (r==true)

           } //End if(response == 1)

       }//End success: function(response)

    });// end Ajax function

});//End $(document)

However, by the looks of your code, it should theoretically working. What browser do you use to test your code? Have you tried step by step debugging of your jQuery code?

Maybe use Google Chrome, press F12, and use the debugger there. Insert "debugger;" into your code where you want the debugger to pause and press F11 to go through it step by step and see what happens and where the code gets executed to submit to the database.

Like this

if(response == 1){
     var r=confirm('Document has already been printed, reprint?')

     debugger; //Code will pause when you press F12 in Chrome. F11 to continue.
            if (r==true)
            {
                $("form").submit();
                return true;
            } else {
                // Insert something here???
                return false;
            }

I hope I at least helped a little. However, don't forget to remove "debugger;" from your code once you're done.

Well I did the debugging and it didn't help much. My conclusion is that there needs to be some code put into the if else statement to cancel the call to the php url of the ajax url parameter. Don't know if it's possible though. Again this is just my opinion.

After a second look at your code, I think I see your problem.

Your SELECT and INSERT statement are in the same file. You send an AJAX request to the entire loyalty.php script, thus making the ENTIRE script execute.

This piece of code that you have here..

jQuery.ajax({
   type: "POST",
   url: "loyalty.php",
   data: 'policy='+ policy,
   cache: false,

Pretty much sends a request with the "policy" as the data. Then your loyalty.php script takes over and runs on the server on its own with jQuery having no impact whatsoever on what the PHP script does.

THEN you get a reply to your AJAX AFTER your entire PHP script finishes executing right here.

success: function(response){

So pressing CANCEL does nothing because your PHP script already finished executing and inserting records into the database.

So this code that you have here

if (r==true)
{
    $("form").submit();
    return true;
} else {
    // Insert something here???
    return false;
}

Does NOTHING to PHP. This code stricly returns true or false to the jQuery script. If you click OK, it will print your form and if you click CANCEL, it will not print it. But the records have already been inserted into the database.

I hope I'm understanding your code correctly and I hope you're understanding what I'm trying to say.

You can do the following.

Split your PHP script in two scripts. One to select records in a file called something like "check_loyalty.php" and one called "insert_loyalty.php" and put the respective code in each file.

Then have your first AJAX request check the loyalty against the "check_loyalty.php" script..and on success, submit the form and call a second AJAX request to the "insert_loyalty.php" to insert the record...like so.

jQuery.ajax({
   type: "POST",
   url: "check_loyalty.php",
   data: 'policy='+ policy,
   cache: false,
   success: function(response){
if(response == 1){
     var r=confirm('Document has already been printed, reprint?')
            if (r==true)
            {

                jQuery.ajax({
                    type: "POST",
                    url: "insert_loyalty.php",
                    data: 'policy='+ policy,
                    cache: false,
                    success: function(response){
                        $("form").submit();
                    }
                });
                return true;
            } else {
                // Insert something here???
                return false;
                } //End if (r==true)
           } //End if(response == 1)
       }//End success: function(response)
    });// end Ajax function

That way, if the user picks OK, the record will be inserted to the database and ONLY on success of the record being inserted will the form be printed.

Hope I answered your question.

Hahaha. U are awesome. I can't believe I couldn't see something so obvious. I wish you could see me laughing at myself. Thanks a lot man.

Haha. Glad I was able to solve your problem.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.