Sunday, June 28, 2026

Data save in sql server table using Java Script

 JavaScript running in a browser cannot directly insert records into a SQL Server database for security reasons. The correct architecture is:

HTML Form → JavaScript → Server-side API (ASP.NET, PHP, Node.js, Java, etc.) → SQL Server

If you want to learn the process, here is a complete example using HTML, JavaScript, and an ASP.NET Web API.

Step 1: HTML Page

<!DOCTYPE html>
<html>
<head>
<title>Insert Record</title>
</head>
<body>

<h2>Student Registration</h2>

Name :
<input type="text" id="txtName"><br><br>

Email :
<input type="text" id="txtEmail"><br><br>

<input type="button" value="Save" onclick="saveData()">

<p id="msg"></p>

<script>
function saveData() {

var name = document.getElementById("txtName").value;
var email = document.getElementById("txtEmail").value;

if(name=="" || email=="")
{
alert("Please fill all fields.");
return;
}

fetch("https://localhost:5001/api/student", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
Name: name,
Email: email
})
})
.then(response => response.text())
.then(data => {
document.getElementById("msg").innerHTML = data;
})
.catch(error => {
console.log(error);
});

}
</script>

</body>
</html>

Step 2: SQL Server Table

CREATE TABLE Student
(
Id INT IDENTITY(1,1) PRIMARY KEY,
Name VARCHAR(100),
Email VARCHAR(100)
)

Step 3: ASP.NET C# API

[HttpPost]
public string Post(Student s)
{
SqlConnection con = new SqlConnection(
"Server=.;Database=CollegeDB;Trusted_Connection=True;");

con.Open();

SqlCommand cmd = new SqlCommand(
"INSERT INTO Student(Name,Email) VALUES(@Name,@Email)", con);

cmd.Parameters.AddWithValue("@Name", s.Name);
cmd.Parameters.AddWithValue("@Email", s.Email);

cmd.ExecuteNonQuery();

con.Close();

return "Record Saved Successfully";
}

Data Flow

HTML TextBox


JavaScript
(fetch API)


ASP.NET Web API


SQL Server Database

Important Note

❌ This is not possible:

// JavaScript cannot connect directly to SQL Server
var con = new SqlConnection(...);

Browsers do not allow direct database connections because it would expose your database credentials to anyone using the website.

If you are teaching Web Technology, I can also provide a complete CRUD (Insert, Update, Delete, Select) project using:

  • HTML
  • CSS
  • JavaScript
  • ASP.NET Web API
  • SQL Server

with source code and database scripts.

No comments:

Post a Comment

Data Transfer Java Script using Local Storage

  Page 1: index.html <!DOCTYPE html> <html> <head> <title> Page 1 </title> </head> <body> ...