Utilizing XMLHttpRequest to retrieve text from an external webpage

I am currently learning JavaScript to develop web applications. Recently, I completed a hangman game using an array of words to select a random word for the game. Now, my next goal is to utilize XMLHttpRequest to fetch a random word from another website. Does anyone know of a tutorial or have information on how to get started with this? Thank you in advance!

<script type="text/javascript">
    var myWords = new Array("first", "hello", "goodbye", "random", "word", "last");
    var item = myWords[Math.floor(Math.random() * myWords.length)];
    var length = item.length;
    var guessedLetters = "";
    var error = 0;

    function partialWords(item, letters) {
        var returnLetter = "";
        for (i = 0; i < item.length; i++) {
            if (letters.indexOf(item[i]) !== -1) {
                returnLetter = returnLetter + item[i];
            } else {
                returnLetter = returnLetter + '_';
            }
        }
        return returnLetter;
    }

    function load() {
        var input = document.getElementById("hangmanID").value;
        var myWords2 = (item.indexOf(input) >= 0);

        if (myWords2 === false) {
            console.log("That letter is not in the word");
            document.getElementById("hangmanID").value = "";
            document.getElementById("error").innerHTML = "That letter was wrong!";
            document.getElementById("success").innerHTML = "";
            error++;

            if (error > 0) {
                document.getElementById('hangmanImg').innerHTML = "<img src='assets/" + error + ".png'>";
            } else {
                document.getElementById('hangmanImg').innerHTML = "No Errors yet!";
            }
        } else {
            console.log("That letter is correct");
            var string = item.indexOf(input, 0);
            console.log(string);
            document.getElementById("hangmanID").value = "";
            document.getElementById("success").innerHTML = "That letter was right!";
            document.getElementById("error").innerHTML = "";
        }
            guessedLetters = guessedLetters + input;
            document.getElementById('hangman').innerHTML = partialWords(item, guessedLetters);
            document.getElementById("lettersUsed").innerHTML = guessedLetters;
    }
</script>

UPDATE: PLEASE NOTE THAT I AM ALLOWED TO USE JSONP

Answer №1

When it comes to fetching data from other domains, the same-origin policy restricts XMLHttpRequest. However, there are ways to work around this limitation, such as using CORS, setting up a proxy on your domain, or utilizing embedded flash or java applets.

JSONP offers a different approach. Unlike XMLHttpRequest, JSONP does not directly return data but instead returns a javascript file. To fetch data using JSONP, all you need to do is add a script tag to your page like so:

<script src="http://other.server.com/path/to/jsonp/data"></script>

If you want to do this programmatically, you can create a script element with the specified source:

var jsonp = document.createElement('script');
jsonp.src = "http://other.server.com/path/to/jsonp/data";
document.body.appendChild(jsonp);

The challenge with script tags is that they do not return any value. To overcome this, the JSONP protocol sends a function name to the server, prompting the server to wrap that function around the JSON data.

For instance, if your regular JSON data looks like this:

{"result":"something"}

The JSONP equivalent would be formatted like this:

callback({"result":"something"})

To apply this concept in practice, let's modify the original code snippet:

function processResult (obj) {
    console.log(obj);
}
var jsonp = document.createElement('script');
jsonp.src = "http://other.server.com/path/to/jsonp/data?jsonp=processResult";
document.body.appendChild(jsonp);

In this updated code, we're passing the designated function name for handling the returned value as a query parameter in the URL.

Keep in mind that while this example uses "jsonp" as the parameter, servers may use alternative names like "callback", such as callback=processResult. Always refer to the API documentation provided by the server you're interacting with.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a maximum size restriction for submitting forms using jQuery's AJAX method?

I am searching for a way to submit a form without having to load a new PHP page. The form I need to submit contains both file upload and textarea fields, which means it may contain large data that needs to be submitted. While looking through various tutor ...

The size of the popup does not align properly with the content within it

After creating an extension for Chrome, I specified the dimensions of the popup to be 600 x 300 px. Everything was working perfectly until Chrome updated to version 27. As shown in the screenshot, I set the width and height using CSS, but there is still a ...

Unable to retrieve the data from the ajax response container

