Monday, January 12, 2009

JQuery post data to .ashx, pass to LINQ to SQL

First I create contact table which has contactId, name, email and comment. Then I create LINQtoSQL contact.dbml file.
Create new handler file call : SubmitDB.ashx. update the ProcessRequest method :

public void ProcessRequest (HttpContext context) {
var name = context.Request["name"];
var email = context.Request["email"];
var comment = context.Request["comment"];

ContactDataContext contactDB = new ContactDataContext();
Contact contact = new Contact();
contact.Name = name;
contact.Email = email;
contact.Comments = comment;
contactDB.Contacts.InsertOnSubmit(contact);
contactDB.SubmitChanges();
context.Response.Write("loading success");
}

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

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

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

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

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

In Javascript, reference google javascript:



add another script:

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

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

return false;
});
});

No comments: