Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass FormData over XMLHttpRequest using GET method

When Method of the senderform is POST, everything works fine. However, as soon as I change the method to GET, I don't receive anything on the server.

function ajaxSubmit(destinationElement, senderform) {

    var xmlreq = new XMLHttpRequest();
    var params = new FormData(senderform);
    xmlreq.open(senderform.method, senderform.action, true);

    if (/\/content\.php$/.test(senderform.action))
        xmlreq.onreadystatechange = receiveTable;
    else xmlreq.onreadystatechange = receiveText;

    xmlreq.send(params);
}

I know that I could manually append key-value pairs at the end of Action address, but the problem is that I don't know which form is going to be passed with what fields.

I would prefer native javaScript if possible.

How can I send a GET request using XMLHttpRequest with key-value pairs from senderform which points to form Element (the same way as it already works for POST requests)?

like image 866
Jakub M. Avatar asked Mar 09 '16 21:03

Jakub M.


2 Answers

First parameter is a reference to submit button, or form element itself. Second is callback function for XMLHttpRequest.

var ajaxSubmit = function(sender, callback) {
    var xmlreq = new XMLHttpRequest(), params;
    // look around for the sender form and key-value params
    if (sender.form !== undefined)
    {
        params = new FormData(sender.form);
        params.append(sender.name, sender.value);
        sender = sender.form;
    }
    else params = new FormData(sender);
    var actAddress = sender.action;

    // append the params to the address in action attribute
    if (sender.method == 'get')
    {
        var firstRun = true;
        for (var key of params.keys())
        {
            if (firstRun)
            {
                actAddress += '?';
                firstRun = false;
            }
            else actAddress += '&';
            actAddress += key + "=" + params.get(key);
        }
    }
    
    xmlreq.open(sender.method, actAddress, true);
    xmlreq.onreadystatechange = callback;
    if (sender.method == 'get')
        xmlreq.send();
    else xmlreq.send(params);
}

Therefore you can use it as

<form onsubmit="ajaxSubmit(this,callbackFx)" >
<!-- or -->
    <input onclick="ajaxSubmit(this,callbackFx)" type="submit" name="" value=""/>
</form>
like image 174
Jakub M. Avatar answered Sep 30 '22 05:09

Jakub M.


Are you sure the problem is not the PHP script? I see no reference that https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#send() with FormData needs POST to work, but if the PHP script takes the info from $POST or something (My PHP is rusty), the behavior would be different.

like image 44
Siderite Zackwehdex Avatar answered Sep 30 '22 05:09

Siderite Zackwehdex