The Codesee The Codesee - 8 months ago 76
Ajax Question

Check if alert box was shown in PHP using AJAX

I am sending data to a PHP file using AJAX and depending on what data is sent, an

alert()
is either shown or not shown.

Inside the
success
function in AJAX, how do I detect if an alert box was shown?

var called = $("#called").val();

$.ajax({
type: "POST",
url: "send.php",
data: "name=" + called,,
success: function(data) {
if(alert box was shown) {
// something happens
}else{
// alert box wasn't shown, something else happens.
}
}
});


send.php
:

<?php
if($_POST['name'] == 'john') {
echo'
<script>
alert("Correct name");
</script>
';
}

Answer Source

It would be better to send back a result form the ajax request and show/don't show the alert in the success callback:

$.ajax({
   type: "POST",
   url: "send.php",
   data: "name=" + called,,
   success: function(data) {    
      if ( data == "show" ) {
         // something happens
         alert("Correct name");
      } else {
         // alert box wasn't shown, something else happens.  
      }  
   }               
});

And on your server:

if ( $_POST['name'] == 'john' ) {
   echo "show";
}