challenges encountered when saving a getjson request as a variable

I am experiencing difficulties in retrieving a variable from a getJSON() request. The issue lies within the following three functions:

function getPcLatitude() { // onchange

    var funcid = "get_postcode_latitude";
    var postcode = parseInt($('#input-field-postcode').val());

    var jqxhr = $.getJSON('functions/getdata.php', {

        "funcid":funcid,
        "postcode":postcode}).done(function(dataLatitude) {

            if (dataLatitude == null) {
                //..
            } else {
                var myLatitude = 0;
                for (var i=0;i<dataLatitude.length;i++){
                   myLatitude = dataLatitude[i].pc_latitude;
                }
                return parseFloat(myLatitude);
                //alert(myLatitude);
            }

        });
}

function getPcLongitude() { // onchange

    var funcid = "get_postcode_longitude";
    var postcode = parseInt($('#input-field-postcode').val());

    var jqxhr = $.getJSON('functions/getdata.php', {

        "funcid":funcid,
        "postcode":postcode}).done(function(dataLongitude) {

            if (dataLongitude == null) {
                //..
            } else {
                var myLongitude = 0;
                for (var i=0;i<dataLongitude.length;i++){
                   myLongitude = dataLongitude[i].pc_longitude;
                }
                return parseFloat(myLongitude);
                //alert(myLongitude);
            }

        });
}

function getTop5Postcode() { // onchange

    setTimeout(function() {

        var funcid = "get_top_5_postcode";
        var er = rangeM3Slider.noUiSlider.get();
        var zv = $("#selectzv").val();
        if (zv < 1) {
            var zv = $("#selectzvfc").val();
        }
        var zp = $("#selectzp").val();
        if (zp < 1) {
            var zp = $("#selectzpfc").val();
        }
        var latitude = getPcLatitude();
        var longitude = getPcLongitude();
        var chosendistance = parseInt($('#input-field-afstand').val());

        var jqxhr = $.getJSON('functions/getdata.php', {
            "funcid":funcid,
            "er":er,
            "zp":zp,
            "zv":zv,
            "latitude":latitude,
            "longitude":longitude,
            "chosendistance":chosendistance}).done(function(dataPrices) {

                if (dataPrices == null) {
                    $('#myModalAlert').modal('show');
                } else {

                    //$('#myModalData').modal('show');
                    var table = '';
                    var iconClassZkn = '';
                    var iconClassIp = '';
                    for (var i=0;i<dataPrices.length;i++){
                       if (dataPrices[i].zkn_score == 0) {
                            iconClassZkn = 'no-score';
                       } else {
                            iconClassZkn = 'zkn-score';
                       }
                       if (dataPrices[i].ip_score == 0) {
                            iconClassIp = 'no-score';
                       } else {
                            iconClassIp = 'ip-score';
                       }
                       table += '<tr>'
                       + '<td width="75" class="zkh-image" align="center">'+ dataPrices[i].zvln_icon +'</td>'
                       + '<td width="250" align="left"><b>'+ dataPrices[i].zvln +'</b><br><i>Locatie: ' + dataPrices[i].zvln_city + '</i></td>'
                       + '<td class=text-center> € '+ dataPrices[i].tarif +'</td>'
                       + '<td class=text-center> € '+ dataPrices[i].risico +'</td>'
                       + '<td class=text-center><a target="_blank" href="' + dataPrices[i].zkn_url + '"><span class="' + iconClassZkn + '"><font size="2"><b>' + dataPrices[i].zkn_score + '</b></font></span></a></td>'
                       + '<td class=text-center><a target="_blank" href="' + dataPrices[i].ip_url + '"><span class="' + iconClassIp + '"><font size="2"><b>' + dataPrices[i].ip_score + '</b></font></span></a></td>'
                       + '</tr>';   
                    }
                    $('#top5').html(table);
                    //$('#myModalData').modal('hide');
                  }
            })
            .fail(function() { $('#myModalAlert').modal('show');}); //When getJSON request fails
    }, 0);

}

There seems to be an issue with the

var latitude = getPcLatitude();
var longitude = getPcLongitude();

sections not working or failing to retrieve values from the functions. Interestingly, changing the return statement in both functions to an alert() successfully displays the expected values indicating that these functions are functioning correctly.

However, when I manually set the two variables as follows:

var latitude = 5215;
var longitude = 538;

the getTop5Postcode() function operates smoothly and populates the table accordingly.

If you have any insights or solutions to this problem, I would greatly appreciate your assistance.

Kind regards, Bart

Answer №1

