2012-03-12 9 views
57

Continuo a ricevere l'avviso di errore. Non c'è niente di sbagliato nella parte MYSQL, la query viene eseguita e posso vedere gli indirizzi email nel db.Come posso restituire un buon successo/messaggio di errore per JQuery .ajax() usando PHP?

Il lato client:

<script type="text/javascript"> 
    $(function() { 
    $("form#subsribe_form").submit(function() { 
     var email = $("#email").val(); 

     $.ajax({ 
     url: "subscribe.php", 
     type: "POST", 
     data: {email: email}, 
     dataType: "json", 
     success: function() { 
      alert("Thank you for subscribing!"); 
     }, 
     error: function() { 
      alert("There was an error. Try again please!"); 
     } 
     }); 
     return false; 
    }); 
    }); 
</script> 

Il lato server:

<?php 
$user="username"; 
$password="password"; 
$database="database"; 

mysql_connect(localhost,$user,$password); 
mysql_select_db($database) or die("Unable to select database"); 

$senderEmail = isset($_POST['email']) ? preg_replace("/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['email']) : ""; 

if($senderEmail != "") 
    $query = "INSERT INTO participants VALUES (CURDATE(),'".$senderEmail."')"; 
mysql_query($query); 
mysql_close(); 

$response_array['status'] = 'success';  

echo json_encode($response_array); 
?> 
+6

Considerare l'utilizzo di pdo, le funzioni mysql_ sono obsolete –

risposta

103

È necessario fornire il tipo di contenuto a destra se si sta utilizzando JSON dataType. Prima di echeggiare il json, inserisci l'intestazione corretta.

<?php  
    header('Content-type: application/json'); 
    echo json_encode($response_array); 
?> 

Ulteriori correzione, si dovrebbe verificare se la query successo o meno.

if(mysql_query($query)){ 
    $response_array['status'] = 'success'; 
}else { 
    $response_array['status'] = 'error'; 
} 

Sul lato client:

success: function(data) { 
    if(data.status == 'success'){ 
     alert("Thank you for subscribing!"); 
    }else if(data.status == 'error'){ 
     alert("Error on query!"); 
    } 
}, 

Speranza che aiuta.

+1

Oh, e occorre distinguere tra * errore lato server * e * errore di trasmissione *. Metto il controllo sulla parte 'successo' dell'AJAX per controllare il valore inviato dal server (quindi non è un errore di trasmissione). –

19

Qualcuno consiglia di utilizzare codici di stato HTTP, ma piuttosto disprezzano quella pratica. per esempio. Se stai facendo un motore di ricerca e le parole chiave fornite non hanno risultati, il suggerimento sarebbe quello di restituire un errore 404.

Tuttavia, ritengo che sia sbagliato. I codici di stato HTTP si applicano al browser attuale < -> connessione server. Tutto ciò che riguarda la connessione è andato perfettamente. Il browser ha fatto una richiesta, il server ha richiamato lo script del gestore. Lo script ha restituito "nessuna riga". Nulla di ciò significa "404 pagina non trovata" - è stata trovata la pagina WAS.

Invece, preferisco il divorzio del livello HTTP dallo stato delle operazioni sul lato server. Invece di restituire semplicemente del testo in una stringa json, restituisco sempre una struttura dati JSON che incapsula lo stato della richiesta e richiede i risultati.

ad es. in PHP avresti

$results = array(
    'error' => false, 
    'error_msg' => 'Everything A-OK', 
    'data' => array(....results of request here ...) 
); 
echo json_encode($results); 

Poi nel codice lato client che avresti avuto

if (!data.error) { 
    ... got data, do something with it ... 
} else { 
    ... invoke error handler ... 
} 
28

Proprio per questo, è possibile utilizzarlo per il debug.Mi ha aiutato molto, e lo fa ancora

error:function(x,e) { 
    if (x.status==0) { 
     alert('You are offline!!\n Please Check Your Network.'); 
    } else if(x.status==404) { 
     alert('Requested URL not found.'); 
    } else if(x.status==500) { 
     alert('Internel Server Error.'); 
    } else if(e=='parsererror') { 
     alert('Error.\nParsing JSON Request failed.'); 
    } else if(e=='timeout'){ 
     alert('Request Time out.'); 
    } else { 
     alert('Unknow Error.\n'+x.responseText); 
    } 
} 
+0

Ottimo! Ho appena scoperto che il mio server non supporta json_encode – Pieter

+0

@Pieter: Quindi implementa il tuo js_encode :) Prova questo: http://snippets.dzone.com/posts/show/7487 –

