I have a rest call,where it requires one parameter empid to be passed of type
application/x-www-form-urlencoded
Iam trying to consume that using the following code.But the value is getting passed as undefined to the restcall
function searchEmployee(employeeid){
var empEndpoint = 'http://localhost:3001/searchemp';
var http = new XMLHttpRequest();
http.open('POST',empEndpoint,true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
var empid = employeeid;
http.send(empid) ;
}
Please can someone point out the mistake and help me how to POST that in proper format.
***Edit added server code
app.post('/searchemp',function(req,res){
reqbody = req.body.empid;
console.log(reqbody,"reqbody");
var empdetails =con.query('SELECT * FROM tasktable WHERE Empid =?',reqbody,
function(err,rows){
if(err) throw err;
console.log('EMP Data received from Db:\n');
res.send(rows);
});
});
That depends on where you call the function searchEmployee
from and how you do it.
as var empid = employeeid;
and employeeid
is the first parameter of your function you should call searchEmployee
with an appropriate parameter such as 2474
.
so your should call it like that:
searchEmployee(2474); function searchEmployee(employeeid){ var empEndpoint = 'http://localhost:3001/searchemp'; var http = new XMLHttpRequest(); http.open('POST',empEndpoint,true); http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); var params = `empid=${empid}`; http.send(params); }
maybe this helps: http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
var url = "get_data.php"; var params = "lorem=ipsum&name=binny"; http.open("POST", url, true); //Send the proper header information along with the request http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http.setRequestHeader("Content-length", params.length); http.setRequestHeader("Connection", "close"); http.onreadystatechange = function() {//Call a function when the state changes. if(http.readyState == 4 && http.status == 200) { alert(http.responseText); } } http.send(params);
especially this should be the way to go:
var params = "lorem=ipsum&name=binny";
your equivalent should look like this:
var params = `empid=${empid}`; http.send(params);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.