user287745
user287745

Reputation: 3171

How to send text message using JavaScript to avoid post back?

This is what I have implemented, for further code, how to send the text of the text box to the server to store in variable or database without post back?

It can be done by using Ajax and update plane, but I would like to implement it using a JavaScript script.

<div id="CommentID" style=" width:30%; height:30%">
   <asp:Button ID="Button1" runat="server"
        Text="Comment"
        OnClientClick="visibleDiv('id1'); return false;" />

   <div id="id1" runat="server" style="visibility: hidden; background-color:Green; width:100%; height:100%">
       <asp:TextBox ID="TextBox1" runat="server"
            AutoCompleteType="Disabled" Rows="3"
            TextMode="MultiLine" Width="98%">
       </asp:TextBox>
       <asp:Button ID="Button2" runat="server"
            Text="Post"
            onclick="Button2_Click" />
       <asp:Button ID="Button3" runat="server"
            Text="Cancel"
            OnClientClick="visibleDiv('id1'); return false;" />
    </div>
</div>

Upvotes: 0

Views: 432

Answers (2)

Sean Kinsey
Sean Kinsey

Reputation: 38046

Skip jQuery, just add use a PageMethod

This will expose a static server side method in javascript and facilitate all the Ajax stuff

Add this to your code behind

[System.Web.Services.WebMethod]
public static string SendString( string text ) {
    // store the string in the database
    return text;
}

Add a scriptmanager to your markup

<form runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"/>
    ...

And now you can call SendString from javascript using

 PageMethods.SendString("mystring", function(text){
     alert("wooot! " + text);
 });

Also note that you can use strongly typed parameters and return values.
ASP.NET AJAX will automatically create client side classes in javascript to emulate the server side ones, and will automatically serialize and deserialize them :)

Upvotes: 1

Roman Bataev
Roman Bataev

Reputation: 9361

I suggest you to use jQuery:

<asp:Button ID="Button1" runat="server"
        Text="Comment" 
        OnClientClick="$.post("you_url", {text: $("#TextBox1").val()});"/>

See http://api.jquery.com/jQuery.post/ for details.

Upvotes: 0

Related Questions