.NET Simple Form Submit via AJAX and JQUERY
I've got the flow all worked out thanks to balexandre and rtiq. My .ashx file is being called so I know a portion of the code is working and it is alerting me to an error. When I trace the .NET, the variables pulled in via context.Request["email"] and context.Request["optin"] are NULL.
I know there's something wrong but I can't see it. I've re-edited this post to have the latest code.
jQuery in HEAD
<script type="text/javascript">
$(document).ready(function () {
$(".submitConnectButton").click(function (evt) {
evt.preventDefault();
alert("hello click");
alert($(".emailConnectTextBox").val());
$.ajax({
type: "POST",
url: "/asynchronous/insertEmail.ashx",
data: "{email: '" + $(".emailConnectTextBox").val() + "',optin: '" + $(".connectCheckbox").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) { alert(msg.d); },
error: function (msg) { alert('Error:' + msg); }
});
});
});
</script>
HTML
<div class="emailConnect">
<asp:TextBox runat="server" ID="TextBox1" CssClass="emailConnectTextBox" BorderStyle="Solid"></asp:TextBox>
<asp:ImageButton id="connectButton" CssClass="submitConnectButton" runat="server" ImageUrl="~/Images/submit_btn.png" /><br />
<asp:CheckBox Checked="true" id="checkbox1" runat="server" CssClass="connectCheckbox" />
</div>
CodeBehind in a .ashx
public class insertEmail : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string strConnection = System.Configuration.ConfigurationManager.AppSettings["SQLConnectStri开发者_Python百科ng"].ToString();
string email = context.Request["email"],
optin = context.Request["optin"];
string strSQL = "INSERT INTO Emails (emailAddress,optIn) VALUES('" + email.ToString() + "','" + optin.ToString() + "')";
SqlConnection Conn = new SqlConnection(strConnection);
SqlCommand Command = new SqlCommand(strSQL, Conn);
Conn.Open();
Command.ExecuteNonQuery();
Conn.Close();
context.Response.ContentType = "text/plain";
context.Response.Write("email inserted");
}
public bool IsReusable
{
get
{
return false;
}
}
}
The form and elements are acting properly. We are just getting this NULL values and not being able to insert. The ajax is calling the .ashx file properly and the file is compiling, the requested variables are null.. The previous help was awesome, if anyone could help me get this last kink out, you would get a gold star for the day! :)
After some searching offline in books, this finally worked for me in concjunction with balexandres .aspx method:
SOLUTION
$.post("/asynchronous/addEmail.aspx", {email: $(".emailConnectTextBox").val(),optin: $(".connectCheckbox").is(':checked')}, function(data) { alert('Successful Submission');});
- create a new folder in your website root called
asynchronous
- create a new
aspx
page calledaddEmail.aspx
and delete all HTML except the 1st line - inside that
addEmail.aspx
you place your code behind, like:
.
public void Page_Load(...)
{
insertEmail();
}
public void inserEmail() {
string email = Request["email"],
optin = Request["optin"];
string strSQL = "INSERT INTO Emails (emailAddress,optIn) VALUES('" + email.ToString() + "', optin)";
SqlConnection Conn = new SqlConnection(strConnection);
SqlCommand Command = new SqlCommand(strSQL, Conn);
Conn.Open();
Command.ExecuteNonQuery();
Conn.Close();
// Output
Response.Write("email inserted");
}
in your main page that has the
.ajax()
call change theurl
property tourl: "/asynchronous/insertEmail.aspx",
You will have in your msg
in success: function (msg) {}
the string email inserted
This is what I always do, though, instead of creating an ASPX Page, I use ASHX (Generic Handler) page that does not contain any ASP.NET Page Cycle (faster to load) and it's a simple page.
if you want to use a Generic Handler
instead, create inside asynchronous
folder a file called inserEmail.ashx
and the full code would be:
public class insertEmail : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string email = context.Request["email"],
optin = context.Request["optin"];
string strSQL = "INSERT INTO Emails (emailAddress,optIn) VALUES('" + email.ToString() + "', optin)";
SqlConnection Conn = new SqlConnection(strConnection);
SqlCommand Command = new SqlCommand(strSQL, Conn);
Conn.Open();
Command.ExecuteNonQuery();
Conn.Close();
context.Response.ContentType = "text/plain";
context.Response.Write("email inserted");
}
public bool IsReusable
{
get
{
return false;
}
}
}
and, remember to change your url
property to url: "/asynchronous/insertEmail.ashx",
from your comment I realized that your data
property was also not correct.
the correct is:
data: {
"email" : $(".emailConnectTextBox").val(),
"optin" : $(".connectCheckbox").val() },
your full ajax call should be:
$.ajax({
type: "POST",
url: "/asynchronous/insertEmail.ashx",
data: {
"email" : $(".emailConnectTextBox").val(),
"optin" : $(".connectCheckbox").val()
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (msg) {
alert('Error:' + msg.d);
}
});
and your Response.Write
in the generic handler should pass a JSON string as well
so, change tgis context.Response.Write("email inserted");
into context.Response.Write("{d:'email inserted'});
that's all.
$("button").click(function(){
var content = new Object();
content.email = $("#email").val();
content.option = $("#checkbox").val();
content = JSON.stringify(content);
$.ajax({
async: false,
type: "POST",
url: aspxPage + "/" + function, //make sure root is set proper.
contentType: "application/json;",
data: content,
dataType: "json",
success: successFunction,
error: errorFunction
});
});
//Make sure the form is posted ..which is needed for ajax to submit.
//the data part in code behind seems ok.
You don't have a form in your html code and since you may not use submit. Use click instead as rciq wrote.
Try changing this:
$("#connectButton").submit(function () {
alert("hello click");
(...)
To this:
$("#connectButton").click(function (evt) {
evt.preventDefault();
alert("hello click");
(...)
Also you must remember that the ID of the ASP.NET server control is not the same as the rendered DOM control ID. This might be the reason why your alert does not fire. If you write the client script on the same page as the server control, you can 'render' the ClientID inside a script tag this way:
$("<%= connectButton.ClientID %>").click( ...
Another thing. If you use jQuery selections in HEAD scripts they might be firing too early to find the controls. You should run them after the DOM controls are created. One thing to accomplish that is to use the 'ready' event:
http://api.jquery.com/ready/
精彩评论