Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

411
Visualizações
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>
   ';
}
about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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";
}
about 4 years ago · Santiago Trujillo Relatório

0

You could use json_encode() php function to return data from php.

This will be a better approach :

PHP :

if (!isset($_POST['name'] || empty($_POST['name']) {
    die(json_encode(array('return' => false, 'error' => "Name was not set or is empty")));
} elseif ($_POST['name'] == "John") {
    die(json_encode(array('return' => true)));
} else {
    die(json_encode(array('return' => false, 'error' => "Name is different than John.")));
}

At this point, you will be allowed to check the returned values from JS and decide if you need to display the success alert or send an error message to the console (or do what ever you want...).

JS :

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

$.ajax({
   type: "POST",
   url: "send.php",
   dataType: "JSON", // set the type of returned data to json
   data: {name: called}, // use more readable syntaxe
   success: function(data) {
      if (data.return) { // access the json data object 
         alert("Congrats ! Your name is John !");
      } else {
         console.log("Sorry, something went wrong : " + data.error);  
      }  
   }               
});

So, json_encode() allows to return easy accessible object from JS and will also allows you to set and display error messages easily in case the return is false.

Hope it helps !

about 4 years ago · Santiago Trujillo Relatório

0

PHP does not know if an alert has been shown, because in javascript the alert() function has no return value and no events which you could use to send an ajax request a click confirmation to the server.

One solution is to use a confirm() command inside the success event of your $.ajax(), which sends anothe ajax request if the user clicked "ok" or "cancel".

Something like this

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

$.ajax({
   type: "POST",
   url: "send.php",
   data: "name=" + called,
   success: function(data) {

        if (data == "show") {

            var clicked = confirm("Correct name");

            if (clicked == true || clicked == false) {
                $.ajax({
                    url: "send.php?clicked=1",
                });
            }  
        }
        else {
             // Whatever to do than...
        } 
    }
});
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda