Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending an array using javascript ajax

In jquery I can do this

myAray=['abc', '123', 'more'];
$.post('myscript.php', {data:myAray}, function(data){
    alert(data);
});

How can I do the same thing using plain javascript ? I want to send an array to my php script using POST method. I have found so many examples but all of them are jquery related.

Thanks in advance.

like image 482
SPS Avatar asked Jan 21 '26 07:01

SPS


1 Answers

You will have to use XMLHttpRequest and serialize the array yourself:

function ajax(myArray) {

    var xmlHTTP;

    if (window.XMLHttpRequest) { 
        xmlHTTP = new XMLHttpRequest();
    } else { 
        xmlHTTP = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlHTTP.onreadystatechange = function () {
        if (xmlHTTP.readyState == 4 && xmlHTTP.status == 200) {
            // do whatever it is you want to do
        }
    }

    //Serialize the data
    var queryString = "";
    for(var i = 0; i < myArray.length; i++) {
        queryString += "myArray=" + myArray[i];

        //Append an & except after the last element
        if(i < myArray.length - 1) {
           queryString += "&";
        }
    }

    xmlHTTP.open("POST", "www.myurl.com", true);
    xmlHTTP.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
    xmlHTTP.send(queryString);
}
like image 108
Vivin Paliath Avatar answered Jan 23 '26 19:01

Vivin Paliath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!