How do I pass along variables with XMLHTTPRequest

JavascriptHtmlAjax

Javascript Problem Overview


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)

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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.

Solution 3 - Javascript

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);

Solution 4 - Javascript

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.

Solution 5 - Javascript

Following is correct way:

xmlhttp.open("GET","getuser.php?fname="+abc ,true);

Solution 6 - Javascript

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

Solution 7 - Javascript

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
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSteven MatthewsView Question on Stackoverflow
Solution 1 - JavascriptTJHeuvelView Answer on Stackoverflow
Solution 2 - JavascriptJames ForbesView Answer on Stackoverflow
Solution 3 - JavascriptAuxTacoView Answer on Stackoverflow
Solution 4 - JavascriptmellamokbView Answer on Stackoverflow
Solution 5 - JavascriptMuhammad Junaid IqbalView Answer on Stackoverflow
Solution 6 - JavascriptcowlsView Answer on Stackoverflow
Solution 7 - JavascriptENDEESAView Answer on Stackoverflow