Using JavaScript: Retrieve the URL from a JSON file and run it in the background

I am looking to make a JSON request using jQuery:

$.getJSON('http://example.com/file.php', function(data) {
    //data
});

An example of the JSON output:

{ "url":"http://example.com/execute.php" }

Next, I want to silently execute the URL on the client side without notifying the user. This is obtained from the JSON file.

I would like to repeat this entire process every second, fetching the JSON and executing it in the background.

Answer №1

function executePhpScript() {

  $.ajax({
  file: "http://example.com/runscript/index.php"
  method: 'POST',
  success: function(data) {
    setTimeout(function() { executePhpScript() }, 1000);
  }});

}

setTimeout(function() { executePhpScript() }, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I want to silently run the URL in the background (on the client side) that we have obtained from a JSON file.

You can utilize AJAX not only for a response, but also as a request. This code will continuously execute the PHP page every * times it is called. In the success listener, you can either leave it empty or use a setInterval() to repeat the process

For further information, refer to the documentation: http://api.jquery.com/jquery.ajax/

Answer №2

I came up with this unique solution where I continuously retrieve a URL every second and execute it:

function fetchAndExecuteURL() {
    var targetURL = 'http://uniqueexample.com/pending.php';
    $.getJSON(targetURL, function(response){
        var urlToExecute = response.url;
        $.get(urlToExecute);
    });
}

$(document).ready(function(){
    setInterval(fetchAndExecuteURL, 1000);
    fetchAndExecuteURL();
});

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

The react-router-dom seems to be malfunctioning, so let's simply render the "/"

Struggling to render multiple pages in React, I am a newbie and have been exploring various tutorials and pages. My stack includes React, Webpack, Babel, and ESLint with Airbnb configuration. When I render my React app, it appears like this. View of the ...

The first three AJAX requests are successful, but the fourth one fails to reach the PHP script

I am currently working on cascaded selects (a total of 4) that retrieve data from a database. To populate them, I use SQL queries based on the selection made in the previous select element. To establish communication between the select element and the subs ...

Updating the parameters when clicking on each pagination button: A guide

Does anyone have advice on implementing pagination? I am currently working on loading a datatable with a few records initially. Once the page is loaded, I want to be able to click on pagination buttons like next or any pagination buttons to display a new s ...

Ways to address issues in my tree-building algorithm when the parent ID is missing

Currently, I'm in the process of creating a function to build a tree. Everything seems to be functioning correctly until I encounter a scenario where a document is added with a parentID that doesn't exist in the list. The root node is intended to ...

pytrends_json.decoder.JSONDecodeError: Anticipating a value at line 1, column 1 (character 0)

When I execute this code, I encounter an error: from pytrends.request import TrendReq google_username = '' google_password = '' pytrend = TrendReq(google_username, google_password, custom_useragent='My Pytrends Script') pytre ...

What could be causing an error with NextJS's getStaticPaths when running next build?

When attempting to use Next.js's SSG with getStaticPaths and getStaticProps, everything worked fine in development. However, upon running the build command, an error was thrown: A required parameter (id) was not provided as a string in getStaticPath ...

An application designed to generate a compilation of multiple documents

Data files: file.json - database of athletes including chest number, first name, and last name result.txt - initial results with time data in specific format Information to be included in the list: Results Summary Position | Chest Number | First Na ...

The size of objects on canvas is not consistent when loading with fabric.js loadFromJSON

Click here to view the code var canvas = new fabric.Canvas('canvas_1'); var canvas2 = new fabric.Canvas('canvas_2'); var imgObj = new Image(); imgObj.src = "https://gtaprinting.ca/wp-content/uploads/2021/05/blank-t-shirt-front-gre ...

Displaying tooltips dynamically for newly added elements all sharing a common class in React

I'm facing an issue with the primereact tooltip component from . Everything seems to be working fine except for the target property. When I have multiple elements on a page with the same class, the tooltip works as expected. However, when I add a new ...

Display the Bootstrap datepicker within an h4 element set to default to today's date, utilizing both Angular and jQuery

Utilizing Boostrap datepicker to obtain the selected date from the calendar and insert it into an <h4> html tag. However, my goal is to display today's date by default in the h4 when it opens for the first time. Using angular.js + jquery f ...

Error in custom class using vanilla JavaScript: "Error: Unable to assign innerHTML to an undefined property"

Apologies for the ambiguous title, but I am struggling to pinpoint the exact issue at hand... I'm essentially guessing my way through this problem. This marks my initial venture into creating a reusable Javascript class. Below is a simplified version ...

What is the best way to determine the moving average of an Object value within an array?

In my dataset, I have an array called 'scores' that contains 4 objects. export const scores = [ { day: '1', Barcelona: 1, Real: 3, Valencia: 0}, { day: '2', Barcelona: 4, Real: 6, Valencia: 3}, { day: '3', Bar ...

What other ways can websockets be utilized besides comet?

Websockets offer a more efficient solution for comet (reverse Ajax, often achieved through long-polling). However, are there other ways we can utilize websockets? For instance: - Can websockets be used to facilitate communication between different bro ...

Ideas for displaying data or a message only once when selecting multiple checkboxes in jquery

code: <script> $(document).ready(function(){ $(".choose").click(function(){ job_type = $(':checked').map(function() { return this.value; }).get().join(',&ap ...

Updating a single .jshintrc option for a folder

My project has a .jshintrc file at the root, containing the following settings: { "node": true, "smarttabs": true, "undef": true, "unused": true } While these settings work well for node-related code in my project, they are not suitable for brows ...

What is the best way to retrieve a value in Ajax?

I'm trying to assign the result of an MVC controller method to a variable. function someFunction(){ var result; $.Ajax{ //??? } return result; } //Contrast with C++ int f() { //just! return result; } Post Script: Th ...

Submitting the form does not result in the textbox being cleared

I have been attempting to clear the txtSubTotal text box upon clicking the PROCEED button, but it seems that my efforts have been in vain despite trying various code examples, including those from SO. btnProceed/HTML <input type="submit" name="btnProc ...

Using a spray to parse a JSON array with nested JSON elements

I have a case class with string list fields and I am struggling to parse it from JSON. I have defined a JSON Reader : val jsonReader = new JsonReader[PeaceWatcherReport] { override def read(json: JsValue): PeaceWatcherReport = { val fields = js ...

Guide on How to Upload Huge Files Using a Single Connection in JavaScript

As I work on writing some HTML/JS code to enable the uploading of large files (multi-GB) to a remote server, I am facing some challenges. In the past, we relied on a flash uploader that sent a file in a single network request. However, using flash has now ...

Using JQuery to manipulate `this`, its children, its siblings, and more

Can anyone help me determine the most effective way to send data from a get request to a specific div? My challenge is to send it only to a div that is related to the one triggering the action. For example, when I click on the message_tab, I want to send t ...