Store transient information in JSON

Struggling with incorporating JSON into my project! I'm aiming to track user changes and save them to a SQL database using AJAX and PHP later on. Initially, I want to structure all user modifications in a JSON object before finalizing the process.

I'm relatively new to JSON and facing difficulties consolidating results into a single large object for server transfer upon user confirmation. Need help with the coding aspect – particularly unsure if JSON is the optimal approach for temporary storage.

A snippet of what I've done so far:

HTML

<div class="button" data-info='2' data-id='8-7' onclick=addDeskid(e)></div>
<div class="button" data-info='4' data-id='2-5' onclick=remDeskId()></div>
<div class="button" value="submit">submit</div>

JS

function addDeskId(e){
    $adjustment;
    userObject = $(this); 
    userObjectChange = 'CHANGE_SEAT_TO'; //Determines SQL statement via AJAX and PHP
    userObjectID = userObject.attr('data-info'); 
    userObjectDeskID = userObject.attr('data-id');
    userObjectSeatID = 9-4; 

    var addUserObject = new jsonAddTest(userObjectID, userObjectChange, userObjectDeskID, userObjectSeatID,);

    //Functionality on the user side

}
function remDeskId(){
    userObject = $dropObject.find('div.dragTest');
    userObjectChange = 'REMOVESEAT'; 
    userObjectID = userObject.attr('data-info'); 
    userObjectDeskID = userObject.attr('data-id'); 
    userObjectDeskIDVal = 0; 
    
    var remUserObject = new jsonRemTest(userObjectID, userObjectChange, userObjectDeskID, userObjectDeskIDVal);

    //Functionality on the user side
    
}

    //JSON functions test
function jsonRemTest(id, change, name, seat, value){
    this.ID = id;
    this.ChangeType = change;
    this.Name = name;
    this.Seat = seat;
    this.setTo = value;

            userMoves.push(jsonRemTest);

}
function jsonAddTest(id, change, name, desk, seat, previousseat, previousseatnewvalue){
    this.ID = id;
    this.ChangeType = change;
    this.Name = name;
    this.Seat = desk;
    this.setTo = seat;
    this.PreviousSeatValue = previousseat;
    this.PreviousSeatNewValue = previousseatnewvalue;

            userMoves.push(jsonAddTest);

}
console.log(JSON.stringify(userMoves));

Encountering userMoves is undefined error. Seeking guidance on rectifying this issue while combining output from JSON functions into one preparatory object for submission via AJAX/PHP upon clicking submit.

Your insights are highly appreciated.

Answer №1

Alright, let's dive into this with some suggestions.

Firstly, your onclick=addDeskid(e) isn't properly formatted to call your function and it's placed in the markup instead of the code, so let's correct that.

I've made some adjustments to your markup to enhance compatibility with my event handlers by using a class for myAddButton and myRemButton. Feel free to modify it as needed, but I found this approach useful. I also included a button to display the results logged after all events have been triggered. Currently, you're getting [] because there is no data present when it's logged. I haven't made any changes to the submit functionality; it's up to you to handle that (perhaps through an ajax call?).

<div class="button myAddButton" data-info='2' data-id='8-7'>add</div>
<div class="button myRemButton" data-info='4' data-id='2-5'>remove</div>
<div class="button mySubmitButton">submit</div>
<button id="ShowResults" type='button'>ShowResults</button>

Now onto the code - I've refactored this to establish a "class" for the object using makeClass. While there are other approaches, this method allows for creating instance objects when necessary and simplifies namespace management for certain functions. I deliberately added a private function to demonstrate its use along with a public function. Note that inside the function, "this" refers to the instance object, not a global one. (Refer to makeClass with credited authors for more details.)

I defined a "class" with generic attributes. You could opt for separate functions for "add" and "remove" rather than the SetChangeObject function - each addressing a specific action...I chose a generic approach for consistent object signature.

Here's the adjusted code which may seem somewhat contrived in places solely for illustrative purposes:

// makeClass - By Hubert Kauker (MIT Licensed)
// originally by John Resig (MIT Licensed).
function makeClass() {
    var isInternal;
    return function (args) {
        if (this instanceof arguments.callee) {
            if (typeof this.init == "function") {
                this.init.apply(this, isInternal ? args : arguments);
            }
        } else {
            isInternal = true;
            var instance = new arguments.callee(arguments);
            isInternal = false;
            return instance;
        }
    };
}

