Utilizing MVC architecture and AJAX for seamless form submission

Recently, I delved into exploring MVC on the client side using JavaScript (JavaScript MVC). While everything seemed promising at first, I hit a roadblock when it came to form submissions. The View part couldn't handle it easily. The event is attached in the Controller, which makes it a suitable place for validating form data. However, I'm hesitant about letting my Controller know the specific server address for form submission. It would be ideal to have a method in the Model, but then I don't want the Model to be aware of the Form structure (which is essentially HTML).

I find myself questioning my understanding of the MVC concept. I'm also reluctant to serialize the form in the Controller and pass it as a parameter to the Model. As of now, the only solution that comes to mind to keep the Model independent is to create a JavaScript structure (entity) that the Controller fills based on form data and passes it to the Model method for saving on the server. Here's a simplified snippet of code:

Info = {
    name,
    address,
    // 15 more properties
    ...
}

InfoController = {
    ...
    onFormSubmit: function() {
       ... 
       info.name = document.getElementById("info-name").value;
       info.adress = document.getElementById("info-address").value;
       ...
       InfoModel.save( info );
    }
}

InfoModel = {
    ...
    save: function( info ) {
        // here some code to setialize info object 
        // send it to server
        ...
    }
}

However, this approach seems to complicate my code compared to simply serializing the form with some third-party frameworks and sending it. What would be the right choice in this scenario?

Answer №1

It's interesting how I ended up answering my own question. To summarize - yes, my initial assumptions were correct ;) After exploring JavaScriptMVC, I discovered a simple solution that I had overlooked before. By creating a basic function to generate a JavaScript object based on a form (using their formParams function), I was able to streamline my controller:

InfoController = {
    ...
    onFormSubmit: function() {
       ... 
       var info = $infoForm.formParams();
       InfoModel.save( info );
    }
}

This approach has simplified the complexity of my code by centralizing the knowledge of data saving within the model. This includes handling validation, defining the URL for data submission, managing client-side storage, triggering events for new creations, and any other specific requirements tailored to our application. Plus, if I ever need to replicate this functionality in another section of my code, I can do so without duplication. Additionally, it is not tied to any specific presentation format (whether it be a form, input fields, wizard, etc.), making the Model highly reusable.

Prior to adopting this methodology, we had a similar concept in place, but it lacked the structured organization that is now present across different interfaces in my application that utilize JavaScript.

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

Using MongoDB map-reduce with Node.js: Incorporating intricate modules (along with their dependencies) into scopeObj

I am currently immersed in developing a complex map-reduce process for a mongodb database. To make the code more manageable, I have organized some intricate sections into modules that are then integrated into my map/reduce/finalize functions through my sco ...

What is the best way to ensure that navigation takes up the full width of the screen in pixels when

Trying to use jQuery to set a specific pixel width for my Bootstrap navbar that spans the entire width of the browser window. However, encountering some bugs as the width needs to be recalculated whenever the browser is resized. Currently, I have this cod ...

The "if" statement carries out the identical action each time it is executed

