Home > Mobile >  How to send values as form object via AJAX?
How to send values as form object via AJAX?

Time:10-26

We're experiencing problems with special characters from a pw field send as string via AJAX.

Current situation is this:

function resetPW() {
    var username = encodeURIComponent($("#email").val());
    var password = encodeURIComponent($("#newpassword").val());

    $.ajax({
        url: "/setnewpassword",
        type: "post",
        data: "username="   username   "&password="   password,
    }).done(function (response) { 
        ... 
    });

Some special characters (&) have been replaced by blanks before (this seems to be fixed with the encoding, which wasn't there before), others seem to be wrong encoded. At the end, a lot of users are having problems with their login.

I really don't know what to do here. Someone mentioned I should send data via "form objects" - but how do I achieve this here? I can find some questions to this topic already online, but as I am absolute inexperienced in object building and AJAX at all, I cannot adopt those replies to my special problem. So please excuse if this question is a duplicate for you!

CodePudding user response:

Don't encode the data yourself. jQuery does that for you. Let it.

function resetPW() {
    return $.post("/setnewpassword", {
        username: $("#email").val(),
        password: $("#newpassword").val()
    }).done(function (response) { 
        ... 
    });
}

If that doesn't work, then your server code is broken.

Some special characters (&) have been replaced by blanks before

No, don't do that either. Leave everything exactly as the user has entered it.

  • Related