JavaScript: How to get http response as a result of click - javascript

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

Related

AJAX request to python does not return back to java script without using JQuery

I am sending an XMLHTTPrequest to a flask location like so...
var ourRequest = new XMLHttpRequest();
ourRequest.open("GET", "makeDiff")
diff = ourRequest.send();
console.log(diff);
The request then executes this Python code using Flask...
#app.route('/makeDiff')
def makeDiff():
diffNew = {"THIS IS A TEST": "HELLO", "TEST2": "HOLA"}
return json.dumps(diffNew)
However, after the python executes, the variable diff in the javascript is alway undefined. I don't know how to actually send the dictionary back to the javascript. There are many examples on how to do this with JQuery, but is it possible to do this with only javascript and no JQuery.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
xhr.open('GET', 'http://example.com/makeDiff', true);
xhr.send(null);
onreadystatechange callback is called when response arrive from python.

Javascript serialized POST

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&param2=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)

How to send JSON response from python server to the javascript using ajax call

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 !

How to send XMLHttpRequest Put call (error: too many redirects)

I can make GET calls fine, but I don't know how to make PUT requests. The error I'm getting is "Failed to load resource: too many HTTP redirects"
Code:
var url = "https://{{shop.domain}}/cart.js";
var xhrPut = new XMLHttpRequest();
xhrPut.open("PUT", url, true);
xhrPut.setRequestHeader("Content-Type", "application/json");
xhrPut.send("{\"total_price\":50}");
The JSON that I'm trying to change is this:
{"token":"a97c89f7e2c7c22becab8cfef40fa272","note":null,"attributes":{},"original_total_price":100,"total_price":100,"total_discount":0,"total_weight":0,"item_count":1,"items":[{"id":19673785606,"properties":null,"quantity":1,"variant_id":19673785606,"key":"19673785606:59d774c1f413525441dcb716e0c982e2","title":"Short Sleeve Shirt","price":100,"line_price":100,"original_line_price":100,"total_discount":0,"discounts":[],"sku":"","grams":0,"vendor":"Dev Store","product_id":6213990086,"gift_card":false,"url":"\/products\/short-sleeve-shirt?variant=19673785606","image":"https:\/\/cdn.shopify.com\/s\/files\/1\/1278\/7069\/products\/happyman.jpg?v=1462811058","handle":"short-sleeve-shirt","requires_shipping":true,"product_type":"","product_title":"Short Sleeve Shirt","product_description":"description","variant_title":null,"variant_options":["Default Title"]}],"requires_shipping":true}
The total_price variable is currently 100, I'm trying to set it to 50.
Editing this so I may get answers
I changed the code to the following and then get error 400: bad request
var url = "https://{{shop.domain}}/cart.json";
var xhrPut = new XMLHttpRequest();
xhrPut.open("PUT", url, false);
xhrPut.setRequestHeader("Content-Type", "application/json");
xhrPut.send('{"token":"a97c89f7e2c7c22becab8cfef40fa272","note":null,"attributes":{},"original_total_price":100,"total_price":50,"total_discount":0,"total_weight":0,"item_count":1,"items":[{"id":19673785606,"properties":null,"quantity":1,"variant_id":19673785606,"key":"19673785606:59d774c1f413525441dcb716e0c982e2","title":"Short Sleeve Shirt","price":100,"line_price":100,"original_line_price":100,"total_discount":0,"discounts":[],"sku":"","grams":0,"vendor":"Dev Store","product_id":6213990086,"gift_card":false,"url":"\\/products\\/short-sleeve-shirt?variant=19673785606","image":"https:\\/\\/cdn.shopify.com\\/s\\/files\\/1\\/1278\\/7069\\/products\\/happyman.jpg?v=1462811058","handle":"short-sleeve-shirt","requires_shipping":true,"product_type":"","product_title":"Short Sleeve Shirt","product_description":"description","variant_title":null,"variant_options":["Default Title"]}],"requires_shipping":true}"');
From my knowledge of how the PUT request works, this should overwrite the entire document, but the only changes made were:
The variable total_cost was reduced from 100 to 50
The escape character '\' was used before the characters '\' in the variable 'url' in the array 'item'
Here is a GET request that I am sending before this PUT request, which returns no errors and writes the expected values to console. Note that the errors with the PUT request occur whether this is run or commented out.
var totalCost;
var url = "https://{{shop.domain}}/cart.json";
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var resp = xhr.responseText;
console.log(resp);
var json = JSON.parse(resp);
console.log(json);
totalCost = json.total_price;
console.log(totalCost);
}
};
xhr.open("GET", url, false);
xhr.send();
console.log(totalCost);
The only reason this is synchronous is so that I can log the totalCost after the API call.

How do I force or add the content length for ajax type POST requests in Firefox?

I'm trying to POST a http request using ajax, but getting a response from the apache server using modsec_audit that: "POST request must have a Content-Length header." I do not want to disable this in modsec_audit.
This occurs only in firefox, and not IE. Further, I switched to using a POST rather than a GET to keep IE from caching my results.
This is a simplified version of the code I'm using for the request, I'm not using any javascript framework.
function getMyStuff(){
var SearchString = '';
/* build search string */
...
/* now do request */
var xhr = createXMLHttpRequest();
var RequestString = 'someserverscript.cfm' + SearchString;
xhr.open("POST", RequestString, true);
xhr.onreadystatechange = function(){
processResponse(xhr);
}
xhr.send(null);
}
function processResponse(xhr){
var serverResponse = xhr.responseText;
var container = document.getElementById('myResultsContainer');
if (xhr.readyState == 4){
container.innerHTML = serverResponse;
}
}
function createXMLHttpRequest(){
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
try { return new XMLHttpRequest(); } catch(e) {}
return null;
}
How do I force or add the content length for ajax type POST requests in Firefox?
xhr.setRequestHeader("Content-Length", "0");
would be my best guess.
BTW, if you want to stop caching in IE, just add a random number onto the end, as in:
var RequestString = 'someserverscript.cfm' + SearchString + '&random=' + Math.random();
Try to actually send something instead of null (xhr.send(null);).

Categories

Resources