Despite my efforts to toggle the value of the turn variable every time the if statement runs, I keep encountering the same outcome. It appears that turn consistently evaluates as 2. Below is the code snippet in question: $(function() { var turn = 2; ...

Is it possible to remove individual items from a FlatList by clicking on them and updating the state?

I have a FlatList displaying items from an array called data. My goal is to remove each item individually by clicking on it, but currently when I click on one item, all items are deleted at once. Any suggestions on how to address this issue? Here's ...

Tips for incorporating ajax to load a new webpage into a specific div container

I have a website with two pages. I want to load Page 2 into a div on Page 1 and then display Page 2 when clicked on. I'm attempting to implement the following code, but it doesn't seem to be working for me. As a beginner, I apologize if this is a ...

When attempting to navigate to a new route with a query, I encounter the error message "NavigationDuplicated: Avoided redundant navigation to current location."

I'm facing an issue with my navigation header setup. It includes a search bar that redirects users to the home view with the search query as a parameter. Here's the code snippet for reference: <template lang="html"> <div cl ...

Disregard keys with null values when making a post request using react and axios

As a beginner in JavaScript, I am facing an issue where I do not want to include keys with null values when sending metadata. For example, I should only send the filepath as it has a value, and omit tags and owner which are null. How can I achieve this? ...

How do I resolve the jQuery error "unable to find function url.indexOf" when working with Vide?

I had previously asked a question regarding the use of the Vide plugin for playing background videos on my website, which can be found here. However, I am now encountering an error that is puzzling me: https://i.stack.imgur.com/UDFuU.png I am unsure abo ...

Having Trouble with Typescript Modules? Module Not Found Error Arising Due to Source Location Mismatch?

I have recently developed and released a Typescript package, serving as an SDK for my API. This was a new endeavor for me, and I heavily relied on third-party tools to assist in this process. However, upon installation from NPM, the package does not functi ...

Is it possible to invoke a helper function in Node.js from within a callback?

I recently started programming with node.js and I am encountering an error that I can't quite figure out. The function appears to be correctly set up, and I don't believe there are any asynchronous issues because of the self variable I have in pl ...

Save form data as a serialized post within a colorbox

I'm currently facing an issue with serializing form data from a form within color-box. While I am able to submit the form, the form data doesn't seem to be included. Below is the script I have been using in an attempt to retrieve the form data: ...

Mastering the art of constantly monitoring data changes in a Firebase real-time database using Vue.js

I am currently utilizing vue.js version 2 in CDN mode. I have designed 2 vue components - one that pushes data to a database and another that displays it. Here is the code snippet: firebase.database().ref().on('value', function (data) { c ...

The console logs indicate success for every call, but unfortunately Twitter is not displaying the retweets

Hey there! I'm having some trouble with calling a function and it's not working as expected. var T = new Twit(config); var retweet = function() { T.get('search/tweets', {q:'#python3, #nodejs, python3, nodejs,', count :5 }, f ...

Issue with req.user being Undefined in Node, Express, Passport, and Mongoose

I've encountered an issue where req.user is defined when logging in, but undefined on other paths. I'm starting to feel stuck and out of ideas at this point. Another thing is that deserialization is never being called. server.js: var LocalStra ...

"Regarding compatibility with different browsers - IE8, Firefox3.6, and Chrome: An inquiry on

Snippet of JavaScript Code: var httprequest = new XMLHttpRequest(); var time = new Date(); if (httprequest) { httprequest.onreadystatechange = function () { if (httprequest.readyState == 4) { alert("OK"); } }; httprequest.open("GET", ...

Executing a NodeJS function from a JavaScript function

I am working on a project involving Firebase and I am looking to connect a server-side function that can send an email to the client-side script. Below is my server-side index.js file: const functions = require('firebase-functions'); var nodema ...

Adjust size of item within grid component in VueJS

I have a grid container with cells and a draggable item in a Vue project. I am trying to figure out how to resize the box inside the grid component (refer to images). https://i.stack.imgur.com/q4MKZ.png This is my current grid setup, and I would like the ...

Tips for preventing duplicate properties in Material UI when using React JS

Incorporating components from Material-UI, I have designed a form where the state of inputs is controlled by the parent component. However, I encountered an error stating "No duplicate props allowed" due to having multiple onChange parameters. Is there a w ...

While attempting to scrape data, the console.log function displays the information, however it is not being returned

This code is now working perfectly! However, I am struggling to organize the data into an array of separate objects. getGAS: function(url) { var self=this; rp(options) .then(($) => { let gasset = []; $('.stations-list').each(functio ...

Retrieving input field values in JS/Ajax without needing to refresh the page or click a button

Currently, I have set up a JavaScript function that submits data without refreshing the page or requiring a button click. The input field is located within tab #2 and triggers the JS function when the user stops typing. However, the issue arises when the ...