Criteria for sending error messages (JSON, SQL)

Apologies for any language barriers, I will do my best to explain clearly.

I created a function that generates a table from a JSON based on SQL query values within the JSON.

Sometimes, when the SQL query is incorrect, I encounter issues accessing the JSON. To handle this, I use a variable called test which is defined within the $.getJSON.

To address this issue, I use an if statement to check if the test variable is defined or not. If it's not, I display an alert to notify the user :

if(typeof test == "undefined"){
     $('#loading').hide();
     alert("Error in the query, please adjust your filters."); //Error !
     return;
  }

The problem arises when even with a correct query, I still receive the error message. I'm unsure why this happens because when I print test using console.log(test), it displays as 1 as intended...

Below is my complete function for reference :

function get_values(){ 

  $('#loading').show();

  $("table#mon_tableau").removeClass("hidden");

  var myjson = "http://******/get_json_test.php?callback=?";
  $('.filter').each(function(i, obj){
     var input = $(obj).find("input")[0];
     myjson += '&'+input.name+'=' + input.value;
  });

  $('.display').each(function(i,obj){
     myjson += '&'+$(obj).attr('table')+'|'+$(obj).attr('titre')+'';
  });

  console.log(myjson);

  $.getJSON(myjson, function(data){
     var titre_colindex = 0;
     var test = 1;
        if(data.length != 0){
           newRow = document.getElementById('mon_tableau').getElementsByTagName('tbody')[0].insertRow(-1);
              $.each(data[0], function(index, valeur){ 
                 newCell = newRow.insertCell(titre_colindex);
                 newCell.innerHTML = index;
                 titre_colindex+=1;
              });

              $.each(data, function(i,ti){
                 var newRow;
                 var newCell;
                    newRow = document.getElementById('mon_tableau').getElementsByTagName('tbody')[0].insertRow(-1);
                 
                 var i_colindex=0;
                 $.each(ti, function(index, valeur){
                     
                       newCell = newRow.insertCell(i_colindex);
                       newCell.innerHTML = valeur;
                       i_colindex+=1;
                    
                 });
              }); 
           console.log(erreur);
           $('#loading').hide();
           alert("There are " + data.length + " results");
        }
        else{
           $('#loading').hide();
           $("table#mon_tableau").addClass("hidden");
           alert("There are no results...");
        }
  console.log(test);
  }); 

  if(typeof test == "undefined"){
     $('#loading').hide();
     alert("Error in the query, please adjust your filters.");
     return;
  }
  console.log(test);
} 

Answer №1

When using <code>getJSON, it's important to remember that it is an asynchronous call. This means that the call will be executed, but your if statement will be run immediately afterwards, before the data has been returned. This often leads to the data being undefined. To avoid this issue, make sure to include your if statement within the success or failure routine.

In fact, you can simplify your code by utilizing the promise returned by $.getJSON. You can take advantage of the .done (success) and fail (error) routines provided. Your revised code could look something like this:

$.getJSON(myjson).done(function(data){
    // place all your success logic here
}).fail(function() (
    // handle any errors here
});

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

Simplify JSON data using Jq and include array index in the final output

I'm currently working on consolidating a nested JSON structure into a single JSON output: { "Id" : "1", "items" : [ {"item_name" : "shirt","value" : 10}, {"item_n ...

Parameter name used for jQuery input

