62

How do I send variables to the server with XMLHTTPRequest? Would I just add them to the end of the URL of the GET request, like ?variable1=?variable2=, etc?

So more or less:

XMLHttpRequest("GET", "blahblah.psp?variable1=?" + var1 + "?variable2=" + var2, true)
2
  • 2
    You can do it that way, but you'll need to separate the key/value pairs with ampersands instead of question marks. So: "blahblah.php?variable1=" + var1 + "&variable2=" + var2
    – nnnnnn
    Nov 9, 2011 at 12:02
  • 1
    Also take care that var1 and var2 do not themselves contain reserved characters. You may want to escape them with encodeURIComponent(). Jul 1, 2014 at 18:31

7 Answers 7

72

If you want to pass variables to the server using GET that would be the way yes. Remember to escape (urlencode) them properly!

It is also possible to use POST, if you dont want your variables to be visible.

A complete sample would be:

var url = "bla.php";
var params = "somevariable=somevalue&anothervariable=anothervalue";
var http = new XMLHttpRequest();

http.open("GET", url+"?"+params, true);
http.onreadystatechange = function()
{
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(null);

To test this, (using PHP) you could var_dump $_GET to see what you retrieve.

0
54

Manually formatting the query string is fine for simple situations. But it can become tedious when there are many parameters.

You could write a simple utility function that handles building the query formatting for you.

function formatParams( params ){
  return "?" + Object
        .keys(params)
        .map(function(key){
          return key+"="+encodeURIComponent(params[key])
        })
        .join("&")
}

And you would use it this way to build a request.

var endpoint = "https://api.example.com/endpoint"
var params = {
  a: 1, 
  b: 2,
  c: 3
}

var url = endpoint + formatParams(params)
//=> "https://api.example.com/endpoint?a=1&b=2&c=3"

There are many utility functions available for manipulating URL's. If you have JQuery in your project you could give http://api.jquery.com/jquery.param/ a try.

It is similar to the above example function, but handles recursively serializing nested objects and arrays.

27

If you're allergic to string concatenation and don't need IE compatibility, you can use URL and URLSearchParams:

const target = new URL('https://example.com/endpoint');
const params = new URLSearchParams();
params.set('var1', 'foo');
params.set('var2', 'bar');
target.search = params.toString();

console.log(target);

Or to convert an entire object's worth of parameters:

const paramsObject = {
  var1: 'foo',
  var2: 'bar'
};

const target = new URL('https://example.com/endpoint');
target.search = new URLSearchParams(paramsObject).toString();

console.log(target);

1
  • great - at least normal way
    – Emiter
    May 8, 2020 at 5:10
7

The correct format for passing variables in a GET request is

?variable1=value1&variable2=value2&variable3=value3...
                 ^ ---notice &--- ^

But essentially, you have the right idea.

0
2

Following is correct way:

xmlhttp.open("GET","getuser.php?fname="+abc ,true);
1
  • So much work trying to find this. No need to use an encoded argument in send() just to pass through the PHP query string. Of course, POST is better if you need security. Dec 13, 2022 at 16:45
0

Yes that's the correct method to do it with a GET request.

However, please remember that multiple query string parameters should be separated with &

eg. ?variable1=value1&variable2=value2

0

How about?

function callHttpService(url, params){
  // Assume params contains key/value request params
  let queryStrings = '';

  for(let key in params){
      queryStrings += `${key}=${params[key]}&`
    } 
 const fullUrl = `${url}?queryStrings`

  //make http request with fullUrl
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.