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.

2

4 Answers 4

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);
}
Sign up to request clarification or add additional context in comments.

8 Comments

Can I get this in $_POST['data']
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']
What is queryString here? I think it should be data.
@user2567857: Don't make edits to the post that changes the original meaning. A comment will suffice.
@staticx that depends on the OP. This answer is accepted hence it is likely that users won't read the comments.
|
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>';
}
?>

1 Comment

It would be nice to know why my answer got down voted. We are all learning here!
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);
}

Comments

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 )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.