What is the process of submitting a query request and then saving it as a variable in javascript?

As a beginner in SQL, JSON, and Fusion Table, I am looking to extract data from a Fusion Table and store it in a JavaScript variable, allowing me to display the data within a div element.

This is the progress of my JavaScript code so far:

var TopCity;
TopCity = '{
  "dataSourceUrl": 'http://www.google.com/fusiontables/gvizdata?tq=',
  "query": 
'SELECT Location FROM 131fgSFd-cumxvMzICckXO-W4CldzfO9J9D--Vw9V ORDER BY Total_Task_Num DESC LIMIT 1',

 }';


$("#TopCityDiv").append("<div>" + TopCity + "</div>");

The aim is to identify the city with the highest number of completed tasks and showcase its name.

Although I have gone through the Fusion Table SQL documentation, there are still aspects that confuse me: https://developers.google.com/fusiontables/docs/v1/sql-reference

Your assistance is greatly appreciated.

Update: Success has been achieved!

To execute queries on my fusion table rather than just save them, I must activate the Fusion Table API and acquire a public API key.

The operative code is as follows:

$(document).ready(function() {
    var TopCity;

    $.ajax({
        type: "GET",
        url: "https://www.googleapis.com/fusiontables/v1/query?sql=SELECT+Location+FROM+131fgSFd-cumxvMzICckXO-W4CldzfO9J9D--Vw9V+ORDER+BY+Total_Task_Num+DESC+LIMIT+1&hdrs=false&typed=false&fields=rows&key={API Key}",

        success: function(data) {
            TopCity = data["rows"];
            $("#TopCityDiv").append("<div>" + TopCity + "</div>");
        },
        error: function(xhr, error) {
            console.log('NaN');

        }
    });

});

Answer №1

To fetch the data, it is recommended to utilize a callback function. Here's an example of how you can achieve this:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {

        var TopCity;

        $.get('https://www.googleapis.com/fusiontables/v1/query?sql=SELECT Location FROM 131fgSFd-cumxvMzICckXO-W4CldzfO9J9D--Vw9V ORDER BY Total_Task_Num DESC LIMIT 1&key={your API key}', function (data, status, xhr) {
            //store the fetched data in TopCity variable
            TopCity = data;

            //perform actions with the retrieved data
            $("#TopCityDiv").append("<div>" + data + "</div>");
        });
    });
</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

What is the best method to ensure a jQuery function only runs once, even when declared multiple times within a form?

Whenever a button with a specific class is clicked in a document, a jQuery function is triggered to perform a certain action. See example below. $(document).on('click', '.tambah', function(){ alert('tombol tambah telah ditekan ...

How can you create a dynamic bounce effect for text with jquery animate()?

I've been experimenting with Jquery to achieve a bounce effect, here's what I have so far: Html: <div id ="animation">bounce</div> Jquery: $("#animation").animate({ marginTop: "80px" }, 1500 ) .animate({ marginBotto ...

Exploring the functionality of className using materialUI

Attempting to test whether my component has a specific class is proving challenging. This difficulty stems from the fact that the class is generated using MaterialUI. For instance, I am looking for a class named spinningIconCenter, but in reality, it appea ...

Utilize a function or array to send various data with an Ajax post request

Hey, I'm on the hunt for a more efficient method to send data using ajax to php for multiple users. Take a peek at my code below: $(document).ready(function(){ $("#all").click(function(){ document.getElementById('babon').click(); ...

Sorting data using a SQL Case statementIn SQL, you can

I have encountered a problem with the following queries. In these queries, TOTAL_AMOUNT is of data type decimal, and INVOICE_NO is of data type varchar. The first query is functioning correctly, but the second query is producing an error: Error converting ...

How can I dynamically assign ngModel in AngularJS?

I've created a directive with an isolate scope that maps a list of objects to inputs for modifying a specific property. However, I now aim to make this component more universal by allowing it to bind to deeply nested properties within each object. Fo ...

Utilizing Python requests/Beautiful Soup to extract JSON data from a scraped div class

I am currently working on a project to scrape images from Google search results using Requests and Beautifulsoup. While there are some examples online that use urllib2 (which works for me half the time), I am specifically focusing on utilizing Requests wit ...

Patience is necessary as we await the initialization of the lazily loaded

I'm dealing with a scenario where I have a button triggering an onClick handler. In the onClick function, the first action is: if (this.state.lazyLoadedData === undefined) { await this.loadData(); } The issue arises when I click the button rapid ...

Obtain a specific element in Puppeteer JS by utilizing the waitForSelector function to detect when its class name changes

I am faced with a situation where I need to wait for a specific element to change its classes dynamically. The challenge arises when utilizing the waitForSelector function, as it fails to work when no new element is added to the DOM. Instead, it is the &l ...

How can I effectively store nested JSON data in a SQL Server database?

I am currently dealing with a nested JSON dataset that needs to be uploaded into SQL SERVER 2012. This JSON data consists of two main sections - one for columns and the other for rows. My task is to map the values from the rows section into their correspon ...

How to set a JSON Schema property to specify the maximum length for a numerical value

I need to limit the decimal Amount field to have a length of 12+4, meaning the maximum integer value can be 999999999999 and the maximum number of fractional digits is 4. I am implementing schema validation using NewtonSoft.JSON. Despite trying the schema ...

Is it possible to bind a function to data in Vue js?

Can a function be data bound in Vue? In my template, I am trying something like this: <title> {{nameofFunction()}}</title> However, when I run it, it simply displays 'native function' on the page. Any insights would be appreciated ...

Combining two tables using CAST in SQL Server

I am currently working with two tables and I need to create a view that will join them together. To better illustrate my issue, I have created a visual aid. In the image provided above, it is clear that the values in table 1 are unique. My goal is to dete ...

When it comes to iterating through arrays in nodejs

Can someone assist me with using a for loop on an array to search for titles? I have a basic ADD TODO form input that submits and adds todos or titles to the array: todos.push({ title: req.body.add_todo_input, complete: false }); I am pushing user input ...

Iterate over the JSON file, organizing the contents by date (utilizing a custom field) and displaying a maximum of

Trying to create a function to loop through a JSON file from the WordPress JSON API that contains 100 items. I want to display only 4 items, specifically the 4 items from today. The function needs to check today's date and loop through the 100 items t ...

What is the best way to utilize Python in order to transform a large amount of unicode into characters to create a string-like appearance?

In JavaScript, I've managed to do this: eval(String.fromCharCode(102,117,110,99,116,105,111,110,32,99,104,101,99,107,40,41,123,13,10,09,118,97,114,32,97,32,61,32,39,100,52,103,39,59,13,10,09,105,102,40,100,111,99,117,109,101,110,116,46,103,101,116,69 ...

Attempting to invert certain JSON data

I have successfully displayed data from a JSON array on a webpage, but now I am trying to reverse the order of the output. I attempted to change the foreach statement to $result['calls']. <?php $getfile = file_get_contents('call.json&ap ...

Hide form data upon submission

I have a form and I'm looking to send hidden input using JavaScript. How can this be achieved? Example: <input id="total" type="hidden" value="" name="total" /> When the submit button is clicked, I would like to set its value. ...

redux form has encountered an error: the element type provided is not valid, a string is expected for built-in components

While working on my stepper code, I attempted to add a radio button. However, this addition resulted in the following error. I referenced this example before implementing it. Despite that, I am still encountering errors. Could you please advise me on how ...

Execute a parent action within a Controller

I'm currently working on customizing the update() and create() actions within a specific controller in my Sails.js application. My goal is to upload a file first, store the file path (which is saved on s3 using skipper) in the request body, and then ...