1

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["SQLConnectString"].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');});
CSSHell
  • 103
  • 5
  • 16
  • So far, I have used the answers from balexandre and rciq to get it flowing correctly. I am now just having problems with the ajax sending the proper content and not nulls. – CSSHell Jun 13 '11 at 21:20

4 Answers4

1
  • create a new folder in your website root called asynchronous
  • create a new aspx page called addEmail.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 the url property to

    url: "/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.

balexandre
  • 73,608
  • 45
  • 233
  • 342
  • I used your solution to deal with the incoming ajax, the .ashx file. It fires off properly, but the request objects are null. I am assuming the data is not being sent properly then. – CSSHell Jun 13 '11 at 21:05
  • string email = context.Request["email"], optin = context.Request["optin"]; – CSSHell Jun 13 '11 at 21:09
  • Its grabbing nulls... is there something in my ajax call that's not correct? – CSSHell Jun 13 '11 at 21:09
  • yes, you right, your `data` is also incorrect... I edited my answer to give you the correct data line that you need to change yours into – balexandre Jun 13 '11 at 21:34
  • It is still coming back as null... should it matter that I am using Master Pages? It seems to be calling the code behind just fine. It's only the variables that aren't being passed through. Thanks for your continued help. – CSSHell Jun 13 '11 at 22:27
  • I think it has to do with how I am calling the value from the checkbox... its coming up undefined so I am going down that road for troubleshooting now.. – CSSHell Jun 13 '11 at 22:49
  • I traced it out and have the checkbox returning a value so it is not null now but once the ajax call is made... both variables are null... sigh. :) – CSSHell Jun 13 '11 at 23:16
  • is it possible I am missing a namespace? Do I need anything extra than default namespaces? using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.SqlClient; using System.Web.Services; – CSSHell Jun 14 '11 at 00:01
  • the best way is to open your webpage in chrome/safari, right click somewhere and choose **Inspect Element**, open the console tab and write your jQuery like: `$(".emailConnectTextBox").val()` and `$(".connectCheckbox").val()` and see if you are getting something. If not try to see what's the Classes of the controls by looking up the final HTML of your page, maybe you are not retrieving just one but a collection of objects with the same class name, if that happen use the id instead, for example: `$("#<%= myCheckBox.ClientID %>").val()` – balexandre Jun 14 '11 at 07:51
1
 $("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.
abhijit
  • 1,958
  • 3
  • 28
  • 39
  • When you say 'make sure the form is posted' do you mean anything else beyond the type: "POST" setting? – CSSHell Jun 13 '11 at 21:06
0

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/

rciq
  • 1,309
  • 10
  • 10
  • I'm trying your example first as it seems to directly address what I am attempting. – CSSHell Jun 13 '11 at 20:05
  • Ok, as far as reaching my element and it grabbing the email address and alerting to me all the above solution worked. Now, the ajax portion doesn't seem to be firing the Web Method of the code-behind.. – CSSHell Jun 13 '11 at 20:27
  • I'm glad that it worked. As for the .ashx code, it's a different problem and there I'm sure that balexandre's answer is complete and will help you make the rest work:) – rciq Jun 13 '11 at 22:19
0

You don't have a form in your html code and since you may not use submit. Use click instead as rciq wrote.

Dynamikus
  • 2,861
  • 4
  • 22
  • 20