Search code examples
javascriptphpsweetalertsweetalert2

PHP onclick confirm to Sweet Alert 2 confirmation


I need your help here please.I have a button which is echoed by a PHP file to a HTML file. When the button is clicked it uses window confirm() method but I want to use a sweet alert 2 modal to be displayed with yes or no option in the HTML file.

Does anyone have any idea how I can make this work?

PHP echo:

$row['handler'] = "<a class=\"btn btn-detail btn-small\" href=\"user.php?act=cancel_order&order_id=".$row['order_id'].
"\" onclick=\"if (!confirm('".$GLOBALS['_LANG']['confirm_cancel'].
"')) return false;\">".$GLOBALS['_LANG']['cancel'].
"</a>";

Do I need to add the script to a external file and call it inside PHP or there is better way to do this ?


Solution

  • I have just modified your code.

    $row['handler'] = '<a class="btn btn-detail btn-small" href="javascript:;" onclick="confirmation(\''.$GLOBALS['_LANG']['confirm_cancel'].
            '\',\'user.php?act=cancel_order&order_id='.$row['order_id'].
            '\')">'.$GLOBALS['_LANG']['cancel'].
        '</a>';
    

    And your javascript function will looks like this

    function confirmation(text,text2)
      {
        swal({
          title: text,
          type: 'warning',
          showCancelButton: true,
          confirmButtonColor: '#3085d6',
          cancelButtonColor: '#d33',
          confirmButtonText: 'Yes, delete it!',
          cancelButtonText: 'No, cancel!',
          confirmButtonClass: 'btn btn-success',
          cancelButtonClass: 'btn btn-danger',
          buttonsStyling: false
        }).then(function () {
          location.href=text2;
        }, function (dismiss) {
            return false;
        })
      }
    

    Hope it will work :)