Using JavaScript Ajax to retrieve content from another site - javascript

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.

Related

How To Get an HTML element from another HTML document and display in current document?

I'm building a web site which lets users post requests on site and others to respond. I have built an app-like form to collect information. In that form I need to display 3 pages.
So I have created one page with the from and and a JavaScript file to handle these 3 pages. Other form-pages are designed separately (HTML only).
I'm planning to load the other two pages into that 1st page with XMLHttpRequest and it works.
But I need to take 3rd page into the 1st form-page (display the 3rd page of form) and change the innerHTML of that 3rd page. I tried it with
function setFinalDetails() {
document.getElementById("topic").innerHTML = object1.start;
}
//creating a XMLHttpObject and sending a request
//requiredPage is the page we request.
//elementId is the element we need to display
function requestAPage(requiredPage) {
selectElementId(requiredPage);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
m = xhttp.responseXML;
y = m.getElementById(elementId).innerHTML;
document.getElementById("hireForm").innerHTML = y;
//m is a global variable
//m is the object recieved from XMLHttpRequest.
//it is used to change the innerHTML of itself(m) and display.
//y is displaying the 3rd page in the form-page one("id =hireForm")
return m;
}
};
xhttp.open("GET", requiredPage, true);
xhttp.responseType = "document";
xhttp.send();
}
but that gives an error:
Cannot set a .innerHTML property of null
find my work on https://github.com/infinitecodem/Taxi-app-form.git
It it hard to help you in detail because we do not have a way to reproduce your error and test your code. I can suggest you to use a service like plunker to share your code. I do not know if this service will support to do some xhrRequest on other files in its working tree, you can try.
Your error message seems to reveal that one of your document.getElementById(...) is returning null instead of the html elt you want (so the id do not exist in the page).
But again without a way to test, it is hard to help you more sry. I really encourage you to try to share a link to a service (like plunker, etc) that will help others to play with your use case.

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

Function execute after Ajax request is complete (pure JavaScript)

In my application I use MVC model and Views are built with JavaScript DOM API.
On each page I have to check user's information to find out if session is active and if user's role gives him ability to access that page.
To make this happen, on each page I have "onload" function that triggers "sessionCheck" function which sends AJAX request to controller and returns information with which application makes decisions.
As I said JavaScript is also used to build Views, which means that after "sessionCheck" function I also have "headerView", "sectionView" and other functions that build the structure of page.
So the problem is that, before "sessionCheck" is finished other functions are loaded and nearly for 1-2 seconds users have ability to see what happens on that page and only after that they are transported out of that page by application if that is needed.
I read that there are some solutions in JQuery where "ajax.Complete" functions are available, but I couldn't same solutions in pure JavaScript. Can someone help me to solve this problem ?
This is HTML
<body onload="sessionCheckAdmin(); adminHeaderView(); adminUser(); modalView();">
sessionCheckAdmin functions looks like this
function sessionCheckAdmin()
{
var formData = new FormData();
formData.append("Code", "3");
formData.append("Sequence", "27");
formData.append("TaskId", "All");
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
var array = JSON.parse(xmlHttp.responseText);
if(array["userRole"] != "Administrator")
window.location.href = "task.php";
}
}
xmlHttp.open("POST", "../Controller.php");
xmlHttp.send(formData);
}
Part of PHP controller
case 27:
$array = json_encode($_SESSION);
echo $array;
break;

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