Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top