Parsing JSON stored in local storage and converting it to a Fabric JS object - JSON generated from form inputs

Currently, I am facing some challenges while using Fabric js for a project that I am working on. My main goal is to create a form where users can input details, which will then be converted into a JSON object and stored locally.

After submitting the form, the user is redirected to a new page where the JSON data is retrieved and objects are generated.

The issue arises during the object creation process. While transforming the form information into JSON works fine, the resulting object only appears as a simple border with corners on the canvas. It lacks other attributes like size and color. This might be due to how the JSON data is being deserialized. Despite my efforts to find a solution, I have not been successful yet. Any assistance would be greatly appreciated.

Here's a snippet of sample code showcasing the creation of an object:

var a = {
    type: "rect",
    left:200,
    top:110,
    fill:'red',
    width:80,
    height:50
};

A comparison between creating an object directly and retrieving it from local storage:

[Log] From JSON: {"type":"rect","top":"110","left":"200","fill":"red","height":"50","width":"80"} (sim.html, line 135)

To retrieve the data, I am using the following script:

var test = localStorage.getItem("Number1");
console.log("From JSON: " +test);

var obj = JSON && JSON.parse(test) || $.parseJSON(test);
console.log(obj.type +"-"+ obj.left);

Although adding 'a' in the method below works correctly, 'obj' does not behave as expected. The key difference seems to be in the quotations, but I am unsure if this is the root cause or how to address it effectively.

Below is the function used to iterate over and render objects:

    fabric.util.enlivenObjects([circle1, obj], function(objects) {
    var origRenderOnAddRemove = canvas.renderOnAddRemove;
    canvas.renderOnAddRemove = false;

    objects.forEach(function(o) {
        canvas.add(o);
    });
    canvas.renderOnAddRemove = origRenderOnAddRemove;
    canvas.renderAll();
});

I appreciate any assistance provided. Thank you.

Answer №1

In order to enhance your "serialize" function, consider adding a feature that automatically converts certain inputs to numbers:

$.fn.serializeObject = function() {
    var obj = {};
    var arr = this.serializeArray();
    $.each(arr, function() {
        var val = this.value || '';
        if (/^\d+$/.test(val))
          val = +val;

        if (obj[this.name] !== undefined) {
            if (!obj[this.name].push) {
                obj[this.name] = [obj[this.name]];
            }
            obj[this.name].push(val);
        } else {
            obj[this.name] = val;
       }
    }} );
    return obj;
};

This function identifies input values that resemble numbers and changes them accordingly. It currently only handles integers; for decimal numbers, you could adjust the regular expression.

While this approach may not cover all scenarios, as it relies on an assumption, for greater precision, consider assigning a class to relevant form inputs, distinguishing them as numeric. Then, create a custom serializer to process all inputs more accurately.

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

Tips for stopping a click from going through a fixed element to the one in the background

My website features a fixed positioned header with a search box, overlaying content below it (thanks to the higher z-index). When I click on the search box, an event handler is triggered. However, the click response also passes through the header to the ...

Angular-ui typeahead feature allows users to search through a predefined

I recently developed a typeahead feature using the angular-ui library. Here is the current HTML for my typeahead: <input name="customers" id="customers" type="text" placeholder="enter a customer" ng-model="selectedCustomer" uib-typeahead="customer.fir ...

Struggling to make Vue.js transition effects function properly?

