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
asked Oct 25, 2018 at 20:24
\$\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.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
answered Nov 3, 2018 at 0:21
\$\endgroup\$
1
  • \$\begingroup\$ Thanks, but more looking for something like promise.done() and promise.then(). Try/Catch seems old, no? \$\endgroup\$ Commented Nov 3, 2018 at 23:00

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.