Murad Emi
Murad Emi

Reputation: 51

How to send array to PHP with AJAX

I have got this array

var Age=[$(".AJcountry").find(".focus").html()];

and this AJAX

$.ajax({
    type: "GET",
    url: '../connect.php',
    data: "CountS=" + Age,
    success: function (dataa)
    {
        alert(dataa);
    }
});

But it only return the last selected item.How can i send to PHP everything inside array

Upvotes: 1

Views: 38

Answers (3)

Martiens Kropff
Martiens Kropff

Reputation: 118

Convert the array to JSON like this:

var json = JSON.Stringify(Age);

Then send it via AJAX like you are doing:

data: {CountS: Age}

In the back-end convert the JSON back to an array like so:

$json = json_decode($_GET['CountS']);

This method converts the data to a very small text string before transmitting it. The PHP back-end then converts it back to an array. This method also works with most objects in JavaScript. You can read more about JSON here

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

If you provide an object to the data property of $.ajax then jQuery will serialise it for you:

data: { CountS: Age }

Also note that while you are putting the html() value of the .focus element in an array, that array will always only contain one string element, so the array itself seems completely redundant in this case.

Upvotes: 0

madalinivascu
madalinivascu

Reputation: 32354

Use a loop

var Age=[];

$(".AJcountry").find(".focus").each(function(){
Age.push($(this).html());
});

in ajax:

data: {CountS:Age},

in php you do :

echo $_GET['CountS'][0];//get the first

or a loop

Upvotes: 1

Related Questions