Daniel Fein
Daniel Fein

Reputation: 327

How can I pass an array in a url to be retrieved by javascript?

I am trying to pass an array in a url so I tried this:

?question_id=10&value=1&array=["Saab","Volvo","BMW"]

This didn't work (didn't think it would, but it's a start).

It's a key and value array anyway so I needed something like this:

&array[28]=1&array[9]=1&array[2]=0&array[28]=0

But that didn't work either

Upvotes: 0

Views: 159

Answers (4)

Touki
Touki

Reputation: 7525

If you want to pass an array, you just have to set the different parts of the array in the URI like

http://example.com/myFile.php?cars[]=Saab&cars[]=volvo&cars[]=BMW

So you get your formated array in $_GET['cars']

print_r($_GET['cars']); // array('Saab', 'Volvo', 'BMW')

To get such a result in javascript you can use this kind of code

var cars = ['Saab', 'Volvo', 'BMW'],
    result = '';

for (var i = cars.length-1; i >= 0; i--) {
    results += 'cars[]='+arr[i]+'&';
}

results = results.substr(0, results.length-1); // cars[]=BMW&cars[]=Volvo&cars[]=Saab

Upvotes: 1

William Buttlicker
William Buttlicker

Reputation: 6000

You may also try this:

?arr[]="Saab"&arr[]="BMW"

Using the jQuery getUrlParam extension I can get url variables very easily

or in PHP

var_dump($_GET);

Upvotes: 0

GautamD31
GautamD31

Reputation: 28753

Try to pass like this

?question_id=10&value=1&my_array=Saab,Volvo,BMW

and you can get like

<?php
    $my_array = explode(',',$_GET['my_array']);
?>

or you can try like this

$aValues = array('Saab','Volvo','BMW');
$url = 'http://example.com/index.php?';
$url .= 'aValues[]=' . implode('&amp;aValues[]=', array_map('urlencode', $aValues));

Upvotes: 0

Sibiraj PR
Sibiraj PR

Reputation: 1481

in jquery try this

var arr = [1, 4, 9];
var url = '/page.php?arr=' + JSON.stringify(arr);
window.location.href = url;

Upvotes: 2

Related Questions