I'm having trouble getting a vue.js (version 1) transition to work. I copied the code from their official website, but it's not running the javascript console.logs! Vue.transition('fade', { css: false, enter: function ( ...

Tips on avoiding asynchronous issues in NodeJS: Ensure task a is finished before initiating task b

I have a situation where I need to ensure that task B code only executes after task A has completed. Task A involves converting an audio file, while Task B relies on the converted audio for further processing. The issue arises because Task A saves the n ...

What is the reason behind WP AJAX consistently returning a value of 0?

Having trouble retrieving a proper response, as it always returns 0. Here is the JavaScript code in the head section: q = new XMLHttpRequest(); q.open('POST', ajaxUrl); q.onreadystatechange = function () { if (q.readyState === 4) { ...

Extracting the value of an attribute from an XML element and converting it into an HTML unordered list with

Here is an example of an xml file structure: <root> <child_1 entity_id = "1" value="Game" parent_id="0"> <child_2 entity_id="2" value="Activities" parent_id="1"> <child_3 entity_id="3" value="Physical1" parent_id="2"> ...

Guide to Setting Up Bootstrap 4 Beta Using Bower

Trying to update to the newest Bootstrap 4 Beta version via bower. Issue with this command: bower install bootstrap#v4.0.0-beta Getting the error message: no matches found: bootstrap#v4.0.0-beta Is there something incorrect in my process? This is how ...

Using Python with Selenium and JavaScript for Logging in

When using Selenium and Python, I am attempting to log in to a website but encountering difficulties. The issue is that the source code does not display the necessary Id=apple_Id required for sending login information, although it can be seen when inspecti ...

What is the best way to showcase images using Vue.js?

For my Vue project, I am encountering issues with the image paths not working properly. Despite trying different variations, such as: <figure class="workout-image"> <img :src= "images.bicep" width= "200px" ...

Battle between Comet and Ajax polling

I'm looking to develop a chat similar to Facebook's chat feature. Using Comet would require more memory to maintain the connection. There seems to be a latency issue when using Ajax polling if requests are sent every 3-4 seconds. Considering t ...

Issue with smart table sorting functionality

I've been working on a table with just one column that is populated from a string array. However, I'm struggling to get the sorting functionality to work properly. Can anyone pinpoint what mistake I might be making here? Steps taken so far: 1) ...

Determine whether a response is not received within 8 seconds

One of the methods in my Angular component is responsible for returning data Here is a snippet of that method getRecognitionById() { this.loaderService.show(null, true); forkJoin( this.vendorWebApiService.getRecognitionById(this.executiveCh ...

Tips for fading the text of list items when their checkbox is marked as done?

I am trying to figure out how to gray out a list item when its checkbox is checked. The code I currently have takes text input from a textbox and adds it to an unordered list when the add button is clicked. Each list item contains a checkbox within it. My ...

What is the functionality of named function expressions?

After coming across an intriguing example in the book labeled as a "named function expression," I was curious to delve into its mechanics. While the authors mentioned it's not commonly seen, I found it fascinating. The process of declaring the functi ...

The Javascript Switch statement is experiencing some functional issues

I am facing an issue where I need to handle different scenarios based on a decimal value, and I thought of using a Switch/case statement for this purpose. However, the code is not working as expected. Below is the snippet of code in question: var spread ...

What is the best way to stop Quasar dropdown list from moving along with the page scroll?

I am facing an issue with my code while using Quasar (Vue 3.0). The code snippet in question is: <q-select filled v-model="model" :options="options" label="Filled" /> When the drop-down menu is open and I scroll the pag ...

Creating regex to detect the presence of Donorbox EmbedForm in a web page

I am working on creating a Regex rule to validate if a value matches a Donorbox Embed Form. This validation is important to confirm that the user input codes are indeed from Donorbox. Here is an example of a Donorbox EmbedForm: <script src="https: ...

Using regular expressions in Javascript to extract decimal numbers from a string for mathematical operations

I'm currently working on a Vue method where I extract information from a WordPress database. The data retrieved sometimes contains unnecessary text that I want to filter out. Using the prodInfo variable, the input data looks something like this: 2,5k ...

Utilizing single-use bindings for a unique element directive

I'm working on a new directive called <call-card> and I want to implement one-time bindings as an exercise for optimizing future directives. Here is the definition object for this directive: { restrict: 'E', controllerAs: &ap ...

Warning: Attempting to access a property of an invalid object in

I've been diving into PHP recently. I expected it to output 0, but oddly enough I received an error message: Notice: Trying to access property of non-object in... <?php $json = '[{"assetref":"","qty":0,"raw":0}]'; $obj = json_deco ...