4

I am receiving a JSON string from an ajax call and would like to convert a value to a predefined variable:

var predefined = "hello world";
var foo = {"msg":"predefined"}; // JSON string

I want to echo out the standard string accessing it with

alert(foo.msg)

EDIT: to make the answer more clear here is my call:

var success_msg = "Your email is send successfully!";

$.ajax({
    url: "ajax-share-email.php",
    type: "POST", 
    dataType: "json", 
    data: {},
    success: function(data) {
        if (data.status == "success") {
            msg.text(data.msg).addClass("email-msg-success");                   
        } else {
            msg.text(data.msg).addClass("email-msg-error");
        }
    }
})

ajax-share-email.php responds:

{"status":"success", "msg":"success_msg"}
FFish
  • 10,964
  • 34
  • 95
  • 136
  • 5
    Why not keep the predefined messages on the server side and just send the actual message? – tvanfosson Jan 09 '11 at 15:00
  • 1
    @tvanfosson To keep the JSON small perhaps. – Hemlock Jan 09 '11 at 15:08
  • I am reconsidering this now, cheers! – FFish Jan 09 '11 at 15:10
  • @tvanfosson Another good reason would be to consider this from an MVC perspective. The server could be an external API sending model-level information and the client is acting as the view, transforming geeky response codes into pretty HTML and human-readable messages. – Phrogz Jan 09 '11 at 15:10
  • @Hemlock - yeah, maybe there are cases where this would be a real performance win (e.g., lots of large messages and high frequency AJAX calls), but doing it server side leads to a simpler client and faster initial download. I'd need to be convinced that it's really necessary. If you're only saving a few dozen or even hundred bytes per message, is is really necessary? – tvanfosson Jan 09 '11 at 15:14
  • @Phrogz - I could see that as a reason, though I'd typically deliver messages verbosely. Note: I didn't say it was absolutely wrong, just that it seems a strange way to do it for the typical case. – tvanfosson Jan 09 '11 at 15:19
  • @tvanfosson Agreed; I already upvoted your comment, but wanted to note the potential cases where it might be reasonable. – Phrogz Jan 09 '11 at 15:22

5 Answers5

5
var strings = {"predefined":"hello world"};
alert(strings[foo.msg]);

or e.g.

var messages = {};
messages.success_msg = "Your email is send successfully!";

// ...
            msg.text(messages[data.msg]).addClass("email-msg-success");             
fuzzyTew
  • 3,511
  • 29
  • 24
  • 1
    If I had to do this on the client, this is probably the method I would use. My preference would be to keep the message dictionary on the server, though, and just send the actual message to the client. I suppose there are cases where loading all the messages (I have to assume there must be more) on the client would make sense, but I'd have to be convinced. – tvanfosson Jan 09 '11 at 15:10
  • +1 for being the only (or first) one to actually understand what was being asked. – Phrogz Jan 09 '11 at 15:11
  • @FFish Edited to provide an example of inclusion – fuzzyTew Jan 09 '11 at 15:29
  • Oh you are wrapping it in an object. Great thanks for all the help! – FFish Jan 09 '11 at 15:34
2

How about this -- just use the message inline on success and don't even bother to make it part of the JSON. On an error, do include the entire message and use it directly. Also, I'd have your server return something like:

{ "status": true }

or

{ "status": false, "msg": "The mail server is down." }

Then you can just evaluate it as a boolean 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 reusing your messages for multiple functions, then refactor to a message dictionary and reference it from there. Note your messages object would likely need to be a global variable, or at least in the outer scope of all the 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");
        }
    }
});
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
0
var predefined = "hello world";
var foo = {"msg":predefined}; // JSON string
alert(foo.msg)

?

Andreyco
  • 22,476
  • 5
  • 61
  • 65
0
var out = eval(foo.msg); // out is now "hello world"

Note: do not use eval() if you are not sure what the content of foo.msg is.

or

var out = foo.msg=="predefined" ? predefined : foo.msg;
Floern
  • 33,559
  • 24
  • 104
  • 119
  • 2
    `eval` is evil and dangerous. There are almost no cases where its use is a good idea. (And this is not one of them.) – Phrogz Jan 09 '11 at 15:05
  • Why would this be downvoted? @Phrogz: If the data is from a secure source, what's the problem? +1 – user113716 Jan 09 '11 at 15:06
  • I know it's evil, but it's a way to get the result – Floern Jan 09 '11 at 15:07
  • down voted probably for the use of eval(foo.msg) in one of the suggestions – diagonalbatman Jan 09 '11 at 15:08
  • @FFish: Do you have absolute control over the JSON data being sent? In other words, it doesn't come from *any* sort of user input, or from some other server? – user113716 Jan 09 '11 at 15:09
  • @patrickdw I downvoted for the reason I stated. Not only is eval dangerous in general _(though you are right, perhaps not in this case)_, it's also slow, requiring the browser to spin up the lexer and parser. This is simply a bad answer when what is wanted is to look up a property dynamically, and it also naïvely encourages the use of `eval`. – Phrogz Jan 09 '11 at 15:15
  • @Phrogz: With all due respect, it is just as erroneous to give a blanket *eval is evil* as it is to blindly suggest eval. And *"when what is wanted is to look up a property dynamically"* isn't necessarily right. What is desired is to look up a *variable* which would only become a property if it was defined globally. – user113716 Jan 09 '11 at 15:21
  • @patrickdw I appreciate your different opinion. If this was the only answer, I would surely have given further explanation. As the right answer exists and has been upvoted, I assumed that @Floem will look at it and learn from it. Coders (myself surely included) have _goals_, and often mistakenly describe them with overly restrictive/specific implementation requirements. Yes, if the OP _had_ to dynamically fetch the value from a variable, `eval` would be warranted. But as @fuzzyTew's answer shows, a small change in code achieves the same goal with a much better solution. – Phrogz Jan 09 '11 at 15:29
  • @Phrogz: Alright. Yes, I do agree that it is more sensible to use the approach in the main upvoted answer. I think it's more the "eval is evil" mantra that is beginning to get to me. ;o) – user113716 Jan 09 '11 at 15:37
0

IFF I understand what you are asking, I think I have all of the pieces here.

You have a variable predefined and you want to be able to return that in your json and have the resulting parsed object contain the value in predefined

JSON.parse will not work for you (at least not in Chrome), but eval will.

var predefined = "Hi! I'm predefined";
// ...

var json = '{"foo": predefined}'; // notice no quotes
var response = eval("(" + json + ")");
alert(response.foo);
Hemlock
  • 6,130
  • 1
  • 27
  • 37
  • Downvoting because (as commented on another answer): Not only is eval dangerous in general _(though perhaps not in this case)_, it is also slow, requiring the browser to spin up the lexer and parser. This is a bad answer when what is wanted is to look up a property dynamically, and it also naïvely encourages the use of `eval` and global variables. There are very few cases where `eval` should be used; this is not one of them. – Phrogz Jan 09 '11 at 15:19
  • @Phrogz I disagree. This is a case where eval is useful (although, might actually be dangerous in terms of injection). It's evil when used to replace bracket notation. This knee jerk fear of `eval` is silly. – Hemlock Jan 09 '11 at 15:49
  • Further - eval is the **fastest** solution that supports older versions of IE and provides a solution that fits the form of the question. – Hemlock Jan 09 '11 at 17:34