Use JavaScript to send GET parameters to the server without needing to refresh the page

My goal is to execute a GET request in JavaScript when a download link is clicked. Upon clicking the link, a GET request should be sent to a PHP script that tracks the number of times the link is clicked. Although I'm relatively new to JavaScript, I have some experience with it. I have confirmed that my getUrlVars() function and the function for when a link is clicked are functioning properly, so the issue seems to be with my GET request implementation.

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
        vars[key] = value;
    });
    return vars;
}
// Wait for page to load
window.onload = function() {
    var a = document.getElementById("downloadLink");
    var app = getUrlVars()["app"];

    a.onclick = function() {    
        var xmlhttp;
        if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else { // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.open("GET", "download_count.php?app=" + app, true);
        xmlhttp.send();
        return true;
    }
}

Answer №1

I finally managed to make it work by adding a return false statement, and then instructing my PHP script to handle the file download. It seems that the jQuery GET value was not being sent because of the file download process.

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

Utilizing the same uuid twice along with Vuex and the unique identifier generation tool uuidv4

Within my vuex store, there is a function to create a post. This function generates a json Object containing a unique uuid using uuidv4(). However, I have noticed that if I execute the function multiple times, the uuid remains the same each time (unless I ...

Is it preferable to include in the global scope or the local scope?

When it comes to requiring a node module, what is the best approach? Should one declare the module in the global scope for accuracy and clarity, or does declaring it in the local scope make more sense? Consider the following examples: Global: let dns = r ...

The system was unable to locate node.js with socket.io

I'm having trouble locating the file. According to the documentation I reviewed, socket.io is supposed to be automatically exposed. Encountered Error: polling-xhr.js?bd56:264 GET http://localhost:8081/socket.io/?EIO=3&transport=polling&t=LyY ...

The functionality of minified JS code is limited to being copied and pasted directly into the

Trying to explain the issue I'm facing may be a bit tricky, but here it goes: I've been working on an AngularJS app (not live yet) and we felt the need to add tooltips for specific metrics in our tables. After some research, we really liked the ...

The server was unable to start because NPM was unable to navigate to the wrong directory and locate the package.json file

I recently used vue create to start a project and everything went smoothly. However, when I tried to run npm run serve, I encountered an issue where node couldn't locate the package.json file that was generated during the project creation process. Th ...

Is there a way to adjust the size of the canvas element in HTML without compromising quality or resorting to zooming?

I'm currently working on a basic modeling application for the web. The main component of my app is a canvas element that I'm trying to size correctly. However, when I set the height and width using CSS, it scales the entire canvas and compromises ...

Obtaining the value of a checkbox with React

I have a form with two input fields (email, password) and a checkbox. The code for the form is shown below: <Box component="form" onSubmit={handleSubmit} noValidate sx={{ mt: 1 }}> <TextField margin="normal" required ...

Having difficulty accessing node_modules directory in JavaScript

I am confused about how to access node_modules for JavaScript. Can someone provide an example of calling module.exports from a node_module folder after installing a package with NPM in Node.js? File tree structure: There is a folder named 'ethereum&a ...

Is it possible to show more than five buttons in an Amazon Lex-v2 response display?

Here is the sessionState object I am working with: { "sessionAttributes": {}, "dialogAction": { "type": "ElicitSlot", "slotToElicit": "flowName" }, "intent": { "name": &q ...

What is the process for retrieving the AJAX response text?

When it comes to my AJAX development, I rely on prototype and utilize the following code: somefunction: function(){ var result = ""; myAjax = new Ajax.Request(postUrl, { method: 'post', postBody: postData, content ...

Error in Allowing Access-Control-Origin

The script I'm using is as follows: <!DOCTYPE html> <html> <head> <script src="jquery-1.9.1.min.js"></script> <script> function postForm() { $.ajax({ type: 'POST', url: &apos ...

Troubleshooting a timing loop problem with jQuery Ajax and setInterval when using flipCounter's onAnimationStopped feature

In the code below, I am retrieving some data to use for a counter. The problem is that after the initial page load and one interval, things start to go haywire. The calls are made without any delay and the counter cannot react before the next call is made. ...

Retrieve the date information from the <td> element, if it exists

There are numerous rows in the table. The table cell labeled "dates" may contain either a specific date or the word "Permanent". If there is a date present and it happens to be greater than today's date, it needs to be highlighted in red. I attempted ...

Tips for integrating Google WebKit with AngularJS

Looking to enhance my application with Google WebKit functionality. My goal is to create a feature similar to Gmail's where hovering over the "+" symbol expands to display options such as "insert photos" and "insert links". I'm just starting out ...

The positioning of the menu icons varies

When it comes to displaying the search icon in the WordPress toggle bar, I use a custom JavaScript file. This setup is mainly focused on website design and menu functionality. Additionally, I have integrated a newsletter subscription plugin for managing su ...

Setting a variable in a v-tab using Vuetify now only takes 2 easy clicks!

I'm currently utilizing Vuetify and vuejs to develop a tab system with 3 tabs. The tabs are being switched dynamically by binding to the href of a v-tab. Each time I click on a tab, the value of the speed variable is modified. However, I'm encoun ...

Prevent automatic scrolling to anchors when using router.push() in Next.js

When using the latest version 10.2 of next, every time a URL with a hash is pushed to the router, next.js automatically jumps to the anchor element. import {useRouter} from 'next/router' router.push('/contact#about-us'); This behavior ...

Issues with the styling of HTML code

Our website features a main menu with submenus that are intended to be displayed only when hovering over the main menu. However, upon loading the site, the submenu is already visible causing an issue. We need the submenu to appear only when the main menu i ...

What is the process for immediately changing the background color of an input field as soon as text is entered?

I am encountering an issue with the code snippet provided below. My goal is to change the background color of an input field as soon as I start typing something into it. The scenario involves 4 input fields where if the submit button is clicked and any f ...

Node.js is throwing an error "Unexpected token v in JSON at position 0" which

I'm currently working on developing PHP code within the Google App Engine flexible environment. Specifically, I am facing some challenges in setting up the Firebase SDK Admin for the web version. My main struggle lies with the following block of code ...