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

Guide to incorporating onchange event in a React.js project

Just starting out with reactjs and looking to incorporate onchange into my application. Utilizing the map function for data manipulation. handleChange = (event, k, i) => { this.setState({ dList: update(this.state.dList[k][i], { [ev ...

Switching the GET method to DELETE in nodeJS can be accomplished using an anchor tag

Let's say I have a link in my EJS file like this: <a href="/user/12">Delete</a> In my route file, I have the delete code set up like this: router.delete( '/user/:id', function ( req, res ) { // code for delete operation }); ...

Attempting to access a shared php/javascript library using mod_rewrite

Let's dive into a fresh perspective on a question I previously raised: I've crafted a mod_rewrite snippet that checks for the existence of JavaScript, CSS, and PHP files on the subdomain they are called from (e.g., subdomain.example.com). If the ...

Interact with AngularJS and ASP.NET MVC by invoking controller actions

Previously, I used the following code to retrieve a JSON result from a function before integrating AngularJS: $.ajax({ url: '@Url.Action("getGamedata", "Home")', type: 'GET', dataType: 'json', ...

Executing child processes in the Mean Stack environment involves utilizing the `child_process`

I am working on a Mean application that utilizes nodejs, angularjs and expressjs. In my setup, the server is called from the angular controller like this: Angular Controller.js $http.post('/sample', $scope.sample).then(function (response) ...

Troubleshooting MongoDB query criteria in Meteor and JavaScript doesn't yield the expected results

I am encountering an issue with a Products collection that has an attribute called "productCode". My goal is to create a server-side query to fetch a product based on the productCode attribute. Unfortunately, I keep running into a "cannot read property &ap ...

Tips for submitting a form using yui3

While utilizing YUI3's io-form module to submit a form, I encountered an issue where the server received null field values. Any insights or assistance would be greatly appreciated. <form name='testajax' id="testajax1"> <input typ ...

I am experiencing an issue where my UI does not reflect changes in the data model in SAP

Hey there, I've been grappling with a particular issue that has me stumped for the past few days, and my colleagues haven't been able to crack it either. The problem lies in binding two boolean values in a JSON to two different visible properti ...

Switch out the name of multiple elements with mootools

Is there a Moo tool that can replace multiple element IDs? I currently have the following code: $$('myelement').each(function(el){ var get_all_labels = el.getElements('label'); var get_label_id = get_all_l ...

Rotate the image using the handler, not by directly manipulating the image itself

I need help rotating the image using a handler instead of directly on the image itself. I do not want to rotate the image when clicking and rotating it directly. Please do not suggest using Jquery UI rotatable because resizing the image with Jquery UI resi ...

Are you experiencing issues with your Ajax request?

I've been struggling to retrieve json data from an API. Despite my efforts, the GET request seems to be executing successfully and returning the correct data when I check the Net tab in Firebug. Can anyone offer advice on what could be going wrong or ...

What is the best way to activate a function within an npm package in a Vue application?

I'm just starting out with Vuejs and I've recently installed the vue-countup-v2 npm package. I successfully imported it into my Vue component and noticed that it works perfectly when the page loads. However, I am interested in triggering the Coun ...

Using Pocketbase OAuth in SvelteKit is not currently supported

I've experimented with various strategies, but I still couldn't make it work. Here's the recommendation from Pocketbase (): loginWithGoogle: async ({ locals }: { locals: App.Locals }) => { await locals.pb.collection('users' ...

Issue with mouseMove function not aligning correctly with object-fit:contain CSS property

My current code allows users to select a color from an image when hovering over the pixel with the mouse. However, I am encountering an issue where the colors do not map correctly when using object-fit: contain for the image. The script seems to be treatin ...

`Optimizing Performance using jQuery Functions and AJAX`

As someone exploring ajax for the first time, I'm eager to learn how to write jQuery code that ensures my simple functions like slideshows and overlays still work smoothly when a page is loaded via ajax. Currently, I am implementing the following met ...

Handling errors in XMLHttpRequest using Axios in React JS

I am currently utilizing the REACT-JS framework for my FRONT-END development: Below is the action I am calling from REDUX-REACT export function UserLogin(values) { var headers = { 'Access-Control-Allow-Origin': '*', ...

Typehead.js on Twitter is displaying the full query instead of just the value

The Problem This is the issue I am facing with my code. My goal is to retrieve only the value, but instead of that, the entire query value is being returned. var engine; engine = new Bloodhound({ local: [{value: 'red'}, {value: 'blue&apo ...

Communication between child and parent components in Vue.js is an essential feature

Attempting to invoke functions from my component to Vue for the login process. This is the code snippet of my component : Vue.component('auths', { data: function() { return { ip: '', sessiontoken: '' } ...

I encountered a blank page issue when incorporating ui.bootstrap into my controller within Angular

After attempting to utilize angular bootstrap in my project, I encountered an issue where adding the dependency in my controller and starting the server with grunt serve resulted in a blank page. Take a look at the bower components in the screenshot provid ...

Utilizing JQuery for real-time total updates

When a new div is created by clicking a button, I want to dynamically maintain an order system where the first div is labeled as 1 of 1, then as more divs are added it should change to 1 of 2, and so on. If a div is deleted, the numbering should reset back ...