Is there a way to continuously send out this ajax request?

My attempt to use setInterval for sending an AJAX request every 2 seconds is causing the page to crash. It seems like there is something wrong in my code!

Check out the code below:

 var fburl = "http://graph.facebook.com/http://xzenweb.co.uk?callback=?";

        //fetching data from Facebook API
        $.getJSON(fburl, function(data){

        var name = data["shares"];
        var dataString = 'shares=' + name;

        //sending share count data to server
        $.ajax({
        type: "POST",
        url: "index.php",
        data: dataString,
        cache: false,

        success: function(html)
        {
        $("#content").html(html);
        }
    });
return false;   
}); 

I'm new to ajax and javascript, any help would be greatly appreciated :)

Answer №1

Make sure to provide a callback function when using the $.getJson method

function fetchData(){
         $.getJSON(apiUrl, 
              function(data) {
                  //Your code here
              }); 
         setInterval("fetchData()",2000);
      }

UPDATED ANSWER ::

<script>

$(document).ready(function(){
    fetchData();
  });


function fetchData(){
    $.getJSON("http://api.example.com/data?callback=?", 
         function(data) {
            var result = data["result"];
            var dataToSend = 'result='+result;

            $.ajax({
                type: "POST",
                url: "process.php",
                data: dataToSend,
                cache: false,

                success: function(response)
                {
                    $("#output").html(response);
                }
            });
            return false;  
         }); 
    setTimeout("fetchData()",5000);
 }

</script>


<body>
<div id="output">Placeholder Text</div>
</body>

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 Material UI (mui) 5.0 within an iframe: Tips and tricks

Attempting to display MUI components within an iframe using react portal has resulted in a loss of styling. Despite being rendered within the iframe, MUI components seem to lose their visual appeal when displayed this way. Most resources discussing this is ...

Steps for incrementing a number in an integer field with Node.js and MongoDB

I have a dataset that looks like this: { "_id": "6137392141bbb7723", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95f7e7fafafef0d5f6f4f2f9f0bbf6faf8">[email protected]</a>", ...

The issue arises when attempting to reopen the jQuery UI dialog box after a div has been loaded

I am facing an issue with my survey results table where I have an EDIT button for each entry. Clicking on the EDIT button opens a dialog box with the survey results loaded from the database. After editing the answers, I want to save them in the database an ...

Turning off the transpiler in Vue Webpack to simplify the debugging process

Debugging in Vue can be quite challenging, especially when it comes to setting breakpoints and stepping through the code. The issue seems to stem from the transpiling of javascript ES6/ES2015/ES2016/ES2017 to ES5. While source maps provide some assistance, ...

Encountering an issue while trying to pass hidden value data in array format to the server side

I am currently learning how to use Handlebars as my templating engine and encountering an issue with passing over data from an API (specifically the Edamam recipe search API). I am trying to send back the array of ingredients attached to each recipe card u ...

Validate Bootstrap - Transmit data from all form fields to external PHP script

Is there a way to send all input field values to a remote PHP file using Bootstrap Validator? In my log in form, I have two input fields. I'm utilizing Bootstrap Validator's remote validation on both of them. However, each validation only sends ...

Extract specific form data to use in a jQuery.ajax request

Having trouble extracting the current selected value from a dropdown form in AJAX URL. The Form: <form name="sortby"> <select name="order_by" onchange="myFunction()"> <option<?php if(isset($_GET['order_by']) && ...

Issue with retrieving data using AngularJS Restangular

I've been trying to figure out how to make restangular work properly. When I call my API (using the endpoint /user) I receive the following JSON response: { "error": false, "response": { "totalcount": 2, "records": [{ "id": "1", ...

A few of the npm packages that have been installed globally are not functioning properly

After installing npm globally, I checked its version using npm -v and it displayed correctly as 7.13.0. Similarly, I installed heroku-cli globally, but when I ran heroku --version, it returned the error message: C:\Users\MyName\AppData&bso ...

Upon refreshing, the user of the React JS application is redirected to a different page

My React JS app utilizes react-router-dom v6 to manage the routes. Everything was working fine until I integrated Firebase Firestore. Now, when I reload the seeker page, it redirects me to the home page instead of staying on the seeker page. This issue is ...

Exploring the intricacies of using jquery text() with HTML Entities

I am having difficulty grasping the intricacies of the jquery text() function when used with HTML Entities. It appears that the text() function converts special HTML Entities back to regular characters. I am particularly uncertain about the behavior of thi ...

Trouble with Vuex Store: Changes to table values not reflected in store

I've been tackling a table project using Quasar framework's Q-Popup-edit and Vuex Store. The data populates correctly initially. However, any changes made on the table do not seem to persist and revert back to their original values. Here is a s ...

traverse a JSON object with JavaScript for a loop

After fetching and parsing data from a database using JavaScript, I have the following code snippet: var categories = <?php echo json_encode($categories); ?>; The 'categories' variable in the source code contains the values: var categori ...

CSS fixed dynamically with JavaScript and multiple div elements placed randomly

Is it possible to dynamically change the position of multiple div elements on a webpage without reloading? I am looking for a way to modify the top and left positions of several divs, all with the same class, simultaneously. I want each div to have a diff ...

Parsing polymorphic JSON with Gson in Retrofit 2

I received the following JSON response from the server: { "Information": { "Id": "2dbc0dad8df94f7de7b63d8f22a03c8f", "Type": "User", "Name": "ASD", "IsInProgress": false }, "Errors": [] } However, at times the response looks like this: { "Information": ...

Retrieve the pdf document from the server's response

Currently, I am working on a project where I am using PHP Laravel to create a docx file, converting it to PDF, and saving it in a public server folder. Afterwards, I send the file as a response to the client. On the client side, I am attempting to downloa ...

Displaying various charts in a single view without the need for scrolling in HTML

How can I display the first chart larger and all subsequent charts together in one window without requiring scrolling? This will eventually be viewed on a larger screen where everything will fit perfectly. Any recommendations on how to achieve this? Here ...

Mapping a JSON array within a static method in Angular2 and TypeScript

Struggling with the syntax to properly map my incoming data in a static method. The structure of my json Array is as follows: [ { "documents": [ { "title": "+1 (film)", "is-saved": false, ...

Tips for making a horizontal grid layout with three items in each row

I have a scenario where I need to render a group of Player components using map() loop, and I want them to be displayed horizontally side by side using a Grid component from material-ui. Currently, the components are rendering in a vertical layout: https ...