user8716936
user8716936

Reputation: 55

jQuery Post retrieve PHP echo on Error

I am trying to create a popup modal that will display text echoed from a php submission script. So far it works for a success and prints the echoed content but I also want to catch echoed messages when an exception occurs in the php script.

popnotify is a seperate js function that takes text input and displays the modal with the text as a paragraph.

createuser.php

try:
    ......
    echo 'Successfully created a new user';
}
catch (PDOException $ex){
    echo "Something went wrong when creating a new user";
    http_response_code(403);
    die();
}

.js

jQuery("#load_form").on("click","#create_submit",function(event){
event.preventDefault();
var to_submit = $("#s_form").serialize();
var formLink = $("#s_form").attr('action');
jQuery('#load_form').find('input, select, button').prop('disabled', true);

$.post(formLink,to_submit)
.done(function(data){
    popnotify_success(data);
})
.fail(function(data){ 
    popnotify_fail(data);
})
.always(function(){
    jQuery('#load_form').find('input, select, button').prop('disabled', false);  
});  });

Upvotes: 0

Views: 113

Answers (1)

Raul Sauco
Raul Sauco

Reputation: 2705

How about using a flag to determine if there were errors

Your PHP, createuser.php

try {
    // Some more code here that tries to create the user
    $response = [
        'error' => 0,
        'message' => 'Successfully created a new user',
    ];
    echo json_encode($response);
}
catch (PDOException $ex){
    $response = [
        'error' => 1,
        'message' => 'Something went wrong when creating a new user',
    ];
    echo json_encode($response);
    // HTTP Code 200 OK, there were not HTTP errors or server (500) errors
    // http_response_code(403);
    die();
}

Your JavaScript

jQuery("#load_form").on("click","#create_submit",function(event){
  event.preventDefault();
  var to_submit = $("#s_form").serialize();
  var formLink = $("#s_form").attr('action');
  jQuery('#load_form').find('input, select, button').prop('disabled', true);

  $.post(formLink,to_submit)
  .done(function(data){
    // Parse the result into an object
    var result = JSON.parse(data);

    // Get the error flag from the object
    if (result.error == 0) {

      // There was no error
      popnotify_success(result.message);

    } else {

      // There was an error
      popnotify_fail(result.message);

    }
  })
  .fail(function(data){ 
    // Handle http errors here
  })
  .always(function(){
    jQuery('#load_form').find('input, select, button').prop('disabled', false);  
  });  
});

You could also use a generic popnotify() function, instead of two, if all the function does is create a notification. Any other code dependent on error/success could go on the handler function.

Upvotes: 1

Related Questions