var SeatGroup = makeClass(); //initialize our class
//method invoked upon creation of a class instance
SeatGroup.prototype.init = function (id, changeType, name, desk, seat, setToValue, previousseat, previousseatnewvalue) {
    // default values
    var defaultSeat = "default";
    var defaultName = "default";

    this.ID = id;
    this.ChangeType = changeType;
    this.Name = name ? name : defaultName;
    this.Desk = desk ? desk : "";
    this.Seat = seat ? seat : privateFunction(defaultSeat);;
    this.SetTo = setToValue ? setToValue : this.ID;
    this.PreviousSeatValue = previousseat ? previousseat : "";
    this.PreviousSeatNewValue = previousseatnewvalue ? previousseatnewvalue : "";

    this.changeObject = {};

    //public method
    this.SetChangeObject = function () {
        this.changeObject.ID = this.ID;
        this.changeObject.ChangeType = this.ChangeType;
        this.changeObject.Name = this.Name;
        this.changeObject.Seat = this.Seat;
        this.changeObject.Desk = this.Desk;
        this.changeObject.SetTo = this.SetTo;
        this.changeObject.PreviousSeatValue = this.PreviousSeatValue;
        this.changeObject.PreviousSeatNewValue = this.PreviousSeatNewValue;
    };

    function privateFunction(name) {
        return name + "Seat";
    }
};
var userMoves = [];//global warning-global object!!

//event handlers
$('.myAddButton').on('click', addDeskId);
$('.myRemButton').on('click', remDeskId);
$('#ShowResults').on('click', function () {
    console.log(JSON.stringify(userMoves));//log this after all are pushed
});

//function called on "add", can be customized
function addDeskId(e) {
    var uo = $(this);//jQuery object of the "myAddButton" element
    var userObjectChange = 'CHANGE_SEAT_TO';
    var userObjectID = uo.data('info');
    var userObjectDeskID = uo.data('id');
    var userObjectSeatID = '9-4';
    //create a private instance of our class (invokes init function)
    var uChange = SeatGroup(userObjectID, userObjectChange, userObjectDeskID, userObjectSeatID);
    uChange.SetChangeObject();//invoke public function
    //display what we created
    console.dir(uChange.changeObject);
    //this doesn't work, it's private:  console.log(  uChange.privateFunction('hi'));
    //push to our global
    userMoves.push(uChange.changeObject);
}

//event function, customize as required
function remDeskId() {
    var userObject = $(this);
    var userObjectChange = 'REMOVESEAT';
    var userObjectID = userObject.data('info');//use jQuery data attribute for ease
    var userObjectDeskID = userObject.data('id');
    var userObjectDeskIDVal = 0;
    var remUserObject = SeatGroup(userObjectID, userObjectChange, userObjectDeskID);
    remUserObject.PreviousSeatValue = "FreddySeat";//demonstrating setting an object property
    remUserObject.SetChangeObject();//invoke public function
    console.dir(remUserObject.changeObject);
    userMoves.push(remUserObject.changeObject);
}

Experiment with it here: http://jsfiddle.net/q43cp0vd/2/

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

Is it possible to utilize JSX independently of React for embedding HTML within a script?

