Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you pass multiple parameters of the same type to jQuery Get

I'm trying to GET some data from a site using jQuery $.get. I need to set 2 parameters of the same type:

..&q=Some Text&q=Some other text

jQuery appears to be overwriting the first instance of q with the second and only sending 1. Any way around this?

This is the code I was trying to use:

var params = {
       "otherParam":"x",
       "q":text,
       "q":title
};
$.get(url, params, mySuccessFunction);
like image 708
Cliff Ribaudo Avatar asked Oct 13 '12 19:10

Cliff Ribaudo


People also ask

How do you pass multiple GET parameters?

The value for the corresponding parameter is given after the symbol "equals" (=). Multiple parameters can be passed through the URL by separating them with multiple "&".


3 Answers

Try:

var params = {
  "otherParam": "x",
  "q": [ text, title ]
};

edit — more information: array-valued parameters like that are treated specially by jQuery. To appease many common server frameworks, by default (since release 1.5 or 1.6 I think) those will result in parameter names that include "[]" (open- and close-bracket characters) as a suffix (no number, contrary to my erroneous comment below). If you don't want that, you can set

jQuery.ajaxSettings.traditional = true;

and it'll just be "q" instead of "q[]".

like image 76
Pointy Avatar answered Oct 11 '22 14:10

Pointy


And another way to solve it that does not require encodeURIComponent() or messing with jQuery.ajaxSettings.traditional = true; which I would prefer not to do because I don't want to interfere (even temporarily) with what other parts of the site might be doing simultaneously.

Is:

 var params=[ 
       {name:"q", value:title},
       {name:"q", value:text}
 ];
 $.get(url, params, mySuccessFunction);
like image 40
Cliff Ribaudo Avatar answered Oct 11 '22 13:10

Cliff Ribaudo


Another approach without modifying jQuery.ajaxSettings.traditional = true; is to use $.param() http://api.jquery.com/jQuery.param/

So something like this:

var params = {
  "otherParam": "x",
  "q": [ text, title ]
};

$.get(url, $.param(params, true), mySuccessFunction);
like image 24
Jhony Fung Avatar answered Oct 11 '22 14:10

Jhony Fung