jQuery AJAX submit form 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 &amp;&amp; response.status=='success')
            {
            message_return('success',response.message);
            unfreezeModal(node);
            node.modal('hide');
            }
        else if(response!=null &amp;&amp; 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
You should first check if the response is null. If not, then check for a success or error response.
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();
}

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.