Understanding of ajax complete call - javascript

I'm struggling with stabilizing Selenium automation for jQuery/AJAX application hence referred to
https://www.swtestacademy.com/selenium-wait-javascript-angular-ajax/
and it has ajaxComplete() method which has following code -
var callback = arguments[arguments.length - 1];
var xhr = new XMLHttpRequest();
xhr.open('GET', '/Ajax_call', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callback(xhr.responseText);
}
};
xhr.send();
);
I haven't work on JavaScript before and this code which I'm not able to understand completely. I've following questions with this, if someone can help to understand it -
What is Ajax_call in this? Is it generic call to check ajax completion? Or do I need to have my own endpoint there? If yes, does single end point enough or do I need to identify all calls and add them in the method?

Please check the documentation for XMLHttpRequest.open. If you do, you will the second argument listed is
url
A DOMString representing the URL to send the request to.
This means that it is simply the URL you want to request. I can be anything you want. The / prefix means that you are request relative to the root of the website (so if you are requesting from https://example.com/somedir/somepage the request will be made to https://example.com/Ajax_call.

Related

Redirecting XMLHTTP request - Javascript

I have a web page that has a too much content and javascript. When the page loads it makes multiple requests using Ajax and XMLHttp to load data. Is there a way to hook up all these requests and direct them to a different server.
For example the webpage fetches data from www.apple.com/data and www.mango.com/data after it is loaded. Is is possible to insert a script somewhere in the webpage which automatically changes any request made to www.orange.com/data.
Waiting for answer. Thanks
You can add a global handler to the ajaxSend event, the event will be triggered right before the ajax request being sent out. So you can check the request uri, apply some filtering logic, and then redirect the request by abort the original and resend it.
Below is an example
$(document).ajaxSend(function(e, xhr, opt) {
if (opt.url.indexOf("www.apple.com") !== -1) {
// abort the request
xhr.abort();
// change the uri to www.orange.com
opt.url = opt.url.replace("www.apple.com", "www.orange.com");
$.ajax(opt);
}
});
Ok. So I followed Anthony C's answer and it did actually work. But the problem with his solution is that it only works with Ajax requests not XMLHttpRequests (I am not sure why, I am a beginner at this topic.) However digging on his idea of creating a hook I came across a similar post here How to get the URL of a xmlhttp request (AJAX). The code provided a way to fetch the requested URL for each request. So by a little tweak to the code I managed to come up with this:-
XMLHttpRequest.prototype.open = (function(open) {
return function(method,url,async) {
var uri=getLocation(url);// use get location function to convert requested url string into readable url
if(uri.hostname!="orange.com"){
url="https://orange.com" + url;
}
open.apply(this,arguments);
};
})(XMLHttpRequest.prototype.open);
var getLocation = function(href) {
var l = document.createElement("a");
l.href = href;
return l;
};
This code at top of the page allows me to change the host name of all XMLHttpRequests that are not directed towards orange.com. Though I am sure there are better ways to write this code as well but since I am not an expert over javascript this will suffice my need for the time.

post http request to 3rd party server and get response with redirect

I have asp.net mvc project with form I need to send as httpRequestObject.
I'm trying for few days already to make simple XMLhttp request to 3rd party Credit card clearing company url and get back the response with redirect which on XML format - I don't care if redirection made by iframe or popup
checked all over the internet for solutions, tried it on JavaScript - but as far as I understood I'm not able to do it with JS, tried asp.net and c# also but nothing works for me.
checked all solutions here but still nothing work.
checked if I'm blocked in any way like proxy or firewall, and it's not the issue.
My current JS code is -
function createMPITransaction() {
var terminal_id = "0962832";
var merchant_id = "938";
var user = "my-user";
var password = "my-password";
var url="https://cguat2.creditguard.co.il/xpo/Relay";
var xmlStr = "my string";
var http = new XMLHttpRequest();
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('Access-Control-Allow-Headers', '*');
http.setRequestHeader('withCredentials', true);
http.setRequestHeader('responseType', 'text');
var response = http.responseText;
http.onreadystatechange = function () {//Call a function when the state changes.
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
console.log(xmlStr);
console.log(http);
http.send(xmlStr);
and getting this from console -
XMLHttpRequest {readyState: 1, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, responseURL: ""…}
Am I be able to do it on JS?
If not, how could I do it on asp.net c#?
the limitation of request to 3rd party server, and get redirection is not common and make it real challenge.
As far as just the code for redirection is concerned, you can look at similar answer, like for example: https://stackoverflow.com/a/3836811/6298965
What you may be still missing is to check if your request is specification compliant or you're actually getting an error so you're not redirected.
After an initial analysis, I guess that a jsonxml is likely needed for the api call.
Moreover it'd be better if you use or at least look at a github implementation: https://github.com/mderazon/creditguard-node/blob/master/lib/creditguard.js

Using JavaScript Ajax to retrieve content from another site

I'm currently experimenting with replacing a number of function I currently use jQuery for with a Vanilla Javascript alternative. This is to:
Increase my understanding of JavaScript as a whole
Make me a better front-end developer (ties into the above)
Improve the speed and responsiveness of my web applications by negating the need for a library such as jQuery for simple tasks.
My aim today is to produce a JavaScript function that allows me to make an Ajax call to another site to retrieve a specific Div and use the content from that Div within my page. I can do this pretty easily with jQuery by filtering the response from an Ajax call with the .find() method to retrieve the specific Div I require then use the .html() function to strip the content and append it to the Div on my site. However, I cannot see an alternative method of doing this using Vanilla JavaScript.
My code so far can be found below:
function fireAjaxRequest(requestType,requestUrl,contentPlaceholder){
var ajaxRequest;
if(window.XMLHttpRequest){
ajaxRequest = new XMLHttpRequest();
}else{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
contentPlaceholder.innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open(requestType,requestUrl, true);
ajaxRequest.send();
}
I call my function as follows:
var contentArea = document.getElementById('news');
fireAjaxRequest('GET', 'http://www.bbc.co.uk',contentArea);
When I load my page, I can see in Firebug that the request completes successfully and I get
a 200 Success response from the Ajax call however, nothing is displayed in my target element. At first I thought this was because you cannot store a whole page within a single element but after altering my code slightly I found the the following snippet of code does not seem to be executed upon the success of the Ajax call:
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
contentPlaceholder.innerHTML = ajaxRequest.responseText;
}
}
Am I doing something incorrectly here?
You really need to look into XSS. I think you'll understand why there are serious restrictions with what you're trying to do.
If you control both domains, you can use JSONP or CORS.
You could also write send an ajax request to your own server that acts as a proxy. Your server would "forward" the request to the destination server, and relay the response to the client.

Append something always to an XHR Request

I want to attach a JS Variable to every XHR request that will be issued from my single page web application.
What would be the best approach to achieve this? I don't want to establish special methods for sending with this attributes, as there may be third parties integrating with my application.
I thought about overriding the send method on the XHR Object but thats not considered good style either.
I can't use cookies due to requests being cross-domain.
Any better idea or approach to this?
Thank you!
-Alessandro
if you really want to extend the existing functionalities without adding any library-like function, you could solve this using monkey patching:
(function() {
var originalOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
var getParameter = 'foo=bar';
if(url.indexOf('?') === -1) {
url = url + '?' + getParameter;
} else {
url = url + '&' + getParameter;
}
console.log('you just got monkey-patched! url is now:', url);
originalOpen.call(this, method, url, async, user, password);
}
})();
var request = new XMLHttpRequest();
request.open('get', 'http://google.com');
see also this jsfiddle for a working example.
you can use the same technique when injecting stuff into the body of a request if you patch the send() function.
if you do, ensure you take care for the type of the data to be transmitted (see MDN). it doesn't make sense to append a parameter to a binary body ;)

Simplest way to write this AJAX call

I need to send an ajax request to a webserver "http://examples.com/ajax" the response will be the html of a <div> and it will be inserted to an existing <div id="holder">. What's the simplest, smallest way to write this in javascript? without using jQuery?
It only needs to support the latest version of chrome.
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
//Is request finished? Does the requested page exist?
if(req.readyState==4 && req.status==200) {
//Your HTML arrives here
alert(req.responseText);
}
}
req.open("GET","http://examples.com/ajax.php",true) //true indicates ASYNCHRONOUS
req.send(null);
This solution uses get, so you've got to add variables using ? and & to your URL (e.g. http://examples.com/ajax.php?foo=bar&blah=blee.
If you want to do it using post, run a few with get and then this article is useful.

Categories

Resources