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
1 Answer 1
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.
-
\$\begingroup\$ Thanks, but more looking for something like promise.done() and promise.then(). Try/Catch seems old, no? \$\endgroup\$bart– bart2018年11月03日 23:00:42 +00:00Commented Nov 3, 2018 at 23:00