Guide for establishing a MySQL database connection within a Knockout.js javascript file

I've set up a table in MYSQL and created a file in Knockout.js. The goal is to store the data entered into Knockout.js through the variable "pf" in the table named "PORTFOLIO". I want to establish the database connection using JavaScript. I attempted to connect MYSQL and Knockout.js but faced difficulties. Seeking assistance on this matter.

 //TABLE
CREATE TABLE PORTFOLIO
  (
  ID INT NOT NULL,
  pf VARCHAR (255)
  );

File in Knockout.js

//View
    <h3>Portfolio</h3>
<form data-bind="submit: addpf">
Add Portfolio: <input data-bind="value: newpf" placeholder="Who needs to be added?" />
    <button type="submit">Add</button>
</form>

<ul data-bind="foreach: pf, visible: pf().length > 0">
    <li>
        <input type="checkbox" data-bind="checked: isDone" />
        <input data-bind="value: title, disable: isDone" />
        <a href="#" data-bind="click: $parent.removepf">Delete</a>
    </li> 
</ul>

You have <b data-bind="text: oldpf().length">&nbsp;</b> New Portfolios
<span data-bind="visible:  oldpf().length == 0"></span>


//ViewModel


function pf(data) {
        this.title = ko.observable(data.title);
        this.isDone = ko.observable(data.isDone);
    }

    function pfListViewModel() {
        // Data
        var self = this;
        self.pf = ko.observableArray([]);
        self.newpf = ko.observable();
        self.oldpf = ko.computed(function() {
            return ko.utils.arrayFilter(self.pf(), function(pf) { return !pf.isDone() });
        });

        // Operations
        self.addpf = function() {
            self.pf.push(new pf({ title: this.newpf() }));
            self.newpf("");

        };
        self.removepf = function(pf) { self.pf.remove(pf) };
    }

    ko.applyBindings(new pfListViewModel());

Answer №1

Unfortunately, direct connection between JavaScript and MySQL is not possible. However, by combining JS with PHP or another server side language, you can achieve this functionality.

Since JavaScript is a client-side language while MySQL runs on a server, you need a server side language to facilitate communication between them. This is where AJAX comes in handy for submitting data to the server.

Answer №2

If you're looking for another option, consider using BreezeJs. This will allow you to create a Data-centric Application with more freedom. Check out this link for more information: . Breeze is compatible and works seamlessly with knockoutJs.

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

Typescript: Securing Data with the Crypto Module

I am currently working on encrypting a password using the built-in crypto module. Previously, I used createCipher which is now deprecated. I am wondering if there is still an effective way to achieve this. Here is the old code snippet: hashPassword(pass: ...

Is there a way to append items to the main level of an array?

I am attempting to populate an array with objects in order to achieve the following structure: myobject1: Object: ItemInside: Object myobject2: Object ItemInside: Object myobject3: Object ItemInside: Object myobject4: Object ItemInside: Ob ...

jQuery UI dynamically adjusting content layout based on browser size changes

Having an issue with my custom accordion script where resizing the browser causes formatting problems in one of the sections. I want the content to remain intact and to utilize a scrollbar if necessary to view the content. The problem is visible in section ...

What are the necessary conditions for executing npm start?

I'm encountering issues running npm start in my project, which is linked to my package.json file below: { "name": "babek", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test speci ...

Insert an icon at the conclusion of a truncated multi-line text without causing a line break

I have a specific requirement where I am looking to present two lines of text, followed by an icon displayed through an img tag. If the text exceeds two lines, I want to display an ellipsis. However, it is crucial that the icon remains inline with the text ...

What is the best way to transmit a 500x500 2D Integer Array using Websockets?

I'm encountering an issue where I believe it may be too time-consuming to JSON.stringify and send data to each individual user. For example, if 4 people connect at the same time, the server will become stalled during array parsing, resulting in signif ...

Initiating Jquery UI dialog without proper initialization

EDIT 3: I mentioned earlier that my goal is to set up the dialog in the header and then be able to use it on any page within the body. It currently works fine if I initialize it right before calling it, but this requires initializing it each time. I want t ...

Can you explain the meanings of ?. and ?? in JavaScript?

Can anyone explain the significance of ?. and ?? in the following code snippet? history.replace(location.state?.redirectPath ?? '/home') ...

Injecting dependencies in AngularJS when utilizing the controller-as syntax: A how-to guide

As I dive into the controller-as feature outlined in the documentation, I'm refining one of my controllers to align with their recommended syntax. However, I'm facing a challenge when it comes to injecting the $http service into my search() funct ...

"IOS exclusive: Encounter INVALID_STATE_ERROR on IOS devices only, not on Android, OSX, or Windows platforms

While developing an HTML5 web page with audio functionality using JavaScript, I encountered an issue. Initially, the basic version of my webpage successfully loaded and played audio files in different formats (e.g., ogg vs mp3) across various OS/browser co ...

If the column in Mysql contains a specific value, ensure that the date column is set to a specified date

Is there a way to create a select statement that gets all the rows from a table where a specific column has a value of 'y' only on a certain date? In other words, I want to retrieve data based on both the column value and the date it was recorde ...

Is it possible to conceal a form field until a previous field has been completed?

Looking for a way to hide a form field until another field is properly completed? I have a divided registration form and want the second field to appear only when the first one is valid. Preferably using CSS3, with HTML5 and maybe some JavaScript if necess ...

When ReactJS invokes a function twice within a child component, it does not successfully update the parent state twice

Dealing with an issue where I need to save data from a specific fieldset using default values on componentDidMount(). The data saving process takes place in the parent component after it is passed up from the child component. However, due to React's ...

Steer clear of making changes to a JavaScript array

Here is my code snippet: let traces = { ref: null, min: null, max: null, avg: null }; let learning = { "Application": "b3", "t": [ { "d": 2, "BinaryType": "Current" }, { "d": 3, ...

What might be causing the hasOwnProperty(key) method in JSON to return false?

I have successfully implemented a method to loop through the JSON data provided below: {"dummmysetsJSONArr":[{"entryID":"1","distance":"100","calories":"50"},{"entryID":"2","distance":"200","calories":"100"},{"entryID":"3","distance":"300","calories":"150 ...

Instructions for navigating to the dashboard component page in vue js after a successful login process within the login component

Greetings! I am currently working on setting up routing for my login component page to redirect to the dashboard component upon successful login. I have managed to receive responses from my local API with status codes 400 and 200 but I am unsure how to h ...

Troubleshooting a timeout error when attempting to save an entity in a large table using JPA repository

Currently utilizing JPA repository. Attempting to save an entity in a MySQL table with 100,000 records. Upon executing FraisProvision fraisProv = new FraisProvision(); ... fraisProvisionRepository.save(fraisProv); An error is encountered ` Caused ...

Utilizing recursive AJAX requests and halting execution at a specified condition

After hours of searching and attempting, I am struggling as a beginner with ajax concepts. Here is my issue: 1. I have a page that retrieves the current date's data from the database, so I am using an ajax function recursively with a setTimeout of 10 ...

Is there a navigation feature in VueJS that functions similarly to React Router?

I am currently working on enhancing the navigation experience of an existing vueJS application that utilizes Vue Router. When working with React, I typically structure breadcrumbs in the following manner: <Breadcrumbs> <Route path="/users&q ...

Guide on obtaining the file path of an uploaded file through the use of HTML, JavaScript, and PHP

After successfully uploading an image from my drive, I am encountering an issue where I am unable to locate the folder path of that image For example: C:\Images\Logo\Image.png $('#pngfile').change(function (e) { var tmppath = URL ...