user3070028
user3070028

Reputation: 35

pass array in javascript .send function

This is regarding passing an array to a php page.Is it possible to send an array like this(code below)? if its not possible , what changes should i bring about to my code?

function ajax_post(){    
var hr = new XMLHttpRequest();    
hr.open("POST", "get_numbers.php", true);  
hr.setRequestHeader("Content-type", "application/json");    
hr.onreadystatechange = function() {
    if(hr.readyState == 4 && hr.status == 200) {
        var data = JSON.parse(hr.responseText);
        var results=document.getElementById("ace");
        //results.innerHTML=data.u1.port;
        for (var obj in data)
       {
        results.innerHTML+=data[obj].port;
       }
    }
} 
var cards= new Array();
cards[0]="hearts";
cards[1]="spades";
hr.send(cards); 
results.innerHTML = "processing...";
}

Upvotes: 0

Views: 105

Answers (1)

jfriend00
jfriend00

Reputation: 707386

.send() doesn't take a javascript array. There are a number of forms of data you could send and you will have to decide which form is appropriate, but an array is not one of them. The simplest would be to turn the array into a JSON string and send that.

var cards = [
    "hearts",
    "spades"
];

hr.send(JSON.stringify(cards)); 

Then, on the receiving end of things, you would parse the JSON back into whatever language form you are using on the server end. If it's PHP, then you can use the PHP functions for parsing the JSON which will put the data into a PHP array on your server.

Per the MDN doc page for the XMLHttpRequest object, .send() can take the following types of data:

void send();
void send(ArrayBufferView data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);

Using JSON would be using the string type.

Upvotes: 1

Related Questions