Save to a JSON file

Hey there, I'm having some trouble with pushing a temporary value to a JSON file using the command "MyJSON.name.push". It keeps giving me an error saying "Undefined is not an object". I've tried different approaches and using JavaScript arrays works fine, but I specifically need to do this on an external JSON file. The error only seems to occur when I click a certain button. Can anyone help me out? Thank you.

<!DOCTYPE html>
<html>

<head>

    <title>SSL Checker</title;
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <script type="text/javascript" src="js/script.js"></script>
    <script type="text/javascript" src="js/json.json" charset="utf-8"></script>
</head>

<body onLoad="start()">
    <div id="title">
        <h1>SSL Checker</h1>
    </div>
    <div id="data">
        <form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
            <input type="text" id="add-name" placeholder="Name"></input>
            <input type="text" id="add-link" placeholder="Link"></input>
            <input type="submit" value="Add">
        </form>

        <div id="edit" role="aria-hidden">
            <form action="javascript:void(0);" method="POST" id="saveEdit">
                <input type="text" id="edit-name">
                <input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">&#10006;</a>
            </form>
        </div>
        <p id="counter"></p>
    </div>
    <div id="table">
        <table style="overflow-x:auto;">
            <tr>
                <th>Sites:</th>
            </tr>
            <tbody id="urls">
            </tbody>
        </table>
    </div>
</body>


</html>

Javascript:

function start() {
var SSL = new function() {
            //List urls to check
            this.el = document.getElementById('urls');
            this.Count = function(data) {
                var el = document.getElementById('counter');
                var name = 'url';

                if (data) {
                    if (data > 1) {
                        name = 'urls';
                    }
                    el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
                } else {
                    el.innerHTML = 'No ' + name;
                }
            };
            //Buttons configuration
            this.FetchAll = function() {
                var data= '';

                if (MyJSON.length > 0) {
                    for (i = 0; i < MyJSON.length; i++) {
                        data += '<tr>';
                        data += '<td><a href="' + MyJSON[i].url + '">' + MyJSON[i].name+ '</a></td>';
                        data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
                        data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
                        data += '</tr>';

                    }
                }

                this.Count(MyJSON.length);
                return this.el.innerHTML = data;
            };
            //Add name
             this.Add = function() {
            el = document.getElementById('add-name');
            el1 = document.getElementById('add-link')
            var url = el.value;
            var url1 = el1.value;
            if (url) {
                if (url) MyJSON.push('{name:"url",url:"url1"}')
                el.value = '';
                this.FetchAll();
            }
        }                
            //Edit
            this.Edit = function(item) {
                var el = document.getElementById('edit-name');
                el.value = MyJSON.name[item];
                document.getElementById('edit').style.display = 'block';
                self = this;
                document.getElementById('saveEdit').onsubmit = function() {
                    var url = el.value;
                    if (url) {
                        self.name.splice(item, 1, url.trim());
                        self.FetchAll();
                        CloseInput();
                    }
                }
            }; 
           //Delete
            this.Delete = function(item) {
                MyJSON.urls.splice(item, 1);
                this.FetchAll();
            };

    };

    SSL.FetchAll();

    function CloseInput() {
        document.getElementById('edit').style.display = 'none';
    }
    window.SSL= SSL;
}

JSON FILE(json.json):

var MyJSON = [{
        name:"Google",
        url: 'google.es',
    },
    {
        name:"Yahoo",
        url: 'yahoo.com',
    }
]

Answer №1

Revamp your this.Add() method with the following adjustments:

this.Add = function() {
        element = document.getElementById('add-name');
        element1 = document.getElementById('add-link')
        var link = element.value;
        var link1 = element1.value;
        if (link) {
            MyData.push({"name":link,"url":link1})
            element.value = '';
            this.FetchAll();
        }
    }

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

Error in Chrome Extension Data Type

