Passing a jQuery variable called "data" into a JavaScript alert

Upon receiving a JSON response, it is successfully displayed to users without any issues. However, I am encountering a problem when trying to show a JavaScript alert.

During the initial page load, the 'var' is empty, so I have disabled the JavaScript processing for this scenario. But once the form is submitted and JSON data is returned, the 'var' is no longer empty. The JSON data is correctly formatted and visible as: { x: 3, y: 33.6 },{ x: 4, y: 92.6 },{ x: 5, y: 121.2 }. Despite this, when attempting to trigger an alert using JavaScript, it fails to work - only displaying an empty message instead of the intended result.

    <script>   
$(document).ready(function() {
        var ndhtml =[];

    if(ndhtml.length==0)
    {
    alert('empty string')   
    }

    else

    {


var kkpppf=$("#chek").html(ndhtml);
alert('done');
    }
});

</script>

I would greatly appreciate any advice on how to update the JSON data here. The first JS file is external, and its code is:

$(document).ready(function() {
    (function() {
        $('#upload-form2').ajaxForm({
            dataType: 'json',
             success: function(data) {
                var ndhtml = '',
                    downlo;
                for (var i = 0; i < data.length; i++) {
                    downlo = data[i];
                    ndhtml += '' + downlo.ndchart + '';
                }
              $('#chek').html(ndhtml);
               }
        })
    })();
  });

Answer №1

Feel free to give this code a try, it can definitely provide assistance:

var ndhtml = {}; //Creating an empty object called ndhtml

$(document).ready(function($) {
    //updateHtml(); //Calling the update function

    $('#upload-form2').ajaxForm({
        dataType: 'json',
        success: function(data) {
            ndhtml = data; //Initializing Ajax success data to ndhtml
            updateHtml(); //Calling the same function again to set HTML
        }
    });
});



var updateHtml = function(){

    if(ndhtml.length > 0) //Checking the length of ndhtml variable
    {   
        var html = "";
        ndhtml.each(function(index, el) { //Iterating through each element of ndhtml
            html += '' + el.ndchart + ''; // Appending ndchart variable to html
        });

        $('#chek').html(html); //Appending prepared HTML to selected element
    }
    else
    {
        alert("Empty"); //Showing an alert box if ndhtml is empty
    }
}

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

Problem with YouTube iFrame API in IE when using JavaScript

Apologies for the unclear heading, but I'm facing a peculiar issue. The YouTube iFrame API works perfectly on all browsers except Internet Explorer. In IE, none of the JavaScript code runs initially. However, when I open DevTools and refresh the page, ...

Issue with $.Post on second attempt

I am attempting to create a 'Follow' button but the action of returning data, which should display the 'Unfollow' button, is not functioning properly. $('.follow_button').click(function() { //event.preventDefault(); v ...

Attempting to adjust numerical values to display with precise two decimal places using jQuery

Possible Redundancy: JavaScript: how to format a number with only two decimal places I'm getting confused while using variables and now I can't seem to get the calculation working correctly. Any ideas? $("#discount").change(function(){ ...

Integrate jQuery-ui into your Angular 5 application

Having some trouble integrating jquery-ui into my Angular 5 project. I need to use a feature that requires jquery-ui, but I keep encountering this error: TypeError: WEBPACK_MODULE_10_jquery(...).droppable is not a function I initially attempted to plac ...

When utilizing fs.writefile with an object, the output will be [object object]

I need assistance with transferring form data to a json file for the first time. After running my code, the json file only shows [object Object] instead of the expected email, username, and password values. Below is my server-side code (expressjs): app.p ...

Fixed position of the element within a parent stacking context

How can I ensure that the #icon appears below the #dropdown in the following example? https://i.stack.imgur.com/GoBcR.png The position: fixed of #container seems to be creating a new stacking context for its children. Changing the position value fixes th ...

Angular 2: Implementing a Universal CSS Style Sheet

Is there a way to include a universal CSS file in Angular 2 applications? Currently, I have multiple components that share the same button styling, but each component has its own CSS file containing the styles. This setup makes it difficult to make changes ...

interacting with data tables using a jQuery selector or through an application programming

I encountered a problem like the following: First, I attempted to initialize the datatable as shown below: var oTable = table.dataTable(); Although my script ran well, I found that I couldn't use the datatables ajax reload function. oTable.ajax.rel ...

Searching Json by keyword in PHP: A step-by-step guide

I am encountering an issue with searching through a JSON file. Currently, I am trying to search and display faculties based on the entered word, but the search only works when I type in the full name. How can I make the search function work if I only enter ...

Retrieve data entries within a specified range of numbers

Retrieve all records in JSON format from 2 tables "posts_main" and "posts_comments" that are associated with a specific User. $sql = "select posts_main.*, (select groupid from posts_comments where groupid = posts_main.id group by groupid ) as count_commen ...

Analyzing Array Data with PHP

I am looking to analyze JSON data with a comparison in mind. Here is the code snippet I have written for this purpose: $packages[0][0] = "5678"; // en route $packages[0][1] = "3098"; // at checkpoint $packages[0][2] = "4331"; // accepted if (array_key_ex ...

Customize the color of the arrow in Bootstrap

I would like to update the color of the arrow buttons. .carousel-control-prev-icon { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23f00' viewBox='0 0 8 8' ...

Connecting to the Wordpress server using RestKit

Trying to send a JSON to a local Wordpress server, with the following mapping: [RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class] forMIMEType:@"text/html"]; RKObjectMapping *orderEntryMapping = [RKObjectMapping requestMapping]; [orderE ...

transforming an object stored in string format using the data() method

Is there a way to convert a string form object saved with data() using JavaScript (or jQuery)? For example, transforming this: Object {imageNum: 0, text: "'sth1','sth2','sth3'"} into this: Object {imageNum: 0, text: [&apos ...

Combine the animations of multiple elements in a queue using jQuery

I have a dilemma with the animation of several elements. Rapidly navigating back and forth over the submenu seems to cause a queuing issue, potentially leading to malfunction. I've attempted using stop(), delay(), :animated without success. Any sugge ...

The Problem with JSON.stringify() Escaping

I am currently utilizing AJAX alongside JQuery to transmit JSON data to an API server. However, I have encountered an issue with one server that escapes the JSON string when I apply JSON.stringify(), while another server processes the same code without any ...

How do I prevent my image slider from scrolling to the top of the page when I click next or prev?

<script> export default { name: "ImageSlider", data() { return { images: [ "https://cdn.pixabay.com/photo/2015/12/12/15/24/amsterdam-1089646_1280.jpg", "https://cdn.pixabay.com/photo/2016/02/17/2 ...

Vue.js V-for not rendering any content

I am currently working on populating an array with objects retrieved from an API. The objects are being fetched successfully, but I am facing issues when trying to display them using v-for in the array. Below are my data variables: data() { return { ...

Angular custom filter applied only when a button is clicked

I have recently started exploring angular custom filters and I am curious to know if there is a way to trigger the filters in an ng-repeat only upon clicking a button. Check out this example on jsfiddle : http://jsfiddle.net/toddmotto/53Xuk/ <div ...

The Node function is failing to produce a JSON object as expected

This particular file in my library is named verifyToken.js require('dotenv').config(); const CognitoExpress = require("cognito-express"); //Initializing the CognitoExpress constructor const cognitoExpress = new CognitoExpress({ cognitoUserP ...