Always keep in mind that JavaScript operates asynchronously, meaning that when you reach the return statement, the request may still be pending. To handle this situation, consider implementing a promise like this:

 fetch('url').then(function(response){//perform desired actions here})

Answer №2

Your getPcLatitude and getPcLongitude functions are not returning any values because the return statement is inside an asynchronous request callback, which is why the alert displays the correct value.

To fix this issue, I recommend updating both function signatures to include a callback parameter:

function getPcLatitude(callback) {
...
}

function getPcLongitude(callback) {
...
}

Instead of returning a value, you should pass the value to the callback like this:

callback(parseFloat(myLatitude));

callback(parseFloat(myLongitude));

Your final function should look something like this:

function getTop5Postcode() { // onchange

setTimeout(function() {

    var latitude;
    var longitude;

    getPcLatitude(function(lat) {
        latitude = lat;
        getTop5(); 
    });

    getPcLongitude(function(longi) {
        longitude = longi;
        getTop5();
    });


    function getTop5() {

        if (!latitude || !longitude) {
            return; 
        }

        var funcid = "get_top_5_postcode";
        var er = rangeM3Slider.noUiSlider.get();
        var zv = $("#selectzv").val();
        if (zv < 1) {
            var zv = $("#selectzvfc").val();
        }
        var zp = $("#selectzp").val();
        if (zp < 1) {
            var zp = $("#selectzpfc").val();
        }

        var chosendistance = parseInt($('#input-field-afstand').val());

        var jqxhr = $.getJSON('functions/getdata.php', {
            "funcid":funcid,
            "er":er,
            "zp":zp,
            "zv":zv,
            "latitude":latitude,
            "longitude":longitude,
            "chosendistance":chosendistance}).done(function(dataPrices) {
                
                if (dataPrices == null) {
                    $('#myModalAlert').modal('show');
                } else {
                    
                    var table = '';
                    var iconClassZkn = '';
                    var iconClassIp = '';
                    for (var i=0;i<dataPrices.length;i++){
                    if (dataPrices[i].zkn_score == 0) {
                            iconClassZkn = 'no-score';
                    } else {
                            iconClassZkn = 'zkn-score';
                    }
                    if (dataPrices[i].ip_score == 0) {
                            iconClassIp = 'no-score';
                    } else {
                            iconClassIp = 'ip-score';
                    }
                    table += '<tr>'
                    + '<td width="75" class="zkh-image" align="center">'+ dataPrices[i].zvln_icon +'</td>'
                    + '<td width="250" align="left"><b>'+ dataPrices[i].zvln +'</b><br><i>Locatie: ' + dataPrices[i].zvln_city + '</i></td>'
                    + '<td class=text-center> € '+ dataPrices[i].tarif +'</td>'
                    + '<td class=text-center> € '+ dataPrices[i].risico +'</td>'
                    + '<td class=text-center><a target="_blank" href="' + dataPrices[i].zkn_url + '"><span class="' + iconClassZkn + '"><font size="2"><b>' + dataPrices[i].zkn_score + '</b></font></span></a></td>'
                    + '<td class=text-center><a target="_blank" href="' + dataPrices[i].ip_url + '"><span class="' + iconClassIp + '"><font size="2"><b>' + dataPrices[i].ip_score + '</b></font></span></a></td>'
                    + '</tr>';   
                    }
                    $('#top5').html(table);
                }
            })
            .fail(function() { $('#myModalAlert').modal('show');}); 
    }


}, 0);

}

This solution may not be perfect but it should work! Keep in mind that this code has not been tested.

Answer №3

After implementing some additional features in my mysql queries, I was able to streamline the process and now only need to utilize the main function.

Everything is running smoothly! Grateful for all the assistance!

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

Get a URL from the JSON data returned by the Wikipedia API

How can I retrieve the image URL from a JSON response and store it in a variable? I found helpful information on the MediaWiki API help page Following this example to extract image information from a page: https://commons.wikimedia.org/w/api.php?action= ...

Using Jquery and css to toggle and display active menu when clicked

I am trying to create a jQuery dropdown menu similar to the Facebook notification menu. However, I am encountering an issue with the JavaScript code. Here is my JSFiddle example. The problem arises when I click on the menu; it opens with an icon, similar ...

Error message: When using the Semantic UI React Modal, the Portal.render() function requires a valid React element to be returned, otherwise

Currently, I am working on integrating the Semantic UI React modal into my dashboard application built using React. To facilitate this integration, I have developed a ModalManager component that will be utilized in conjunction with Redux to handle the stat ...

Is it mandatory for the npm install command to only be compatible with Node.js for the script

I've encountered an API that provides a JS SDK, and the instructions on its GitHub page suggest using npm install. My question is whether I need to have Node.js in order to use this SDK since it seems to be designed for it, or if I can simply work wit ...

When properties remain unchanged, they do not hold the same value in a Firestore-triggered Cloud Function

Within my Firestore database, there is a collection named events consisting of documents with attributes such as begin, end, and title. The function in question is triggered when any changes occur within a document. The begin and end fields are both categ ...

"Implementing AngularJS bidirectional data binding to dynamically link user inputs with corresponding fields

Having trouble automatically outputting data with angularJS. One of the great features of angular is two-way data binding, but I can't seem to bind input with a JSON file. What I want to achieve is if the user's input matches a key, the correspon ...

How can I make the burger icon responsive and centered in my navbar?

Struggling to center the burger icon in the navbar has been a bit of a challenge for me. Although it appears centered on small mobile devices, the icon shifts to the upper side on larger screens like tablets, losing its centered position. I am seeking advi ...

Issue with JavaScript not executing upon clicking the submit button on a form within the Wordpress admin page

In the admin pages of my Wordpress installation, I have created an HTML form. My goal is to validate the data inputted when the submit button is pressed using a Javascript function. If the data is not correctly inserted, I want alerts to be displayed. Desp ...

Establishing a default selection for a react dropdown menu filled with data retrieved from an API request

class Select extends React.PureComponent { constructor(props) { super(props) this.state = { value: this.props.initialValue } this.handleChange = this.handleChange.bind(this) } handleChange(e) { e.persist() ...

Using Node's Express bodyParser() to access a JSON string that has been parsed

Question: How can I retrieve the parsed JSON object from the server side? I have successfully sent a JSON string to the server, but I am having trouble accessing the object once it is parsed. The client-side script for sending the JSON data is as follows ...

What is the best way to assign or convert an object of one type to another specific type?

So here's the scenario: I have an object of type 'any' and I want to assign it an object of type 'myResponse' as shown below. public obj: any; public set Result() { obj = myResponse; } Now, in another function ...

Tips on enabling JS tooltips in Shadow DOM

I am currently developing an app using Vue and Bootstrap, where I am creating web components based on the official Vue documentation. The Bootstrap framework and my business logic are functioning well within the #shadow-root of the web components, behaving ...

Manipulate documents in a Mongoose array by conditionally adding or removing elements

Upon receiving data from the front end, I am dealing with the following object: { name: "Test 1", sets: [1,2] } Mongo Schema: Sets name: { type: String }, tests : [{ type: Schema.Types.ObjectId, ref : 'Test' ...

Discover the myriad of possibilities created by combining arrays

I am working on a code snippet that aims to generate an array containing all possible combinations between two or more arrays. However, I am encountering a specific issue. getCombn(arr: string | any[], pre?: string | undefined) { pre = pre || ' &a ...

I am looking to host two Nuxt.js (Vue.js) applications on a single server using PM2

To begin using Nuxt.js, follow these steps: vue init nuxt/express myapp1 vue init nuxt/express myapp2 The structure of my projects is as shown below. /workspace/myapp1 (Nuxt.js application) /workspace/myapp2 (Nuxt.js application) Within my workspace, ...

What steps can be taken to ensure that a WebSQL query does not return negative

Here's the code snippet I am currently using: function decrementCart(quantity, id){ db.transaction(function(tx){ tx.executeSql("UPDATE cart SET quantity=(quantity -1) WHERE id=?", [id]) ...

ReactJS encountering an invalid dropzone element

Encountering the error "invalid dropzone element". I added var Dropzone = require('react-dropzone'); to my webpack.config.js file in hopes of activating the Dropzone element. This is what is included in my JavaScript file, copied from a Gith ...

Verify if the value in a textbox exceeds the number entered in an array of textboxes

My goal is to compare the value of a single text box, labeled as "totalmarkstoall", with multiple arrays of text boxes labeled as "marksscored". The JavaScript code below is set up to compare these values using a key up function. The issue I am facing is ...

Proceed with another ajax request only when the previous one has been successfully completed and loaded

While scrolling down and loading content into my page, I am facing an issue. The ajax executions load too quickly, causing the subsequent calls to not receive correct information from the first ajax call that is loaded into the DOM. How can I ensure that ...

I am looking for a way to generate unique dynamic IDs for each input textbox created within a PHP while loop. Can

How can I retrieve the ID of a selected text box generated within a while loop in order to update a field similar to phpMyAdmin? <?php while($row=mysql_fetch_assoc($result)) { ?> <tr> <td><input type ...