Home > Net >  AJAX loses " " from email address string
AJAX loses " " from email address string

Time:10-26

I have some ajax code that seems to work fine for most of the places I've used it so far, however on trying to use it for a user details update on my page, it seems to lose the " " symbol if used in an email address (such as test [email protected] comes through as test [email protected] in my PHP file.

function prefUpdate() {
    let ytTog = document.getElementById("togBtn").checked;
    let unameNew = document.getElementById("uname").value;
    let usnameNew = document.getElementById("usname").value;
    let emailNew = document.getElementById("email").value;
    let params = "ytTog=" ytTog "&unameNew=" unameNew "&usnameNew=" usnameNew "&emailNew=" emailNew;
    let xhr = new XMLHttpRequest();
    xhr.open('POST', 'pref_update.php', true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 4 && xhr.status == 200) {
            let return_data = xhr.responseText;
            if(return_data) {
               <do stuff>
            }
        }
    }
    xhr.send(params);
}

So here I grab a button, first and less name along with email address and pass it to a php file which returns some data that I can do stuff with.

I feel it could be the 'application/x-www-form-urlencoded' that's causing it, but googling around that hasn't given me much of a way of resolving it.

[edit] just to say I tried multipart/form-data in place of application/x-www-form-urlencoded but this just broke things entirely.

CodePudding user response:

You're right. For Content-Type: application/x-www-form-urlencoded all ' ' signs mean ' ' (space). So it should be encoded by function encodeURIComponent().

let params = encodeURIComponent("ytTog=" ytTog "&unameNew=" unameNew "&usnameNew=" usnameNew "&emailNew=" emailNew);

Form MDN:

For application/x-www-form-urlencoded, spaces are to be replaced by , so one may wish to follow a encodeURIComponent() replacement with an additional replacement of with .

CodePudding user response:

You have to encode your data properly when making an ajax call.
You can use a URLSearchParams object to do this for you.

let params = new URLSearchParams({ytTog, unameNew, usnameNew, emailNew});
...
xhr.send(params);
  • Related