I am trying to achieve that when I call the JS function, a post request is send. In my browser I would send:
http://myuser:password#hc2:80/api/callAction?deviceID=185&name=turnOn
This works. Yet in my code it doesn't.
Important to note:
- Chrome does raise an Error: Request doesn't pass access control. If I disable this in Chrome, I doesn't display this error (yet no response from the server either).
<script type="text/javascript">
function changestate() {
var http = new XMLHttpRequest();
http.withCredentials = true;
var user = "bassie"
var pass = "password"
var url = "http://hc2/api/callAction";
var params = "deviceID=185&name=turnOff";
http.open("POST", url, true);
http.setRequestHeader("Authorization", "Basic " + user + ":" + pass);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
alert(http.responseText);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
}
</script>
The equivalent to putting the URL in the browser's location is a GET request, not POST.
Since you're sending a cross-domain request, you won't be able to read the response (unless you relay through a proxy on your origin server). So you can't read http.responseText, and can simply omit the onreadystatechange function; you'll just have to assume it
function changestate() {
var http = new XMLHttpRequest();
http.withCredentials = true;
var user = "bassie"
var pass = "password"
var url = "http://hc2/api/callAction";
var params = "deviceID=185&name=turnOff";
http.open("GET", url + "?" + params, true);
http.setRequestHeader("Authorization", "Basic " + user + ":" + pass);
http.send();
}
Eventually ended up creating a sort of like proxy. This was the main component. Not in the example (My script gets the HTTP requested) and gets the output. Below the gist of it:
req = urllib.request.Request('http://hc2:80/api/callAction?param1=1¶m2=2')
credentials = ('%s:%s' % ('user', 'password'))
encoded_credentials = base64.b64encode(credentials.encode('ascii'))
req.add_header('Authorization', 'Basic %s' %
encoded_credentials.decode("ascii"))
response = urllib.request.urlopen(req)
Related
I am using the csurf module in expressjs. It works for all post requests as I use it the following way.
app.use(csrf());
res.locals.csrfToken = req.csrfToken();
This way its automatically available in all forms where I have the following.
<input type="hidden" name="_csrf" value="<%=csrfToken%>">
but how do I set the csrftoken on AJAX requests, I am not using jquery, below is the JS function to send AJAX request. I do have the csrf token available on the html as a hidden value that I have access via getElementByID.
note: I am able to send the request if I disable csrf.
function voteQuestion () {
var qid = document.getElementById("qid").value;
var csrf = document.getElementById("csrf").value;
var http = new XMLHttpRequest();
var url = "/q/ajaxcall";
var params = "qid="+ qid;
http.open("POST", url);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == XMLHttpRequest.DONE && http.status == 200) {
var json = (http.responseText);
var obj = JSON.parse(json);
document.getElementById("vote-sp").innerHTML = (obj.upvotes);
}
};
http.send(params);
}
I have been trying to figure this out for almost a week now, and just decided to console.log req.session and found cookies contains "XSRF-TOKEN" value, so in the AJAX request header I set XSRF-TOKEN to csrf and now it works, I dont know why it works this way particularly for AJAX requests.
setRequestHeader("XSRF-TOKEN", csrf);
Set crsf token in your params as below..
var params = "qid="+ qid + "&crsf="+csrf;
OR
You can create a new object for sending data as below..
var data = {}; //crates new object
data.qid = qis; //adds qid to object
data.csrf = csrf; //adds qid to object
params = data; // to server
I'm trying to get response of GET request, that starts after document.getElementById('btnPdf').click();
I'm using Selenium Webdriver as JavaScriptExecutor.
My question is similar to this How do I capture response of form.submit but I don't know exact url and would prefer to use pure JS without AJAX (if it's possible).
function get
Response() {
var send1='senddata'; // this is a var to send
var send2='senddata2'; // this is another var to send
var xhr = new XMLHttpRequest();
xhr.open('POST', 'myGetPageName',true);
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.onload = function() {
if (xhr.status === 200) {
var myResponse = xhr.responseText;
alert(myResponse);
}
};
xhr.send('myvar1=' + send1 + '&myvar2=' + send2)
}
elif self.path == "/recQuery":
r = requests.get('http://example.com') # This returns some json from a request to another server.
print r.json()
self.wfile.write(r.json())
.
var http = new XMLHttpRequest();
var url = SERVER + "/recQuery";
var params = JSON.stringify({
query: search_query
});
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
console.log(http.responseText);
How can i send data from python server to javascript using ajax call. The one i am using does not return anything in the console. Can you please tell me what i am doing wrong here. I need send the response of what i get from requests.get method to the ajax call. The json should be returned to the ajax call in response. Problem is with the self.wfile.write method, When i use this i dont get anything on javascript side.
var http = new XMLHttpRequest();
var url = SERVER + "/recQuery";
var params = JSON.stringify({
query: search_query
});
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
console.log(http.responseText);
}
};
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
I was not fetching the response onreadystatechange. So this works for me. Thanks !
I started with this post some time ago, unfortunately it didn't work. I decided to look in the console, an found out that it was not sending the requests' headers as they were unsafe. So I decided to comment them out for now.
However there is one more problem: "http is not defined". How do I solve that?
// will use this to turn an object into a url encoded string
var serializeObject = function(obj) {
var output = '';
for(var attr in obj) {
if(obj.hasOwnProperty(attr)) {
output += attr + '=' + obj + '&';
}
}
return output.slice(0, -1);
};
var url = 'http://spacej.ru/sample/getMcoordinates.php';
// you need to serialize your data into key value pairs like the following
var exampleCoords = {
x: 31,
y: 74,
z: 28
};
// postData will be x=10&y=20&z=30
var postData = serializeObject(exampleCoords);
var request = new XMLHttpRequest();
request.open('POST', url, true);
/*
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", postData.length);
request.setRequestHeader("Connection", "close");
*/
// this function gets called when the request changes
// mistake pops up here !
http.onreadystatechange = function() {
// request was successful
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(postData);
Try renaming the http variable to request. The http variable does not appear to be declared anywhere in your code.
I cannot figure out how to get the following code working in my little demo ASP.NET application, and am hoping someone here can help.
Here is the javascript:
function checkUserName() {
var request = createRequest();
if (request == null) {
alert("Unable to create request.");
} else {
var theName = document.getElementById("username").value;
var userName = escape(theName);
var url = "Default.aspx/CheckName";
request.onreadystatechange = createStateChangeCallback(request);
request.open("GET", url, true);
request.setRequestHeader("Content-Type", "application/json");
//none of my attempts to set the 'values' parameter work
var values = //JSON.stringify({userName:"userName"}); //"{userName:'temp name'}"; //JSON.stringify({ "userName":userName });
request.send(values);
}
}
Here is the method in my *.aspx.cs class:
[WebMethod]
[ScriptMethod(UseHttpGet=true)]
public static string CheckName(string userName)
{
string s = "userName";
return s + " modified backstage";
}
When this code runs I receive this exception:
---------------------------
Message from webpage
---------------------------
{"Message":"Invalid web service call, missing value for parameter: \u0027userName\u0027.","StackTrace":" at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)\r\n at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)\r\n at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}
---------------------------
OK
---------------------------
I started searching here, then went on to several threads on SO, trying quite a few combinations of quotation marks and key-value pairs, but nothing I've tried has worked.
When I remove the parameter from the C# method and request.send(), I get a response in my JS callback that I can work with. But as soon as I try to do something with parameters, I get the above exception. I'd like to know how to do this without using jQuery, if possible.
Thanks in advance.
FINAL VERSION
Using Alexei's advice, I ended up with the following, which works. The URL was missing the apostrophes on either end of the parameter value; this was keeping the call from going through.
function checkUserName() {
var request = createRequest();
if (request == null) {
alert("Unable to create request.");
} else {
var theName = document.getElementById("username").value;
var userName = encodeURIComponent(theName);
var url = "Default.aspx/CheckName?name='" + theName + "'";
request.onreadystatechange = createStateChangeCallback(request);
request.open("GET", url, true);
request.setRequestHeader("Content-Type", "application/json");
request.send();
}
}
request.send(values);
This won't work with a "GET". Try
request.open("POST", url, true);
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
You need to:
decide whether you want GET or POST. For GET request you need all parameters to be in Url (and body to be empty), for POST you can use both. As of current code you are expecting GET, but sending POST.
properly add query parameter - name and encoded value. encodeUriComponent is JavaScript function of choice, see Build URL from Form Fields with Javascript or jquery for details
if using POST you need to properly encode parameters there too as well specify correct "content-type" header.
if sending JSON you need to decode JSON server side.
Alternatively you can use hidden form to perform POST/GET as covered in JavaScript post request like a form submit
Side note: jQuery.ajax does most of that for you and good source to look through if you want to do all yourself.
Like Alan said, use the POST method. Or pass your arguments in your URL before opening it, e.g.
var url = "Default.aspx/CheckName?userName=" + values;
EDIT : no, it's probably a bad idea since you want to send JSON, forget what I said.
If you need to go for POST, then you need to send it like this.
var values = JSON.stringify({"'userName':'"+ userName+ "'"});
And you have to change HttpGet to HttpPost
Given that your server side method asks for GET, you need:
request.open("GET", url + "?username=" + userName, true);
request.send();
The works for me:
function checkUserName() {
var request = new XMLHttpRequest();
if (request == null) {
alert("Unable to create request.");
} else {
var userName = "Shaun Luttin";
var url = '#Url.RouteUrl(new{ action="CheckName", controller="Home"})';
request.onreadystatechange = function() {
if (request.readyState == XMLHttpRequest.DONE ) {
if(request.status == 200){
document.getElementById("myDiv").innerHTML = request.responseText;
}
else if(request.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned')
}
}
}
request.open("GET", url + "?username=" + userName, true);
request.send();
}
}
With this on the server side:
[HttpGet]
public string CheckName(string userName)
{
return userName + " modified backstage";
}