0

I have a textarea where a user can enter 1 or more emails on there, each email separated by comma.

My js code:

    var emails = $("#emails").val().split(",");

    if (emails.length == 0)
    {
        window.alert("Enter an email address.");
        $("#emails").focus();
        return;
    }

    var valid = validateEmails(emails);
    var goodEmails = valid[0];
    var badEmails = valid[1];
    var json = JSON.stringify(goodEmails);

    $.ajax
    ({
        url: "/mfa/service/initiate_user",
        type: "POST",
        data: {"emails" : json},

The data I see:

["[email protected]","[email protected]]

What I was hoping for:

[email protected], [email protected]

The way I would handle it in the backend is basically stripping out the "[ ]" from it then stripping out the quotes from each email.

What is the proper way to send the emails to backend without those silly brackets and quotes?

2
  • What does validateEmails return? are the emails still split by ,? Commented Mar 4, 2013 at 22:42
  • @quandrum validateEmails() basically splits the emails string, then return a list of [good emails, bad emails] Commented Mar 4, 2013 at 22:46

2 Answers 2

3

To get the form [email protected], [email protected] you can use the Array.join(delim) function.

Ex:

var emails = ["[email protected]", "[email protected]"];
var email_string = emails.join(", ");
// email_string:
// [email protected], [email protected]

However, I'd say you'd want to keep the emails as an array and do the follow:

var valid = validateEmails(emails);
var goodEmails = valid[0];
var badEmails = valid[1];

$.ajax
({
    url: "/mfa/service/initiate_user",
    type: "POST",
    data: {"emails" : goodEmails},
...

This will allow you to parse the JSON object coming back. Instead of having a string in emails you'll have an array. Not sure of your back-end but this may be an easier approach if you are already able to parse the JSON.

Sign up to request clarification or add additional context in comments.

1 Comment

ah the join! that seems to be workin. thanks! i have to use string, thats how our servlets are set up lol.
0

try to add header to ajax configuration:

headers: {'Content-type' : "application/json; charset=utf-8"}

Comments

Your Answer

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.