3

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.

SPS
  • 33
  • 1
  • 4
  • There are tons of tutorials for this. Check google with "ajax post javascript array" – Chris Aug 29 '12 at 22:55
  • Fourth answer from top to bottom: [http://stackoverflow.com/questions/5350377/how-to-make-an-ajax-request-to-post-json-data-and-process-the-response][1] [1]: http://stackoverflow.com/questions/5350377/how-to-make-an-ajax-request-to-post-json-data-and-process-the-response – Ivan Alagenchev Aug 29 '12 at 22:57

4 Answers4

2

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);
}
Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
  • Can I get this in $_POST['data'] – SPS Aug 29 '12 at 23:13
  • I imagine it would show up under `$_POST['myArray']`. You can change the string in the for loop to `"data=" + myArray[i];` and it should show up under `$_POST['data']` – Vivin Paliath Aug 29 '12 at 23:14
  • What is `queryString` here? I think it should be `data`. – user2567857 Jul 16 '14 at 13:17
  • @user2567857: Don't make edits to the post that changes the original meaning. A comment will suffice. – Engineer2021 Jul 16 '14 at 13:22
  • @staticx Yeah I know but the answer here is wrong. If you try out in you localserver then querystring gives your error. Further, if you read the comments, then Vivin has said that `change the string in the for loop to data= + myArray[i]`, which clearly shows that he meant queryString to be data. – user2567857 Jul 16 '14 at 13:24
  • @user2567857: Let the OP change it. Your comment here will help future readers. – Engineer2021 Jul 16 '14 at 13:26
  • 1
    @staticx that depends on the OP. This answer is accepted hence it is likely that users won't read the comments. – user2567857 Jul 16 '14 at 13:27
  • @user2567857: Yes, they will. Trust me. We have been doing this for a long time. – Engineer2021 Jul 16 '14 at 13:28
1

Mess around with this.

JS

var myarray = Array("test","boom","monkey");
send("test.php", myarray);  

function send(url, data)  
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function()
{
    if (xhr.readyState==4 && xhr.status==200)
    {
        console.log(xhr.responseText);
    }
}
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("data= " +data);
}

PHP

<?php 
$array = explode(',', $_POST["data"]);

for($i=0,$l=count($array); $i<$l; $i++) 
{
echo $array[$i].'<br>';
}
?>
manish
  • 497
  • 9
  • 17
0

Something like this: post is either POST or GET. params are only used in POST otherwise include what you need in the url for GET. success and error are both string names of the functions, not the functions themselves, which is why you need executeFunctionByName, thanks to Jason Bunting: How to execute a JavaScript function when I have its name as a string

getRemoteData = function (url, post,params, success, error){

var http = false;
if (navigator.appName === "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
http = new XMLHttpRequest();
}

http.open(post, url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {var resp; if (http.readyState === 4 && http.status == 200) {  resp=http.responseText; executeFunctionByName(success, window, resp); }else if(http.status == 400){resp=http.responseText; executeFunctionByName(error, window, resp);}};

http.send(params);
return false;
};


function executeFunctionByName(functionName, context, args) {
  args = Array.prototype.slice.call(arguments).splice(2);
  var namespaces = functionName.split(".");
  var func = namespaces.pop();
  for(var i = 0; i < namespaces.length; i++) {
    context = context[namespaces[i]];
  }
  return context[func].apply(this, args);
}
Community
  • 1
  • 1
K'shin Gendron
  • 1,589
  • 1
  • 12
  • 14
0
function loadXMLDoc()
{
  var xmlhttp;
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
   xmlhttp=new XMLHttpRequest();
  }
  else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
   if (xmlhttp.readyState==4 && xmlhttp.status==200)
   {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
   }
  }
xmlhttp.open("POST","jsArrayPhp.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("test[]=Henry&test[]=Ford");
}

Take attention here: test[]=Henry&test[]=Ford"

Where test is the name of array you'll use in php.

In php

<?php
 print_r($_POST['test']);
?>

It'd produce: Array ( [0] => Henry [1] => Ford )

Marcelo
  • 73
  • 1
  • 6