I have a problem with my post request in javascript.
I have the following code for sending the post request
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
//stuff
}
};
xhttp.open("POST", "/deleteUser", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=" + username);
And in my node.js express application i receive it like this
var username = req.body.username;
Now this works perfect with normal characters (numbers and letters). But when i tried
>df)(*&&^%$
as username it gets cut off to
>df)(*
I suspect it is because of the &.
My question: How do i prevent it from getting cut off.
Thanks in advance!
You need to convert the username parameter into a URI safe string, using xhttp.send("username="+encodeURIComponent(username));
Related
I am having issues correctly setting up my XMLHttpRequest object to POST data to a server. The data (from an HTML form) never seems to get posted, or at least readyState == 4 && status are never reached.
function PostToAPI() {
var payersName = document.forms["myForm"]["payersName"].value;
var recipientPhoneNumber = document.forms["myForm"]["recipientPhoneNumber"].value;
var apiKey = document.forms["myForm"]["apiKey"].value;
var params = "payersName="+payersName+
"&recipientPhoneNumber="+recipientPhoneNumber+
"&apiKey="+apiKey;
alert(params); // Note#1
var Url = "https://api.blackShawls.af/c2b"; // Note#2
var xhr = new XMLHttpRequest();
xhr.open('POST', Url, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = processRequest;
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText.headers.Host); // Note#3
}
}
xhr.send(params);
}
Notes
(Note#1) This alert yields the following result:
This suggests that the various fields from the HTML form have been successfully read in, and that everything is working just fine to this point.
(Note#2) The Url value here is fictitious, in contrast to one in my code.
(Note#3) The alert(xhr.responseText.headers.Host); never seems to fire-up, suggesting that the readyState and the status conditions are never met.
Or could it be that the xhr.send(params) is never sent?
Can someone kindly point out where I am going wrong in my code?
Looking forward to your help.
I'm trying to inject new user into a separate database after they sign up on Auth0. I was told that using hook is sufficient but I'm not sure how to make the call.
I tried
var django_endpoint = 'some/endpoint/';
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("POST", django_endpoint, true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send('{"username": user.email}');
cb(null, user, context);
and ran it, but my endpoint is not receiving anything although the result shows 200 on the auth0 test screen
I am unable to send JSON object to XMLHttpRequest(). However, if I send string data through send(), it works. For example, the following code works:
var xhr = new XMLHttpRequest();
var url = 'https://xyz.info/api/contacts';
xhr.open("POST", url,true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
// Request finished. Do processing here.
}
}
xhr.send("apikey=ee694eabf9e3&firstname=Raja1&lastname=Kumars&phone=123456");
However, if I try to send data using JSON, it posts nothing to the url. The following code does not work.
var xhr = new XMLHttpRequest();
var url = 'https://xyz.info/api/contacts';
xhr.open("POST", url,true);
//xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
// Request finished. Do processing here.
}
}
xhr.send(JSON.stringify({
'apikey' :'ee6915d4ee4b4df66bba82277e3',
'firstname' : 'Kumar',
'lastname' : 'Sunder',
'phone':'5557773334'
}));
You're sending very different information in your two calls. Some sample code:
var _stringify = JSON.stringify({
'apikey' :'ee6915d4ee4b4df66bba82277e3',
'firstname' : 'Kumar',
'lastname' : 'Sunder',
'phone':'5557773334'
});
console.log(_stringify);
var _orig = "apikey=ee694eabf9e3&firstname=Raja1&lastname=Kumars&phone=123456"
var _encoded = encodeURI(_stringify);
console.log(_orig);
console.log(_encoded);
when your original string is printed to the console log, it looks as you would expect:
apikey=ee694eabf9e3&firstname=Raja1&lastname=Kumars&phone=123456
when the result of JSON.stringify is printed to the console, it returns:
{"apikey":"ee6915d4ee4b4df66bba82277e3","firstname":"Kumar","lastname":"Sunder","phone":"5557773334"}
That is, it comes complete with lots of extra double quote marks and left and right brackets. If you want to send all of that as a string (as in your initial example), you would need to URI encode the result of the JSON.stringify call. This is what happens with the "_encoded" variable, which contains:
%7B%22apikey%22:%22ee6915d4ee4b4df66bba82277e3%22,%22firstname%22:%22Kumar%22,%22lastname%22:%22Sunder%22,%22phone%22:%225557773334%22%7D
You are sending via a POST action, but then sending the data via a url string. If you want to send it that way you need to set it to GET.
I am using example code which I found here:
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_post2
I want to get a JSON string from an endpoint that requires authentication.
How do I specify my ID / Pass with the request being made to the endpoint ( Is there a HTTP header which I can use which would ask me to authenticate )?
What is a workaround for connecting to the url which might need us to authenticate?
How can I specify to use a SSL certificate for getting response?
< script >
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "demo_post2.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");
} < /script>
I know it can be done but i am no good with http request at all. I have a very specific one i need to write. The code is here but i dont know which line to return to my app for the response.
var request = new XMLHttpRequest();
request.open('POST', 'https://v2.api.xapo.com/oauth2/token');
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.setRequestHeader('Authorization', 'Basic YTVlMGExMTViYTc1MThjYzphNWUwYTExNWJhNzUxOGNjYTVlMGExMTViYTc1MThjYw==');
request.onreadystatechange = function () {
if (this.readyState === 4) {
console.log('Status:', this.status);
console.log('Headers:', this.getAllResponseHeaders());
console.log('Body:', this.responseText);
}
};
var body = "grant_type=client_credentials&redirect_uri=https://myURI.com";
request.send(body);
This is what im trying to do.
curl --include --request POST --header "Content-Type: application/x-www-form-urlencoded" --header "Authorization: Basic MYKEYHERE[auth]" --data-binary "grant_type=client_credentials&redirect_uri=MYREDIRECTURI" 'https://v2.api.xapo.com/oauth2/token'
The api for this is here
please see the following code :
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
}
first you define an instance of XMLHttpRequest() that will do the http request for you
second the method xhttp.onreadystatechange = function()will be listening to state change that means it will be executed once an http responde is returned
third xhttp.open method will determine your connection config for example here we set a property "POST" then determining the link you want to post to it along with the variables you want to post like this :
enter the link
put ? mark
put the variable name
put =
put the varible value
put & mark and repeat the steps 3 4 5 if you want to post more variable else put nothing .
fourth the method xhttp.send()will start the http request to the server and once the response is gotten the xhttp.onreadystatechange = function()will be called then you can get the content of the response with xhttp.responseText
I hope this example is clear