0
\$\begingroup\$

This jQuery code submits a form using AJAX. The server response should return JSON.

addNewOutreach = function(node)
    {
    var form = node.find('form');
    var data = form.serialize();

    $.post('ajax.php',
    {action:'addNewOutreach',string:data},
    function(response) {
        if(response!=null && response.status=='success')
            {
            message_return('success',response.message);
            unfreezeModal(node);
            node.modal('hide');
            }
        else if(response!=null && response.status=='error')
            {
            message_return('error',response.message);
            unfreezeModal(node);
            }
        else 
            {
            message_return('error','Error saving outreach.');
            unfreezeModal(node);
            }
        },'json');
    }

message_return() is a function that displays feedback on the page.

unfreezeModal() is a function that locks the form (avoiding double submits) until the request is finished.

Where this code lacks:

  • What if the server does not respond with valid JSON?
  • What if the AJAX request keeps hanging?
  • The function(response) block can probably be isolated from this block so it can be used in other AJAX request
  • Can probably be written cleaner with Promises
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$
  1. You should first check if the response is null. If not, then check for a success or error response.

  2. You can use a try-catch block to check if it is valid JSON:

    Try{
        JSON.parse(response);
        catch(Exception){
        console.log("Not valid json");
        handle();
    }
    
  3. If what you are expecting from the server to be in a constant format you could use the callback code again and again in different functions.

\$\endgroup\$
1
  • \$\begingroup\$ Thanks, but more looking for something like promise.done() and promise.then(). Try/Catch seems old, no? \$\endgroup\$
    – bart
    Nov 3, 2018 at 23:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.