iCodeLikeImDrunk
iCodeLikeImDrunk

Reputation: 17866

How to send js array to servlet using ajax?

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?

Upvotes: 0

Views: 1816

Answers (2)

Atep
Atep

Reputation: 486

try to add header to ajax configuration:

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

Upvotes: 0

travis
travis

Reputation: 8615

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.

Upvotes: 3

Related Questions