How about this - just use the inline on success message and donβt even bother to make it part of JSON. On error, include the entire message and use it directly. In addition, I will have a server returning something like:
{ "status": true }
or
{ "status": false, "msg": "The mail server is down." }
Then you can simply evaluate it as a logical one without comparing it to a string value.
$.ajax({ url: "ajax-share-email.php", type: "POST", dataType: "json", data: {}, success: function(data) { if (data.status) { msg.text('Your email has been sent successfully!').addClass("email-msg-success"); } else { msg.text(data.msg).addClass("email-msg-error"); } } });
If and only if you start to reuse your messages for several functions, then refactoring to the message dictionary and a link to it from there. Note that your messages object should probably be a global variable, or at least in the outer scope of all functions that use it.
var messages = {}; messages.mail_success = 'Your email has been sent successfully!'; messages.post_success = 'Your data has been updated!'; $.ajax({ url: "ajax-share-email.php", type: "POST", dataType: "json", data: {}, success: function(data) { if (data.status) { msg.text(messages.mail_success).addClass("email-msg-success"); } else { msg.text(data.msg).addClass("email-msg-error"); } } });
source share