Is it possible to incorporate inline HTML within a script using a library such as jsx? <script src="jsx-transform.js"></script> <script type="text/jsx"> define('component', function () { return (<div>test html code< ...

What is the process for transferring data between components in React?

Currently, I have set up a system to display an employee table from the database. Each record in the table includes an "edit" link which, when clicked, should trigger the display of a form below the table containing the corresponding records for editing. T ...

"Enhancing user experience with Ajax by dynamically loading diverse content via

My goal is to change the URL in the address bar and add a class to the anchor tag when clicking on a tab. I came across a great example on jsfiddle that someone shared on stackoverflow. http://jsfiddle.net/VcQKr/2/ The issue I'm facing is that while ...

Element dynamically targeted

Here is the jQuery code I currently have: $('.class-name').each(function() { $(this).parent().prepend(this); }); While this code successfully targets .class-name elements on page load, I am looking to extend its functionality to also target ...

Utilizing Node.js (Express) to import a JSON file from StackExchange and display the data

I've been working on a task to retrieve a json file from the stackexchange api and store it on the client side once the server loads, allowing me to make local changes to it. Despite my efforts, the page just continues loading without any results. He ...

Is it possible to dynamically import a Vue.js component based on a prop value?

Currently, I am utilizing the Material design Icons library specifically made for Vue.js. In this library, each icon is a standalone file component within its designated folder. Within my project, I have a separate component called ToolbarButton, which in ...

implementing a method event within a JavaScript class

Within the wapp.js file, there is a JavaScript class defined as follows: function Wapp() { this.page = function($page_name) { this.onLoad = function($response) { } } this.navigate = { changePage: function(link) { ...

Determining when a function is triggered from the JavaScript console

Is there a way to conceal a function in JavaScript console so that it's inaccessible for calling? Let me give you some context - let's say I have a JavaScript function that adds records to a database using Ajax. The issue is, anyone can call thi ...

Error: Unable to locate script file with npm installation of AngularJS

After installing Angular using npm, I added the following script to my public/index.html file: <script src="/node_modules/angular/angular.js"></script> However, I am encountering a 404 error in the Chrome console. Does anyone have any suggest ...

What is the best way to deploy a REST API utilizing an imported array of JavaScript objects?

I have been using the instructions from this helpful article to deploy a Node REST API on AWS, but I've encountered a problem. In my serverless.yml file, I have set up the configuration for the AWS REST API and DynamoDB table. plugins: - serverless ...

"Encountering Issues with Angular's Modules and EntryComponents during Lazy Loading

Upon lazy loading an Angular module, I encountered an issue when trying to open my DatesModal that resulted in the following error: No component factory found for DatesModal. Have you included it in @NgModule.entryComponents? The declaration and entryCom ...

Using jQuery to retrieve the TD value

I'm attempting to retrieve the TD value using the Value attribute.... Let's say I have the following HTML markup: <td nowrap="nowrap" value="FO2180TL" class="colPadding" id="salesOrderNumber1">bla bla </td> So, I tried this- v ...

What is the best method to extract the values of objects in an array that share

var data= [{tharea: "Rare Disease", value: 3405220}, {tharea: "Rare Disease", value: 1108620}, {tharea: "Rare Disease", value: 9964980}, {tharea: "Rare Disease", value: 3881360}, ...

Displaying image alt text on hover using pure JavaScript

Is there a way to hover over images on my webpage and display their alt text using vanilla javascript, without relying on jQuery? Here is the code for my images: <a href="<?php echo $displayData['href']; ?>" class="group"> <d ...

Preventing Unauthorized Access: Redirecting to Login Page in Vue.js

Here is the code snippet I'm working with: <script> export default{ props:['idStore'], methods:{ addFavoriteStore(event){ $(function () { $(document).ajaxError(functi ...

Experiencing varying outcomes from a single form in Laravel

I am attempting to build an ajax form with Laravel. The interface consists of a table displaying names with buttons next to each name that are enclosed within forms to trigger certain actions. Below is the HTML code: <div style="margin-top: 100px;"> ...

What is the best way to utilize the node.js module passport-google?

I'm currently working on a node.js web application that prompts users to sign in using their Gmail account. While following instructions provided at this website, I modified the URL from www.example.com to localhost and launched the application. Howev ...

Simplify JSON sideloading with RestKit without the need for CoreData

Trying to configure RestKit to incorporate sideloaded associations from JSON data. The structure of the JSON is as follows: { "companies": [ { "id": 1, "name": "420...", "street": "420 Kush St.", ...

Transferring a large object to a child process in Node.js can lead to slow performance

My scenario involves making multiple REST API calls from my node server to various public APIs. The responses can vary in size, with some being large and others small. To handle this, I need to convert the response JSON into a string. However, I am aware t ...

django leaflet - dynamically adjusting controls on HTML page with the click of a button

Presently, I am utilizing django-leaflet along with leaflet-draw controls. My goal is to make the draw controls accessible (and add them to the map) based on a specific event, such as toggling a button. Below is a basic jQuery structure that I currently h ...