Click here to Skip to main content
15,881,281 members
Please Sign up or sign in to vote.
1.80/5 (2 votes)
There is no errors. It just does not show the alert:
"10/19/2014 05:00 PM 123"

Default.aspx
ASP.NET
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript">
        function GetDateTime(json1) {
            $.ajax
            ({
                type: "POST",
                url: "Default.aspx/GetServerDateTime",
                data: json1,
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: function (result) {
                    alert(result.d);
                },
                error: function (err) {
                }
            });
        }
    </script>
<asp:Button ID="Button1" runat="server" Text="AJAX" OnClick="Button1_Click" />


Default.aspx.cs
C#
protected void Button1_Click(object sender, EventArgs e)
        {
            string json1 = "{'one':'1','two':'2','three':'3'}";
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "scr", "Javascript:GetDateTime(" + json1 + ");", true);
        }
        [WebMethod]
        public static string GetServerDateTime(string one, string two, string three)
        {
            return DateTime.Now.ToString() + " " + one + two + three;
        }
Posted
Updated 20-Oct-14 2:13am
v3

Your pretty far off course there. Read the lesson below to get a better idea of how to do it.

I don't care for the examples too much, but it's all I could find in a short amount of time. I attached a sample I wrote in VB, but you should get the idea.

And you'll have to learn json if you select this style or method of talking to the server in the background. Don't forget to jaon lint everything during testing.
http://jsonlint.com/[^]

Simply put, you need a jquery file that calls the webservice, which is a asmx file, or webservice, that is tweaked to support json.

Introduction to using jQuery with Web Services[^]

http://www.c-sharpcorner.com/UploadFile/dacca2/understand-jquery-ajax-function-call-web-service-using-jque/[^]

So an example post script would be like this, which includes error checking and so forth, and url encoding and decoding of test during transmitting and receiving.

There are several ways to do this, but this is what I use. Some folks like json stringify to encode and decode json.
function apply_post() {

    var secure_Token,
    m_template;

    m_secureToken = $('[id*="_txt_Secure_Token_Field"]').val();
    m_jobName = $('[id*="_txt_CE_FI_SaveAs_Field"]').val().replace(/[|&$%@"<>()+,] /g, '');
    
    // Package the data for transmission
    var send_Data =
    "{" +
    "\"p_secureToken\" : \"" + m_secureToken + "\", " +
    "\"p_jobName\" : \"" + escape(m_jobName) + "\"  " +
    "}";

    $('[id*="_updateProgress_Unified"]').fadeIn('fast');

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "broadcastEditor.asmx/apply_Post",
        data: send_Data,
        dataType: "json",
        error: function (xhr, status, error) {
            var exitCode = 2;
            $('[id*="_updateProgress_Unified"]').fadeOut('fast', function () {
                alert(xhr.responseText);
            });
        },
        success: function (responseText) {
            var objB = jQuery.parseJSON(responseText.d);
            var exitCode = objB.exitCode;
            var p_jobNumber = unescape(objB.p_jobNumber.replace(/\+/g, ' '));
            var p_jobStatus = unescape(objB.p_jobStatus.replace(/\+/g, ' '));

            if (0 === exitCode) {
                $('[id*="_lbl_CE_SM"]').text(m_jobName + ' has been posted successfully');
                $('[id*="_div_CE_SM_Container"]').css('background-color', 'rgb(28,134,238)');
            }
            else {
                $('[id*="_lbl_CE_SM"]').text(p_saveAs + ' has failed to be posted');
                $('[id*="_div_CE_SM_Container"]').css('background-color', 'rgb(176,23,31)');
            }
            $('[id*="_lbl_CE_Status_JobNumber_Field"]').text(p_jobNumber);
            $('[id*="_lbl_CE_Status_JobsStatus_Field"]').text(p_jobStatus);
            $('[id*="_div_CE_SM_Container"]').fadeIn('normal').delay(5000).fadeOut('normal');
            $('[id*="_updateProgress_Unified"]').fadeOut('fast');

        }
    });

}


And a asmx file
Imports System.Web.Services
Imports System.Text
Imports System.Web
Imports System.IO
Imports System.Xml.Serialization
Imports System.Data.SqlClient

<webservice(namespace:> _
<webservicebinding(conformsto:> _
<global.microsoft.visualbasic.compilerservices.designergenerated()> _
<system.web.script.services.scriptservice()> _
Public Class ws_broadcastEditor_SQL
    Inherits System.Web.Services.WebService
    <webmethod(enablesession:> _
<webmethod(enablesession:> _
    Public Function apply_Post( _
        ByVal p_secureToken As String,
        ByVal p_jobName As String) As String

        Dim dwExitCode As Integer = 2
        Dim json_response As StringBuilder = New StringBuilder

        Dim m_jobName As String = HttpUtility.UrlDecode(p_jobName)
        Dim m_jobNumber As String = Nothing
        Dim m_jobStatus As String = Nothing

        'Toggle the Publish Flag tp On or 1
        dwExitCode = publish_Job(
            m_jobName,
            m_jobNumber,
            m_jobStatus
        )

        'Just tell the user whether the file data write was sucessful or not
        With json_response
            .Append("{")
            .Append(" ""exitCode"" : " & dwExitCode.ToString & ", ")
            .Append(" ""p_jobNumber"" : """ & HttpUtility.UrlEncode(m_jobNumber) & """, ")
            .Append(" ""p_jobStatus"" : """ & HttpUtility.UrlEncode(m_jobStatus) & """  ")
            .Append("}")
        End With

        Dim js As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer
        js.Serialize(json_response.ToString)
        js = Nothing

        Return json_response.ToString

    End Function
 
Share this answer
 
Hi Teledextri,

I run your code, it gives some Json error of "Authentication Failed".

I have made some changes in your code and now it is giving the desired result.

Default.aspx

XML
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript">
        function GetDateTime(json1) {
            $.ajax
            ({
                type: "POST",
                url: "Default.aspx/GetServerDateTime",
                data: JSON.stringify(json1),
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: function (result) {
                    alert(result.d);
                },
                error: function (err) {
                }
            });
        }
    </script>



Default.aspx.cs
C#
protected void Button1_Click(object sender, EventArgs e)
{
  string json1 = "{'one':'1','two':'2','three':'3'}";
  ClientScript.RegisterStartupScript(GetType(), "GetDateTime","<script>GetDateTime("+ json1 + ");</script>");
}



RouteConfig.cs
C#
public static void RegisterRoutes(RouteCollection routes)
{
     var settings = new FriendlyUrlSettings();
     //settings.AutoRedirectMode = RedirectMode.Permanent;
     routes.EnableFriendlyUrls(settings);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900