I am having trouble adding a highlighted red button to YouTube. The code does not seem to be working as expected. manifest.json { "name": "Example", "version": "0.0", "manifest_version": 2, "c ...

The functionality of linear mode seems to be malfunctioning when using separate components in the mat-horizontal-stepper

In an effort to break down the components of each step in mat-horizontal-stepper, I have included the following HTML code. <mat-horizontal-stepper [linear]="true" #stepper> <mat-step [stepControl]="selectAdvType"> <ng-template matStep ...

I am unable to implement code coverage for Cypress in Debian at the moment

Having trouble obtaining code coverage results using Cypress in my Virtual Machine (Debian Bullseye), but no issues when I run the same project on my Windows machine. On Linux, the code coverage shows up as: Click here to view Index.html inside lcov-repor ...

Convert a two-column layout on the web into a single-column layout for mobile devices, featuring dynamic

Is there a way to style this diagram with CSS that will work on IE11 and all major browsers? It seems like Flexbox doesn't support dynamic height. Do I need separate left and right columns for larger viewports and no columns for smaller viewports? ...

Tips for customizing the appearance of a child component using the parent component in Vue.js

I am working on creating a layout using Vuejs and flexbox that includes elements like 'header, sidebar, main-content, sidebar, footer'. I have separated each part of the layout into individual .vue files, such as header.vue and sidebar.vue. In ...

Error: The term "Worker" is undefined in a new Nextjs project

I'm currently looking into an issue where I am attempting to import a webpacked javascript file into a NextJS project that utilizes Worker, but I keep encountering the error message ReferenceError: Worker is not defined. I've simplified it down t ...

Is there a way to easily identify the error in my Express application that is preventing my hbs template from running properly?

I am facing an issue with my express code where it is not rendering the data properly. Can someone please assist me in resolving this error? Your help will be greatly appreciated! let express=require('express'); let app=express(); ...

What is the best way to handle returning a promise when outside of the scope?

I am currently working on retrieving multiple files asynchronously from AWS S3 by utilizing Promises in my code. Although I'm using AWS S3 for fetching the files, there seems to be an issue with fulfilling the promises as it's out of scope and c ...

Exploring SubjectBehavior within my UserService and Profile Component

Within my ShareService, I have the following code snippet: isLogin$:BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false); <==== default value is false CheckUser = this.isLogin$.asObservable(); public isLogin (bool){ ...

Unable to retrieve file path from image selection in JavaScript by clicking on a button

I am trying to create a simple browsing feature that only accepts images. However, after clicking the button, I am unable to retrieve the full path in JavaScript. All I can get is the filename. JavaScript <script type="text/javascript"> functio ...

What is the syntax for accessing an element within an array in a function?

This code snippet retrieves an array of users stored in a Firestore database. Each document in the collection corresponds to a user and has a unique ID. const [user] = useAuthState(auth); const [userData, setUserData] = useState([]); const usersColl ...

The jQuery function for AJAX does not properly validate the boolean value provided by the controller

I have a controller action that returns a boolean result to jQuery. [HttpGet] public ActionResult IsVoucherValid(string voucherCode) { bool result = false; var voucher = new VoucherCode(voucherCode); if(voucher.Status==0) ...

What is the best way to declare module variables in a Node.js environment?

When it comes to declaring variables when requiring modules in nodejs, there are different styles followed by well-known developers. For instance, TJ Holowaychuk uses a style like this: (method1) var connect = require('connect') , Router = req ...

Clarifying the confusion surrounding AngularJS $q, promises, and assignments

Curious about a particular behavior I'm witnessing. Unsure if there's a misunderstanding on my part regarding promises, JavaScript, or Angular. Here's what's happening (I've prepared a plnkr to demonstrate - http://plnkr.co/edit/ZK ...

The AJAX request encountered an error due to an Unexpected End of JSON Input

My AJAX code is encountering an error message. parsererror (index):75 SyntaxError: Unexpected end of JSON input at parse (<anonymous>) at Nb (jquery.min.js:4) at A (jquery.min.js:4) at XMLHttpRequest.<anonymous> (jquery.min.js: ...

What is the reason for using 'app' as the top-level directory name in React Native import statements within a project setting?

Seeking to comprehend the imports within React Native source code, specifically in a file named questionnaire.actions.js, relative to the top-level directory called lucy-app: ./src/containers/newUserOnboarding/questionnaire/questionnaire.actions.js The m ...

Tips for sending a callback function in Angular following an HTTP request

Currently, I am leveraging an angular controller to make an http post request to my express route. Subsequently, data is dispatched to my Gmail client via nodemailer. Although the $http request functions properly and emails can be received in my Gmail acco ...

Hiding a Component: Achieving Smooth Behavior with Timer and onPress

My goal is to create a user interface where tapping the screen displays a <TouchableWithoutFeedback> component, which should automatically disappear after 4 seconds. Additionally, I want the user to be able to tap on the displayed component to hide ...

Guide on accessing js file in an Angular application

I have a component where I need to create a function that can search for a specific string value in the provided JavaScript file. How can I achieve this? The file path is '../../../assets/beacons.js' (relative to my component) and it's named ...

Troubleshooting issue with applying hover effect to child divs

How come when I hover over one of the child items in my parentDiv, the background of the last childDiv changes no matter which child I place my mouse on? for (let i = 0; i < Number(height); i++) { for (let j = 0; j < Number(width); j++ ...