1

PHP is executed first before JS, but is there an easy way to output a confirmation dialog (like Javascript confirmation) if the data is not empty like in this conditional PHP statement:

<?php
if (!empty($data)) {

//data is not empty
//Ideally I want to show a confirmation dialog in this part to the user
//to confirm if the user wants to overwrite the existing data

//If the user confirms
//Overwrite the existing data here

} else {

//data is empty,proceed to other task
//don't show any dialog

}

I don't want to add another form to the user, just a simple confirmation dialog like the JS confirm. Or is there a PHP replacement function for this? Thanks.

0

3 Answers 3

3

I like to separate the data and the code, so I like to create a JS variable from PHP

// I always use json_encode when creating JS variables from PHP to avoid
// encoding issues with new lines and quotes.
var isDataEmpty = <?php echo json_encode(empty($data)); ?>;

if (!isDataEmpty) {
   if (confirm("Some message")) {
      overwriteExistingData();
   }
} else {
   // proceed
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can have your PHP code write JavaScript like the following:

<script type="JavaScript">
$(document).ready(function(){
    <?php
    if (!empty($data)) {
    ?>
    var answer = confirm("Are you sure you want to overwrite?");
    <?php
    } else {
    ?>
    // Data is empty
    <?php
    }
    ?>
});
</script>

1 Comment

You should keep the mixing of PHP and JS to a minimum, see my answer, JS and PHP interact only in one line.
0

see the code below

<?php
if (!empty($data)) {
    echo '<script language="javascript" type="text/javascript">window.confirm("data is not empty")</script>';

//data is not empty
//Ideally I want to show a confirmation dialog in this part to the user
//to confirm if the user wants to overwrite the existing data

//If the user confirms
//Overwrite the existing data here

} else {
    echo '<script language="javascript" type="text/javascript">window.confirm("data is empty here")</script>';

//data is empty,proceed to other task
//don't show any dialog

}

1 Comment

Using echo to generate HTML is very hard to read. You're unnecessarily coding the script tag in two places (and making the mistake of adding language="javascript" in two places

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.