-1

I have a JavaScript confirm box and i have some MySQL insert query code to be executed at some condition. This is how my code look like:

<?php
$id = $_POST['id'];
$name= $_POST['name'];
$query = mysql_query("select * from table where id='$id'");
$count    =   mysql_num_rows($query );

if($count!=0)
{
?>
   <script type="text/javascript">  
        if (confirm("This seems to be Duplicate. Do you want to continue ?") == true)
        {
            //Execute/Insert into table as how it is given below
        }
        else
        {
            //Dont execute/insert into table but close the window
        }
     </script>
<?php
}
else
{
    $queryinsert = mysql_query("INSERT INTO table(id,name) VALUES('$id','$name')");
}
?>
Koopakiller
  • 2,838
  • 3
  • 32
  • 47
Nathan
  • 125
  • 2
  • 13
  • 1
    I think you need to do some reasearch on AJAX and probably JQuery – RiggsFolly Aug 08 '15 at 12:15
  • Can you share more of your code? How do you reach this snippet? You would need to call the php script after confirmation with an ajax call, or you could do a location.href="myscript.php?ignoreDuplicate=1"; and then use it like `if($count != 0 && ( !isset($_GET['ignoreDuplicate']) || $_GET['ignoreDuplicate'] == 0)){ ... }` This of course should do it if you don't use any framework. – Patrick Hübl-Neschkudla Aug 08 '15 at 12:18

2 Answers2

2

You can't execute MySQL or PHP command inside javascript, what you can do instead is to make a PHP function that you can call by Ajax. The best way is by using jQuery or by redirecting the page with your PHP function in URL.

<script type="text/javascript">  
    if (confirm("This seems to be Duplicate. Do you want to continue ?"))
    {
        $.ajax({
            url: 'your_path_to_php_function.php',
            type: 'POST', // Or any HTTP method you like
            data: {data: 'any_external_data'}
        })
        .done(function( data ) {
            // do_something()
        });
    }
    else
    {
        window.location = 'your_url?yourspecialtag=true'
    }
 </script>
Disha V.
  • 1,834
  • 1
  • 13
  • 21
Tareq El-Masri
  • 2,413
  • 15
  • 23
0

You're mixing serverside and clientside scrips. This won't work. You have to use AJAX, which are asynchronous server-client/client-server requests. I recommend jQuery, which is JavaScript which easily handles lot of things, including AJAX.

Run this if user confirms action

$.post("phpscript.php", {action: true})

Php file:

if ($_POST['action'] === TRUE) {
    <your code here>
}
david8
  • 444
  • 9
  • 23