After a successful ajax response, the following code is executed: success : function(response) { $('#texto').append(response); } Here is the HTML response that is appended: <body> {% load custom_filters %} {% for ...

Using ng-repeat to display table data in AngularJS

There is an array with 7 elements, each containing an object. The goal is to display these elements in a table with one row and 7 columns. The desired output should look like this: some label1 | some label2 | some label3 | some label4 | some label5 som ...

I am eager to display this JSON data using AngularJS tables

I have JSON file with content about categories, departments, and digital marketing: { "categories":[ { "dept_id":"123", "category_name":"database", "category_discription":"list of database", "current time ...

Navigating to the home page when a user is logged in using react-router-dom v6 in ReactJS

I am trying to restrict access to certain routes based on whether the user is logged in or not. If a logged-in user tries to go to /login, I want to redirect them to the home page; otherwise, they should be redirected to the login page. Currently, I am wo ...

Utilizing AJAX to Access JSON Arrays

After clicking a button, I want to append specific parts of a JSON array (received from a server) to a table. However, I'm facing an issue where I am unable to add these parts to the table. Here is the JSON Array that was received from the server: {& ...

When implementing fancybox within bxslider, numerous thumbnails are shown simultaneously

My issue arises when using fancybox within bxslider. Once I open an image, multiple thumbnails start repeating themselves endlessly. This problem only started occurring after adding bxslider. Any thoughts on why this might be happening? ...

Is there a way to add a fade-in and slide-in effect to this dropdown JavaScript, as well as a fade-out and

Although I lack the necessary knowledge of Javascript, I am aware that my request may be a bit much. The code I currently have is directly from the w3school dropdown-list demo. Would it be possible for you to help me implement a fade in and slide in effect ...

Error Message: The function "menu" is not a valid function

I've encountered an issue with a function not being called properly. The error message states "TypeError: menu is not a function." I attempted to troubleshoot by moving the function before the HTML that calls it, but unfortunately, this did not resolv ...

What is the best way to implement ES2023 functionalities in TypeScript?

I'm facing an issue while trying to utilize the ES2023 toReversed() method in TypeScript within my Next.js project. When building, I encounter the following error: Type error: Property 'toReversed' does not exist on type 'Job[]'. ...

Update a specific division

Looking for suggestions on how to automatically refresh a div? I'm currently developing a chess game and I need the div to reload every time one player updates data in the database. The game is almost complete, but there's an issue where Player ...

Tips on resolving the Cross-Origin Read Blocking (CORB) error when blocked cross-origin response while using Postman

After making a call to a third party API using Jquery's AJAX function, the console is showing the following error: The Cross-Origin Read Blocking (CORB) protocol has blocked a cross-origin response from https://example.com/assets/front/font/fonts.m ...

The main server is not yielding any results from the MongoDB query

I attempted to utilize promises in order to retrieve all the items from my mongoDB database. Here is the code I used: exports.findAll = function(){ return new Promise(function(resolve, reject){ Collection.find({}, function(err, res){ if(err ...

Hide the button with jQuery if the variable is empty

As I delve into the world of learning javascript/jQuery on my own, I encountered a bit of difficulty. To tackle this challenge, I created an internal logo repository for easy access to all the logos required by the company. The issue arises from having a ...

How to stop IE from caching ajax-jquery loaded external files

I am currently using a jQuery script to retrieve data from an external file. Everything seems to be working fine except for Internet Explorer, which has its own way of doing things. The external file I am loading with this script (weather.php) contains rea ...

Choose an item from an unsorted list - warning "elementIdAttribute is not a valid function"

I am facing difficulties in accessing a value from a dropdown menu. The dropdown menu is generated using Bootstrap's dropdown.js. In order to tackle this issue, I have created a custom command in "Nightwatch" with two input parameters: the locator of ...

Is there a way to retrieve a large number of users through an API using async await?

I am trying to retrieve all users from an API and I want to identify which user receives the highest payment. For instance let users=['tom','jenny','smith','Joe'] async function getUsers() { let response = awa ...

When a form contains a ViewChild element, changes to the ViewChild element do not automatically mark the

Let's set the stage: MainComponent.html <form #someForm > <input type="text" name="title" [(ngModel)]="mainVar" /> <child-component /> <input type="submit" [disabled]="someForm.form.pristine" /> </form> ChildComp ...

Angular dependency injection function

What is the best placement for the common handleError and handleSuccess functions? These functions are commonly used by every service. Where should these functions be placed? Should they be global functions injected as dependencies? (function () { "u ...