0

I want to do this:

$.getJSON("myscript.php", {0: info[0].value, 1: info[1].value, 2: info[2].value ......});

How do I build a loop to create the second object (the parameters)? I've tried the following, which doesn't work:

var n = info.length;
var params = new Array();
for(i=0; i<n; i++) params[i] = info[i].value;
$.getJSON("myscript.php", params);

The resulting GET to myscript.php becomes myscript.php?undefined=&undefined=&...

2
  • 1
    It would be more idiomatic to do $.getJSON("myscript.php, { data: params });. Then in PHP $_GET['data'] will be the array. Commented May 31, 2013 at 18:29
  • From the documentation about the data parameter: "A plain object or string that is sent to the server with the request.". An array is neither a plain object nor a string. Commented May 31, 2013 at 18:36

1 Answer 1

4

Create params as an object instead of an array

var n = info.length;
var params = {};
for(i=0; i<n; i++) params[i] = info[i].value;
$.getJSON("myscript.php", params);

If you want array to work

var n = info.length;
var params = new Array();
for(i=0; i<n; i++){ 
    params[i] = {
        name: i, 
        value: info[i].value
    }
};
$.getJSON("myscript.php", params);
Sign up to request clarification or add additional context in comments.

2 Comments

Great, that works. Thank you. By the way, why doesn't the array work?
@Eric Maybe for the array to work, you need to push items to it: params.push(info[i].value);? As @ArunPJohny and @FelixKling pointed out, though, you have to use an object.

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.