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)
This question is related to
javascript
html
ajax
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
}
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');_x000D_
const params = new URLSearchParams();_x000D_
params.set('var1', 'foo');_x000D_
params.set('var2', 'bar');_x000D_
target.search = params.toString();_x000D_
_x000D_
console.log(target);
_x000D_
Or to convert an entire object's worth of parameters:
const paramsObject = {_x000D_
var1: 'foo',_x000D_
var2: 'bar'_x000D_
};_x000D_
_x000D_
const target = new URL('https://example.com/endpoint');_x000D_
target.search = new URLSearchParams(paramsObject).toString();_x000D_
_x000D_
console.log(target);
_x000D_
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.
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.
Following is correct way:
xmlhttp.open("GET","getuser.php?fname="+abc ,true);
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
Source: Stackoverflow.com