0pendev
0pendev

Reputation: 41

Unable to perform ajax request on epihpany browser

I am currently working on a website and I need to send a form without performing a redirection.

I have done the following to do so :

my_form.addEventListener('submit',function (event){
    event.preventDefault();
    var request = new XMLHttpRequest();
    var request_process = function (){
        if (request.readyState == 4) {
            if(request.status == 200){
                window.location.replace('nice_URL');
            }else if(request.status == 401){
                login_display_error('Authentification error : '+request.responseText);
            }else{
                alert('Server response, '+request.status+' :'+request.responseText);
            }
        }
    };
    var requestURL = new String();
    requestURL = "requestURL.com";

    request.addEventListener("readystatechange", request_process, false);
    request.withCredentials = true;
    request.open("POST",requestURL , true);
    request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    var parameters = new URLSearchParams(new FormData(my_form)).toString();
    request.send(parameters);
});

It works fine on Google Chrome, Chromium, Firefox Quantum but does not work with Epiphany browser and some older browser.

I want to stay in vanilla JS.

The problem seems to be that new URLSearchParams(new FormData(my_form)).toString(); returns an empty string.

Does anyone had the same issue ?

Upvotes: 0

Views: 33

Answers (2)

0pendev
0pendev

Reputation: 41

So I ended up creating my own function.

Thanks Quentin for your answer.

function serialize (form, expected){
    var encoded = new String();
    var elements = form.elements;
    var i;
    for(i=0; i<elements.length; i++){
        let e = elements[i];
        if (expected.includes(e.name)){
            if (e.multiple){
                let options = e.options;
                let j;
                for(j=0; j<options.length;j++){
                    let o = options[j];
                    if(o.selected && !o.disabled){
                        encoded = encoded.concat('&',e.name,'=',o.value);
                    }
                }
            }else{
                encoded = encoded.concat('&',e.name,'=',e.value);
            }
        }
    }
    return encoded.slice(1);
}

Upvotes: 0

Quentin
Quentin

Reputation: 943569

See the MDN documentation which shows the URLSearchParams is very shiny and new and thus does not have wide browser support.

It links to a Google blog entry and the library which in turn links to a polyfill.

Of course, that's a third-party library that isn't distributed with the browser, so probably doesn't count as vanilla JS, so you will have to reimplement it from scratch.

Upvotes: 0

Related Questions