+0

Capito, grazie Mohammed. – Pieter

0

aggiungendo alla risposta superiore: qui è un codice di esempio da PHP e jQuery:

$("#button").click(function() { 
$.ajax({ 
      type: "POST", 
      url: "handler.php", 
      data: dataString, 

       success: function(data) { 

        if(data.status == "success"){ 

       /* alert("Thank you for subscribing!");*/ 

        $(".title").html(""); 
        $(".message").html(data.message) 
        .hide().fadeIn(1000, function() { 
         $(".message").append(""); 
         }).delay(1000).fadeOut("fast"); 

       /* setTimeout(function() { 
         window.location.href = "myhome.php"; 
        }, 2500);*/ 


        } 
        else if(data.status == "error"){ 
         alert("Error on query!"); 
        } 




        } 


     }); 

     return false; 
    } 
}); 

PHP - inviare messaggi personalizzati/Stato:

$response_array['status'] = 'success'; /* match error string in jquery if/else */ 
    $response_array['message'] = 'RFQ Sent!'; /* add custom message */ 
    header('Content-type: application/json'); 
    echo json_encode($response_array); 
1

al fine di costruire un webservice AJAX, avete bisogno di due file:

  • Un JavaScript chiamando che invia i dati come POST (potrebbe essere come GET) utilizzando jQuery AJAX
  • Un PHP webservice che restituisce un oggetto JSON (questo è conveniente per tornare array o grandi quantità di dati)

Così , prima si chiama il vostro webservice utilizzando questa sintassi JQuery, nel file JavaScript:

$.ajax({ 
    url : 'mywebservice.php', 
    type : 'POST', 
    data : 'records_to_export=' + selected_ids, // On fait passer nos variables, exactement comme en GET, au script more_com.php 
    dataType : 'json', 
    success: function (data) { 
      alert("The file is "+data.fichierZIP); 
    }, 
    error: function(data) { 
      //console.log(data); 
      var responseText=JSON.parse(data.responseText); 
      alert("Error(s) while building the ZIP file:\n"+responseText.messages); 
    } 
}); 

il file PHP (mywebservice.php, come scritto nella chiamata AJAX) dovrebbe includere qualcosa di simile nella sua fine, per restituire un corretto successo o stato di errore:

<?php 
    //... 
    //I am processing the data that the calling Javascript just ordered (it is in the $_POST). In this example (details not shown), I built a ZIP file and have its filename in variable "$filename" 
    //$errors is a string that may contain an error message while preparing the ZIP file 
    //In the end, I check if there has been an error, and if so, I return an error object 
    //... 

    if ($errors==''){ 
     //if there is no error, the header is normal, and you return your JSON object to the calling JavaScript 
     header('Content-Type: application/json; charset=UTF-8'); 
     $result=array(); 
     $result['ZIPFILENAME'] = basename($filename); 
     print json_encode($result); 
    } else { 
     //if there is an error, you should return a special header, followed by another JSON object 
     header('HTTP/1.1 500 Internal Server Booboo'); 
     header('Content-Type: application/json; charset=UTF-8'); 
     $result=array(); 
     $result['messages'] = $errors; 
     //feel free to add other information like $result['errorcode'] 
     die(json_encode($result)); 
    } 
?> 
Problemi correlati