Button for AJAX Get Request

I need assistance in connecting an AJAX script with a button to send a GET Request when clicked. Can someone help me figure out how to achieve this?

<script>
var url = "http://myurl.com";
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onreadystatechange = function () {
   if (xhr.readyState === 4) {
      console.log(xhr.status);
      console.log(xhr.responseText);
   }};

xhr.send();
</script>
<head>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<button>Click Here</button>

Answer №1

Make sure to encapsulate the code within a function that you can call with a button click:

<script>
    function makeRequest()
    {
        var url = "http://myurl.com";
        
        var xhr = new XMLHttpRequest();
        xhr.open("GET", url);
        
        xhr.onreadystatechange = function () {
           if (xhr.readyState === 4) {
              console.log(xhr.status);
              console.log(xhr.responseText);
           }};
        
        xhr.send();     
    }
</script>

<head>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<button onclick="makeRequest();">Send Request</button>

Answer №2

If you have already imported jQuery into your project, there is a convenient helper function available for making AJAX requests. You can utilize it in the following way:

<head>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<button>Click to Request Data</button>
<!-- JavaScript -->
<script>
$('button').click(function(){
    $.get("http://myurl.com", function(result) {
        console.log(result);
    });
});
</script>

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

Can VueJS Computed handle multiple filters at once?

I am encountering an issue with this code - when I attempt to add another filter inside the computed section, it doesn't work. However, if I remove the additional filter, the code functions correctly. My goal is to have both company and product searc ...

Updating a Nested Form to Modify an Object

There is an API that fetches an object with the following structure: { "objectAttributes": [ { "id": "1", "Name": "First", "Comment": "First" }, { "id": "2", "Name": "Second", "Comment": "Second" } ] ...

What are the steps to integrate <br> in a JavaScript code?

I have recently started learning about web development and I'm facing a challenge with this implementation. var obj = [[{ name: "John", age: 30, city: "New York"}, { name: "Ken", age: 35, city: "New Orleans"}]]; ...

When attempting to send data from Ajax to PHP as JSON, an error occurs and the data transmission fails

When attempting to send data as JSON, an error response is received stating: SyntaxError: Unexpected token < in JSON at position 0. If the data is sent as text, it successfully reaches PHP, but PHP does not respond accordingly. AJAX/JavaScript using J ...

How can I craft a customized lightbox with dynamically generated content?

I am currently developing a Twitter fetcher application and have encountered some issues with the scrolling functionality, particularly due to oversized images. I would like to implement image restrictions similar to what Twitter uses. https://i.sstatic.n ...

Issues encountered with the validation of dropdown lists are not functioning as

Below is the code for a dropdown list in PHP: <?php $dataCategory=ArrayHelper::map(Movies::find()->asArray()->all(), 'id', 'movie_name'); echo $form->field($model, 'movie_id')->dropDownList($dataCateg ...

It appears that using "object[prop]" as a name attribute does not function properly in HTML

After using console.log on the req.body I received this output: [Object: null prototype] { 'shoe[name]': 'Shoe Name', 'shoe[description]': '', 'shoe[pictures]': '', 'shoe[collections] ...

What are the steps to implement string interpolation within a template element in Vue.js?

Currently, I am looping through a dictionary that is imported from a .json file and I want to compare an attribute in my props with a value in the dictionary. The first div defines the attribute variable to be one of the values in the dictionary, specifica ...

The split function of a string displays an undefined result

My goal is to extract all characters that come after the equal sign within a URL: let url = this.$route.query.item console.log(typeof(url)) // outputs string let status = url => url.split('=')[1] When I run the code, it shows &apo ...

What is the best way to integrate my PHP regular expression into Node.js code?

I recently encountered an issue when trying to convert a regular expression from PHP to Node.js. The output I'm receiving in Node.js is different from what I expect, and I suspect it has to do with my implementation of PREG_SET_ORDER in Node.js. Here ...

Leveraging the power of ReactJS for efficiency in executing multiple API calls concurrently

I'm encountering an issue with the following code snippet: let tmpContributors = [...this.state.contributors]; for (let i = 0; i < 10; i++) {//10 most active contributors due to performance and github limits contributorPropertiesPromises.pus ...

I'm experiencing issues with my code involving HTML, CSS, and jQuery

Recently, I started learning about jQuery and came across a tutorial on creating a sticky nav bar. However, something went wrong during the implementation and now I don't know how to fix it! In my Script file, I have written code that should run on l ...

"Enhance your website forms with a Bootstrap typeahead feature for tagging using

I've encountered a roadblock while trying to transfer my functioning solution to my meteor app. The typeahead and tags input plugin work perfectly on my local PC, but when I migrate them to meteor.js, something breaks. I've made sure to include ...

What sets Legacy JavaScript apart from its modern counterpart, JavaScript?

Exploring the distinctions in coding practices between JavaScript and jQuery, I came across an interesting concept known as Legacy JavaScript that I was previously unaware of. You can read more about it at this link: Selecting Elements in Different Ways: ...

What is the method for entering text into a Code Mirror line using Selenium?

When I use IE to enter text into a CodeMirror-line text box, the text disappears when I try to save it. I have attempted using JavascriptExecutor to write to the CodeMirror, but it seems to only be for visual purposes. How can I input text into the code mi ...

`Trick Ajax into displaying 200 status code even on error responses`

Is it possible to suppress exceptions in the console by manually setting the status code to 200 for all errors? For example, can I change a 500 internal server error response to 200? Although I understand that hard-coding status codes is generally conside ...

AngularJS directive failing to execute

Check out this directive: app.directive('changeImage', function() { return { restrict: 'A', link: function(scope, element, attrs) { alert('here'); $(element).hover(function() { ...

JavaScript for beginners: show a specified amount of search results and insert a loading indicator at the end

Currently, I have a website that retrieves data from my database using a PHP query. However, the issue I am facing is that there are over 300 entries in my database, resulting in an excessively long displayed page. My main question: How can I restrict ...

Tips for passing multiple parameters to Web API controller methods in Angular 4

Want to learn how to use Spring Rest Api: @RequestMapping(value={"/save-userlist"}, method=RequestMethod.POST) public ResponseEntity<?> saveUserList(@RequestBody UserListDTO userListDTO, @RequestBody List<User> users, @RequestParam Integer ...

What are the steps to make ng-show functional in an AngularJS application?

I am attempting to implement a hover effect where an image is displayed over another image upon hovering over its container. I have been trying to achieve this using Angular and ng-show, but for some reason, the image with the ng-show attribute remains hid ...