Inserting Data in to DB using jQuery Ajax and LINQ to SQL


First create an Employees table that has EmployeeId, name, email and address.

Then create LINQtoSQL Employee.dbml file.

Create new handler file AddEmployee.ashx.

Update the ProcessRequest method :

public void ProcessRequest(HttpContext context)
{
    var name = context.Request["name"];
    var email = context.Request["email"];
    var address = context.Request["address"];
 
    EmployeeDataContext HRDB = new EmployeeDataContext();
    Employee employee = new Employee();
    employee.Name = name;
    employee.Email = email;
    employee.address = comment;
    HRDB.Employees.InsertOnSubmit(employee);
    HRDB.SubmitChanges();
    context.Response.Write("loading success");
}

On the front file: AddEmployee.htm add the form method="post" action ="AddEmployee.ashx"
add container div:

HTML:

<div id="container">
<label for="name">EmployeeName</label>
<input type="text" name="name" id="name" />

<label for="email">Email</label>
<input type="text" name="email" id="email" />

<label for="comment">Address</label>
<textarea id="address " name="comment" cols="35" rows="5">
</textarea>

<br />
<input type="button" id="submit" name="submit" value="Add Employee" /></div>

Add the following code to the head section:

<script type="text/javascript" src="./js/jquery-1.4.4.js"></script>
<script type="text/javascript">

$(document).ready(function() {
$('#submit').click(function(){
$('#container').append('<img id="loadining" src="ajax-loader.gif" alt="loading"/>');
var name = $('#name').val();
var email = $('#email').val();
var address = $('#address').val();
$.ajax({
url: 'AddEmployee.ashx',
type: 'POST',
data: 'name=' + name + '&email=' + email + '&address =' +address,

success:function(result)
{
$('#response').remove();
$('#container').append('<p id="response">'+ result+ '</p>');
$('#loadining').fadeOut(500,function(){
$(this).remove();
});
}
});
return false;
});
});
</script>
Thanks

shinu

Up Next
    Ebook Download
    View all
    Learn
    View all