Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- How do I return a proper success/error message for JQuery .ajax() using PHP?
- <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>
- <?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);
- ?>
- header('Content-type: application/json');
- echo json_encode($response_array);
- ?>
- data: {'email': email},
- if(mysql_query($query))
- $response_array['status'] = 'success';
- else
- $response_array['status'] = 'error';
- success: function(data) {
- if(data.status == 'success')
- alert("Thank you for subscribing!");
- else if(data.status == 'error')
- alert("Error on query!");
- },
- $results = array(
- 'error' => false,
- 'error_msg' => 'Everything A-OK',
- 'data' => array(....results of request here ...)
- );
- echo json_encode($results);
- if (!data.error) {
- ... got data, do something with it ...
- } else {
- ... invoke error handler ...
- }
- 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);
- }
- }
Add Comment
Please, Sign In to add comment