Is it possible to include the agru variable inside the function $('input[name=agru]')? function changeBackground(agru){ $('input[name=agru]').css('background','red'); } It seems that using $('input[nam ...

React splits the page and interrupts the scroll event listener

For some reason, my webpage has been split by the React.js library. When attempting to scroll down while hovering over the top navigation menu, scrolling becomes impossible. However, scrolling works fine when done on any other part of the screen. I' ...

I want the name to be retained in storage to prevent the item from being mistakenly renamed when deleted based on its index

After pressing the "add layer" button in the box shadow generator, a new layer is added. For example, let's say I have added 3 layers (Layer 1, Layer 2, Layer 3) and then deleted Layer 2. After deletion, the remaining Layers are Layer 1 and Layer 3, b ...

Error: Unable to decode byte 0xc4 at position 1 using ASCII codec as it is outside the range of 128

As the title of the question suggests, I am encountering an issue with encoding/decoding strings. The tools I am using are: python 2.7 | django 1.11 | jinja2 2.8 Essentially, the process involves retrieving data from a database, serializing it, caching i ...

Does the useState hook have any connection to hoisting in React?

I am relatively new to React.js and JavaScript, currently working on a project where I need the ability to manually update my components as needed, due to limitations with a third-party library. After doing some research, I came across a pattern on the of ...

What is the best way to incorporate styles from one page to another in Angular JS?

After integrating the style on the home page, I noticed that it is not being applied when clicking on the about page. Despite including routes for the about page, there are no CSS or JS files linked to it. Click here for a screenshot. ...

Having trouble retrieving data from a Postgres table in my Node Express app, despite using async/await functionalities

Trying to fetch a row from my Postgres database table by id has presented an issue. The function calling the query contains data, but the controller is returning null. It appears that the controller is resolving before the query, despite using await in my ...

The JS script is activated only when the window is resized

I have incorporated a touch image slide using an external library called SwipeJS. However, it seems to only function properly when I resize my browser window. Within the body, I have structured my images in the Swipe Container as follows: <div id=&apo ...

The webpage you are looking for cannot be found as there seems to be an issue with

I am attempting to pass some variables to a PHP script and then store them in a MySQL database. Below is my JavaScript code: $.ajax({ url: '/insert.php', type: 'POST', data: {endadres:endadres,stadres:stadr ...

Is it possible to retrieve Firebase values, but not able to access them?

I'm facing an unusual issue where pushing a value to a Firebase object leads to two unexpected outcomes: I am unable to retrieve it from the array when pulling the object from Firebase. The array I receive does not have a length property. Let' ...

Is there a way to stop Bootstrap from automatically bolding the font?

When testing this simple example without the bootstrap link, everything seems to be working correctly: Hovering over any word changes its color to red, and when hovering away it returns to black. But as soon as the bootstrap link is included, the text bec ...

Decoding a JSON array containing an array of nested objects using Retrofit

I am facing an issue with parsing a JSON response from an endpoint to fetch news. It seems like I am getting incorrect information or maybe my implementation is incorrect: { "data": [ { "alignImages": "left", "data": [ ...

Tips for downloading a file using a Django function triggered by JavaScript instead of redirecting to the URL

Managing a page with multiple buttons that trigger various functions, such as sending an SMS (via API), emailing a file, or downloading a PDF. The button actions are powered by Ajax requests through JavaScript instead of using forms. I initially used Java ...

Troubleshooting: Issues with AngularJS $route.reload() functionality

I have an angular app and I'm attempting to refresh the page. I've tried using $route.reload() as recommended in multiple posts, but I can't seem to get it to work (Chrome is showing me an error). Here's my controller: var app = angula ...

Manage the sequence in which the various paths of an SVG element are displayed

Searching for a way to display an image in HTML with a rounded dashed border? Take a look at the example below: https://i.sstatic.net/YrCZS.png The number of dashes and their colors can be controlled, similar to what you see in WhatsApp's status tab ...

Scrolling to the top of the Popper component when an element is selected

I am currently utilizing the Autocomplete Material UI control with multiple selections enabled. Here is the code snippet I have created based on this answer: <Autocomplete PopperComponent={PopperMy} ... /> const PopperMy = function (props) ...

Create a custom countdown using Jquery and Javascript that integrates with MySQL and PHP to display the datetime in the format Y-m-d

Hey there, I'm looking to create a countdown script using dates in the format (Y-m-d H:m:s). The goal is to retrieve the current_datetime and expire_datetime in this format and incorporate them into some JavaScript or jQuery plugin to display a countd ...

Ways to obtain the chosen option from a drop-down menu using jQuery

I'm currently experiencing an issue where the selected value of a drop down is not being displayed correctly. Instead of selecting the dropdown value, it's adding another value to the list. Below is the code snippet I'm using: JQuery var ...

What is the best way to introduce a time delay between two JavaScript functions?

Here is some JavaScript code that I am working with: clientData.reloadTable( "CreateCSV", "/create/file" ); $("#downloadFrame").attr("src","/download/download"); The first statement in the code above creates a CSV file on the disk. The second statement d ...