2012-04-11 19 views
6

Está bien que tienen un script php que termina como tan:Enviar respuesta php al Ajax

if ($success) 
{ 
    $result = array('success' => true); 
} 
else 
{ 
    $result = array('success' => false, 'message' => 'Something happened'); 
    header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500); 
} 
    echo json_encode($result); 

Y algunos jQuery que yo estaba pensando en tener Avisarme cuando la secuencia de comandos funciona.

jQuery(document).ready(function() { 

    $.ajax({ 
     url: './contactengine.php', 
     type: 'GET', 
     dataType: 'JSON', 
     success: function(response) { 
         alert("GOOD"); 
       }, 
       error: function() { 
         alert("BAD"); 
       } 
    }); 

}); 

fuente editado

+0

¿Su instrucción 'return 1' se llama dentro de una función? –

+2

¿Qué significa _ "Sí" _? – gdoron

+0

Deberías generar el 1 como JSON. –

Respuesta

5
 <?php 
     if ($success){ 
      $result = array("status" => "1"); 

      echo json_encode($result); 
      } 
      else{ 
       print "<meta http-equiv=\"refresh\" content=\"0;URL=/404.html\">"; 
      }  
     ?> 
     <script> 
     jQuery(document).ready(function() { 

      $.ajax({ 
          type: 'GET', 
          url: 'Thatscriptsomething.php', 
          cache: 'false', 
          dataType: 'json', 
          success: function(response) { 
           if(response.status == "1") { 
            alert("we having a working script"); 
           } else { 
            alert("Oops, script is a no go"); 
           } 
          } 
         }); 
     }); 
     </script> 
+0

Volviendo a trabajar en esto y me reenvío a una página que dice: ' {"success": true} ' va a una página domain.com/script.php cuando no debería ir allí. – lostAstronaut

+0

Intenté ejecutar el script y no funciona. Si hago una alerta (respuesta) obtuve el {"estado": 1} ... Así que supongo que esa es la razón por la que no funciona. Además, si no elimino dataType: el script 'json' no hace nada. – doplumi

4

Ejemplo básico - que funciona para mí

PHP RESPUESTA

$value = array('msg' => 'true'); 
      echo json_encode($value); 

AJAX MÉTODO

$.ajax({ 
    type: 'post', 
    url: 'URL', 
    contentType: false, 
    processData: false, 
    dataType:'JSON', 
    data: formData, 
     success: function(value) { 
       if (value.msg == 'true') { 
         //your action 
       }else{ 
         //your action 
       } 
     } 
}); 
Cuestiones relacionadas