views:

33

answers:

2

I'm trying to use the following switch statement in an ajax success callback:

success: function(datain) {
                    switch (datain)
                    {
                        case "ERROR. No ID. Try again":
                            $(".errors").append('There was an error.');
                            break;

                        case "ERROR. Wrong captcha. Try again":
                            $(".errors").append('There was an error.');
                            break;
                    }
                }

datain is a string (typeof datain returns string) and it does indeed contain the same text, capitalization and punctuation as the case so why would it not match either of the cases?

console.log(datain) and console.log("ERROR. No ID. Try again") match exactly and both return a typeof of string so why does my case never get matched?


Solution and cause

The solution is offered by palswim below $.trim(datain). The cause was visible in Firebug and it was the fact that the string had a newline at the end while my switch case did not... so I was getting "foo\n" and trying to match "foo". Given that js uses === in the switch this, naturally (now that I see it), is why it failed.

+1  A: 

Try trimming your strings.

In jQuery:

switch($.trim(datain))
{ //...

But trying to match strings that long is fraught with peril!

palswim
I know :(. I'm stuck receiving some data from a bit of java middleware and I have no access to the code (nor knowledge of java even if I did). I'll try trimming and see how it goes...
rg88
Perfect. Did the trick. Thanks palswim.
rg88
+1  A: 

No clue as to why neither are called based on what you say. At the risk of suggesting the obvious though: Put in a "default" statement at the end of the switch to make sure you're function is being called, and in the default statement do some if comparisons: datain === "ERROR:...".

One other thing that might be easy to miss is if (possibly) there should be a "." at the end of "...Try again."

mjhm
Thanks for the suggestions. I have a default at the end, I just left it off for my example. It turned out there was a newline at the end of the string that was causing it to fail.
rg88