skip to Main Content

having spent so many days searching for a solution, am left with option but to ask you guys here. Am totally new to AJAX, and have tried to avoid it at all cost but this time around, I have no choice but to face it squarely.

What I want is a simple data exchange (eg hello world) between an HTML page and a server side ASPX page (preferable VB).. The solutions am seeing online are either too complex for me to understand or are incomplete.

I was able to receive data from an ajax html page in the aspx server app, but find it very difficult to communicate back the feedback from the page through JSON ajax. pls i would appreciate your help. Thanks

My current client side JQuery code (got if from one of the tutorial I am using)
I have a contact submission form , when the SUBMIT button is clicked, it invokes the script below. I received the user’s data in my server side, but i am unable to communicate a success signal to the client page from the server side.

<script>
    (function($) {

        'use strict';

        /*
        Contact Form: Basic
        */
        $('#contactForm').validate({
            submitHandler: function(form) {

                var $form = $(form),
                    $messageSuccess = $('#contactSuccess'),
                    $messageError = $('#contactError'),
                    $submitButton = $(this.submitButton),
                    $errorMessage = $('#mailErrorMessage');

                $submitButton.button('loading');

                // Ajax Submit
                $.ajax({
                    type: 'POST',
                    url: $form.attr('action'),
                    data: {
                        Fname: $form.find('#Fname').val(),
                        Sname: $form.find('#Sname').val(),
                        GSM: $form.find('#GSM').val(),
                        sector: $form.find('#sector').val(),
                        email: $form.find('#email').val(),
                        categoryofclient: $form.find('#categoryofclient').val(),
                        message: $form.find('#message').val()
                    }
                }).always(function(data, textStatus, jqXHR) {

                    $errorMessage.empty().hide();

                    if (data.response == 'success') {

                        $messageSuccess.removeClass('hidden');
                        $messageError.addClass('hidden');

                        // Reset Form
                        $form.find('.form-control')
                            .val('')
                            .blur()
                            .parent()
                            .removeClass('has-success')
                            .removeClass('has-error')
                            .find('label.error')
                            .remove();

                        if (($messageSuccess.offset().top - 180) < $(window).scrollTop()) {
                            $('html, body').animate({
                                scrollTop: $messageSuccess.offset().top - 180
                            }, 300);
                        }

                        $submitButton.button('reset');

                        return;

                    } else if (data.response == 'error' && typeof data.errorMessage !== 'undefined') {
                        $errorMessage.html(data.errorMessage).show();
                    } else {
                        $errorMessage.html(data.responseText).show();
                    }

                    $messageError.removeClass('hidden');
                    $messageSuccess.addClass('hidden');

                    if (($messageError.offset().top - 180) < $(window).scrollTop()) {
                        $('html, body').animate({
                            scrollTop: $messageError.offset().top - 180
                        }, 300);
                    }

                    $form.find('.has-success')
                        .removeClass('has-success');

                    $submitButton.button('reset');

                });
            }
        });
    }).apply(this, [jQuery]);
</script>

My server side (Load event of the aspx page):

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim jsserialize As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim feedbackM2 As New Dictionary(Of String, String)
feedbackM2.Add("response", "success")
Context.Response.Write(jsserialize.Serialize(feedbackM2))
End Sub

when I run the ASPX page, I get

    {"response":"success"}

but still it could not trigger the client form.

ASPX/HTML markup

    <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="amasico.aspx.vb" Inherits="utilityserverapps._Default" %>

Entire Client side HTML markup (the links to some of the CSS are else where)

 <!DOCTYPE html>
<html>

<head>

    <!-- Basic -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <title>Contact Us </title>

    <meta name="keywords" content="HTML5 Template" />
    <meta name="description" content="Porto - Responsive HTML5 Template">
    <meta name="author" content="okler.net">

    <!-- Favicon -->
    <link rel="shortcut icon" href="webcom/img/favicon.ico" type="image/x-icon" />
    <link rel="apple-touch-icon" href="webcom/img/apple-touch-icon.png">

    <!-- Mobile Metas -->
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">

    <!-- Web Fonts  -->
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800%7CShadows+Into+Light" rel="stylesheet" type="text/css">

    <!-- Vendor CSS -->
    <link rel="stylesheet" href="webcom/vendor/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="webcom/vendor/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="webcom/vendor/simple-line-icons/css/simple-line-icons.min.css">
    <link rel="stylesheet" href="webcom/vendor/owl.carousel/assets/owl.carousel.min.css">
    <link rel="stylesheet" href="webcom/vendor/owl.carousel/assets/owl.theme.default.min.css">
    <link rel="stylesheet" href="webcom/vendor/magnific-popup/magnific-popup.min.css">

    <!-- Theme CSS -->
    <link rel="stylesheet" href="webcom/css/theme.css">
    <link rel="stylesheet" href="webcom/css/theme-elements.css">
    <link rel="stylesheet" href="webcom/css/theme-blog.css">
    <link rel="stylesheet" href="webcom/css/theme-shop.css">
    <link rel="stylesheet" href="webcom/css/theme-animate.css">

    <!-- Skin CSS -->
    <link rel="stylesheet" href="webcom/css/skins/default.css">

    <!-- Theme Custom CSS -->
    <link rel="stylesheet" href="webcom/css/custom.css">

    <!-- Head Libs -->
    <script src="webcom/vendor/modernizr/modernizr.min.js"></script>

</head>
<body>
    <div class="body">
        <header id="header" data-plugin-options='{"stickyEnabled": true, "stickyEnableOnBoxed": true, "stickyEnableOnMobile": true, "stickyStartAt": 57, "stickySetTop": "-57px", "stickyChangeLogo": true}'>
            <div class="header-body">
                <div class="header-container container">
                    <div class="header-row">
                        <div class="header-column">
                            <div class="header-logo">
                                <a href="webcom/index.html">
                                    <img alt="Amasico" width="200" height="70" data-sticky-width="142" data-sticky-height="50" data-sticky-top="33" src="img/amalogo.jpg">
                                </a>
                            </div>
                        </div>
                        <div class="header-column">
                            <div class="header-row">
                                <nav class="header-nav-top">
                                    <ul class="nav nav-pills">
                                        <li class="hidden-xs">
                                            <a href="webcom/about-us.html"><i class="fa fa-angle-right"></i> About Us</a>
                                        </li>
                                        <li class="hidden-xs">
                                            <a href="webcom/contact-us.html"><i class="fa fa-angle-right"></i> Contact Us</a>
                                        </li>
                                        <li>
                                            <span class="ws-nowrap"><i class="fa fa-phone"></i> (123) 456-789</span>
                                        </li>
                                    </ul>
                                </nav>
                            </div>
                            <div class="header-row">
                                <div class="header-nav">
                                    <button class="btn header-btn-collapse-nav" data-toggle="collapse" data-target=".header-nav-main">
                                        <i class="fa fa-bars"></i>
                                    </button>
                                    <ul class="header-social-icons social-icons hidden-xs">
                                        <li class="social-icons-facebook"><a href="http://www.facebook.com/" target="_blank" title="Facebook"><i class="fa fa-facebook"></i></a>
                                        </li>
                                        <li class="social-icons-twitter"><a href="http://www.twitter.com/" target="_blank" title="Twitter"><i class="fa fa-twitter"></i></a>
                                        </li>
                                        <li class="social-icons-linkedin"><a href="http://www.linkedin.com/" target="_blank" title="Linkedin"><i class="fa fa-linkedin"></i></a>
                                        </li>
                                    </ul>
                                    <div class="header-nav-main header-nav-main-effect-1 header-nav-main-sub-effect-1 collapse">
                                        <nav>
                                            <ul class="nav nav-pills" id="mainNav">
                                                <li>
                                                    <a href="index.html">
                                                            Home
                                                        </a>
                                                </li>
                                                <li class="dropdown-mega active">
                                                    <a href="index.html">
                                                            About Us
                                                        </a>
                                                </li>
                                                <li>
                                                    <a href="index.html">
                                                            Products
                                                        </a>
                                                </li>
                                                <li>
                                                    <a href="index.html">
                                                            Services
                                                        </a>
                                                </li>
                                            </ul>
                                        </nav>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </header>


        <div role="main" class="main">

            <section class="page-header">
                <div class="container">
                    <div class="row">
                        <div class="col-md-12">
                            <ul class="breadcrumb">
                                <li><a href="#">Home</a>
                                </li>
                                <li class="active">HIRE AMASICO</li>
                            </ul>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <h1>HIRE AMASICO</h1>
                        </div>
                    </div>
                </div>
            </section>

            <div class="container">

                <div class="row">
                    <div class="col-md-3"><img src="img/contactus.jpg" class="img-responsive" alt="Contact us" />
                    </div>
                    <div class="col-md-6">
                        <h2 class="mb-sm mt-sm"><strong>Discover </strong>how we can serve you?</h2>
                        <br>
                        <br>
                        <div class="alert alert-success hidden mt-lg" id="contactSuccess">
                            <strong>Success!</strong> Your message has been sent to us.
                            <br> Thank you, we will call you soon!) </div>

                        <div class="alert alert-danger hidden mt-lg" id="contactError">
                            <strong>Error!</strong> There was an error sending your message.
                            <span class="font-size-xs mt-sm display-block" id="mailErrorMessage"></span>
                        </div>
                        <form id="contactForm" action="http://localhost:57414/amasico.aspx" method="POST">
                            <div class="row">
                                <div class="form-group">
                                    <div class="col-md-6">
                                        <label>First Name *</label>
                                        <input type="text" value="" data-msg-required="Please enter your name." maxlength="100" class="form-control" name="Fname" id="Fname" required>
                                    </div>
                                    <div class="col-md-6">
                                        <label>Surname *</label>
                                        <input type="text" value="" data-msg-required="Please enter your surname." maxlength="100" class="form-control" name="Sname" id="Sname" required>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="form-group">
                                    <div class="col-md-6">
                                        <label>Your GSM Number *</label>
                                        <input type="telephone" value="" data-msg-required="Please enter your GSM no." maxlength="100" class="form-control" name="GSM" id="GSM" required placeholder="GSM number">
                                    </div>
                                    <div class="col-md-6">
                                        <label>Your email address *</label>
                                        <input type="email" value="" data-msg-required="Please enter your email address." data-msg-email="Please enter a valid email address." maxlength="100" class="form-control" name="email" id="email" required>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="form-group">
                                    <label class="col-md-12 control-label">Category</label>
                                    <div class="col-md-6">
                                        <select name="categoryofclient" class="form-control" id="categoryofclient" data-plugin-selectTwo>
                                            <option value="SELF_EMPLOYED">SELF EMPLOYED </option>
                                            <option value="ENTREPRENEUR">ENTREPRENEUR</option>
                                            <option value="EMPLOYED">EMPLOYED </option>
                                            <option value="UNEMPLOYED">UNEMPLOYED</option>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="form-group">
                                    <div class="col-md-12">
                                        <label>Industrial Sector</label>
                                        <input type="text" value="" data-msg-required="Please enter the sector you are interested in." maxlength="100" class="form-control" name="sector" id="sector" required>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="form-group">
                                    <div class="col-md-12">
                                        <label>Other comment? *</label>
                                        <textarea maxlength="3000" data-msg-required="Please enter your message." rows="10" class="form-control" name="message" id="message"></textarea>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <input type="submit" value="Send Message" class="btn btn-primary btn-lg mb-xlg" data-loading-text="Loading...">
                                </div>
                            </div>
                        </form>
                    </div>


                </div>

            </div>

        </div>

        <footer id="footer">
            <div class="container">
                <div class="row">
                    <div class="footer-ribbon">
                        <span>Get in Touch</span>
                    </div>
                    <div class="col-md-6">
                        <div class="contact-details">
                            <h4>Contact Us</h4>
                            <ul class="contact">
                                <li>
                                    <p><i class="fa fa-map-marker"></i> <strong>Address:</strong> 1234 Street Name, City Name, United States</p>
                                </li>
                                <li>
                                    <p><i class="fa fa-phone"></i> <strong>Phone:</strong> (123) 456-789</p>
                                </li>
                                <li>
                                    <p><i class="fa fa-envelope"></i> <strong>Email:</strong> <a href="mailto:[email protected]">[email protected]</a>
                                    </p>
                                </li>
                            </ul>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <h4>Follow Us</h4>
                        <ul class="social-icons">
                            <li class="social-icons-facebook"><a href="http://www.facebook.com/" target="_blank" title="Facebook"><i class="fa fa-facebook"></i></a>
                            </li>
                            <li class="social-icons-twitter"><a href="http://www.twitter.com/" target="_blank" title="Twitter"><i class="fa fa-twitter"></i></a>
                            </li>
                            <li class="social-icons-linkedin"><a href="http://www.linkedin.com/" target="_blank" title="Linkedin"><i class="fa fa-linkedin"></i></a>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
            <div class="footer-copyright">
                <div class="container">
                    <div class="row">
                        <div class="col-md-1">
                            <a href="index.html" class="logo">
                                <img src="img/amalogoBlack.jpg" alt="Amasico Freelance" width="200" height="70" class="img-responsive">
                            </a>
                        </div>
                        <div class="col-md-7">
                            <p>© Copyright 2016. All Rights Reserved.</p>
                        </div>
                        <div class="col-md-4">
                            <nav id="sub-menu">
                                <ul>
                                    <li><a href="page-faq.html">FAQ's</a>
                                    </li>
                                    <li><a href="sitemap.html">Sitemap</a>
                                    </li>
                                    <li><a href="contact-us.html">Contact</a>
                                    </li>
                                </ul>
                            </nav>
                        </div>
                    </div>
                </div>
            </div>
        </footer>
    </div>

    <!-- Vendor -->
    <script src="webcom/vendor/jquery/jquery.min.js"></script>
    <script src="webcom/vendor/jquery.appear/jquery.appear.min.js"></script>
    <script src="webcom/vendor/jquery.easing/jquery.easing.min.js"></script>
    <script src="webcom/vendor/jquery-cookie/jquery-cookie.min.js"></script>
    <script src="webcom/vendor/bootstrap/js/bootstrap.min.js"></script>
    <script src="webcom/vendor/common/common.min.js"></script>
    <script src="webcom/vendor/jquery.validation/jquery.validation.min.js"></script>
    <script src="webcom/vendor/jquery.stellar/jquery.stellar.min.js"></script>
    <script src="webcom/vendor/jquery.easy-pie-chart/jquery.easy-pie-chart.min.js"></script>
    <script src="webcom/vendor/jquery.gmap/jquery.gmap.min.js"></script>
    <script src="webcom/vendor/jquery.lazyload/jquery.lazyload.min.js"></script>
    <script src="webcom/vendor/isotope/jquery.isotope.min.js"></script>
    <script src="webcom/vendor/owl.carousel/owl.carousel.min.js"></script>
    <script src="webcom/vendor/magnific-popup/jquery.magnific-popup.min.js"></script>
    <script src="webcom/vendor/vide/vide.min.js"></script>

    <!-- Theme Base, Components and Settings -->
    <script src="webcom/js/theme.js"></script>

    <!-- Current Page Vendor and Views -->
    <script>
        (function($) {

            'use strict';

            /*
            Contact Form: Basic
            */
            $('#contactForm').validate({
                submitHandler: function(form) {

                    var $form = $(form),
                        $messageSuccess = $('#contactSuccess'),
                        $messageError = $('#contactError'),
                        $submitButton = $(this.submitButton),
                        $errorMessage = $('#mailErrorMessage');

                    $submitButton.button('loading');

                    // Ajax Submit
                    $.ajax({
                        type: 'POST',
                        url: $form.attr('action'),
                        data: {
                            Fname: $form.find('#Fname').val(),
                            Sname: $form.find('#Sname').val(),
                            GSM: $form.find('#GSM').val(),
                            sector: $form.find('#sector').val(),
                            email: $form.find('#email').val(),
                            categoryofclient: $form.find('#categoryofclient').val(),
                            message: $form.find('#message').val()
                        }
                    }).always(function(data, textStatus, jqXHR) {

                        $errorMessage.empty().hide();

                        if (data.response == 'success') {

                            $messageSuccess.removeClass('hidden');
                            $messageError.addClass('hidden');

                            // Reset Form
                            $form.find('.form-control')
                                .val('')
                                .blur()
                                .parent()
                                .removeClass('has-success')
                                .removeClass('has-error')
                                .find('label.error')
                                .remove();

                            if (($messageSuccess.offset().top - 180) < $(window).scrollTop()) {
                                $('html, body').animate({
                                    scrollTop: $messageSuccess.offset().top - 180
                                }, 300);
                            }

                            $submitButton.button('reset');

                            return;

                        } else if (data.response == 'error' && typeof data.errorMessage !== 'undefined') {
                            $errorMessage.html(data.errorMessage).show();
                        } else {
                            $errorMessage.html(data.responseText).show();
                        }

                        $messageError.removeClass('hidden');
                        $messageSuccess.addClass('hidden');

                        if (($messageError.offset().top - 180) < $(window).scrollTop()) {
                            $('html, body').animate({
                                scrollTop: $messageError.offset().top - 180
                            }, 300);
                        }

                        $form.find('.has-success')
                            .removeClass('has-success');

                        $submitButton.button('reset');

                    });
                }
            });

            /*
            Contact Form: Advanced
            */
            $('#contactFormAdvanced').validate({
                onkeyup: false,
                onclick: false,
                onfocusout: false,
                rules: {
                    'captcha': {
                        captcha: true
                    },
                    'checkboxes[]': {
                        required: true
                    },
                    'radios': {
                        required: true
                    }
                },
                errorPlacement: function(error, element) {
                    if (element.attr('type') == 'radio' || element.attr('type') == 'checkbox') {
                        error.appendTo(element.parent().parent());
                    } else {
                        error.insertAfter(element);
                    }
                }
            });

        }).apply(this, [jQuery]);
    </script>

    <!-- Theme Custom -->
    <script src="webcom/js/custom.js"></script>

    <!-- Theme Initialization Files -->
    <script src="webcom/js/theme.init.js"></script>
    <script>

</body>
</html>

3

Answers


  1. Chosen as BEST ANSWER

    I appreciate all your contributions, I tried it all but still had error, i guess i missed some essential piece of information while trying them out.

    I decided to research further on the webservice of asp. Eventually I pieced in several bits of information to arrive at a working solution. Of immense relevance are this 2 link to my final working solutions, some of the codes were copied and pasted with little or no modifications (C# lang)

    http://forums.asp.net/t/1934215.aspx?Using+jQuery+ajax+to+call+asmx+webservice+methods http://www.codeproject.com/Articles/45275/Create-a-JSON-WebService-in-ASP-NET-with-a-jQu

    I also appreciate live webs webservice jsonplaceholder.typicode.com it gave me something to test my pages with.

    However some essential piece of information that detered my progress was the fact that I had to place a link to a jquery script on the my website folder. Also by default, I cant access the webservice of asp from a different domain name. Any way I eventually got some success after a week effort.

    First I had to create a webservice using vb 2008, the web service is named json.asmx.cs

        using System;
        using System.Collections;
        using System.ComponentModel;
        using System.Data;
        using System.Linq;
        using System.Web;
        using System.Web.Services;
        using System.Web.Services.Protocols;
        using System.Xml.Linq;
        using System.Collections.Generic;
        using System.Web.Script.Services;
        using System.Web.Script.Serialization;
        namespace JSONDemo
        {
            /// <summary>
            /// Summary description for Service1
            /// </summary>
            [WebService(Namespace = "http://tempuri.org/")]
            [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
            [System.ComponentModel.ToolboxItem(false)]
            [System.Web.Script.Services.ScriptService]
            public class json : System.Web.Services.WebService
            {
    
                [WebMethod]
                [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
                public string TestJSON()
                {
                    Employee[] e = new Employee[2];
                    e[0] = new Employee();
                    e[0].Name = "Ajay Singh";
                    e[0].Company = "Birlasoft Ltd.";
                    e[0].Address = "LosAngeles California";
                    e[0].Phone = "1204675";
                    e[0].Country = "US";
                    e[1] = new Employee();
                    e[1].Name = "Ajay Singh";
                    e[1].Company = "Birlasoft Ltd.";
                    e[1].Address = "D-195 Sector Noida";
                    e[1].Phone = "1204675";
                    e[1].Country = "India";
    
                    feedback[] f2 = new feedback[1];
                    f2[0] = new feedback();
                    f2[0].response = "success";
                    return new JavaScriptSerializer().Serialize(e);
                    //Context.Response.Write(new JavaScriptSerializer().Serialize(e)); //returns text string
                }
    
                [WebMethod]
                [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
                public  void TestJSON2()
                {
                    Employee[] e = new Employee[2];
                    e[0] = new Employee();
                    e[0].Name = "Ajay Singh";
                    e[0].Company = "Birlasoft Ltd.";
                    e[0].Address = "LosAngeles California";
                    e[0].Phone = "1204675";
                    e[0].Country = "US";
                    e[1] = new Employee();
                    e[1].Name = "Ajay Singh";
                    e[1].Company = "Birlasoft Ltd.";
                    e[1].Address = "D-195 Sector Noida";
                    e[1].Phone = "1204675";
                    e[1].Country = "India";
    
                    feedback[] f2 = new feedback[1];
                    f2[0] = new feedback();
                    f2[0].response = "success";
                    //return new JavaScriptSerializer().Serialize(e);
                    Context.Response.Write(new JavaScriptSerializer().Serialize(e)); //returns text string
                }
    
                [WebMethod]
                [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
                public void FeedbackB()
                {
                    feedback[] f2 = new feedback[1];
                    f2[0] = new feedback();
                    f2[0].response = "success";
                    //return new JavaScriptSerializer().Serialize(e);
                    Context.Response.Write(new JavaScriptSerializer().Serialize(f2)); //returns text string
                }
    
                [WebMethod]
                //[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
                public string FeedbackC()
                {
                    feedback[] f2 = new feedback[1];
                    f2[0] = new feedback();
                    f2[0].response = "success";
                   return new JavaScriptSerializer().Serialize(f2);
                   //Context.Response.Write(new JavaScriptSerializer().Serialize(f2)); //returns text string
                }
    
    
                [WebMethod]
                public string FeedbackD()
                {
                    var data = new { sresponse = "success"};
    
                    // We are using an anonymous object above, but we could use a typed one too (SayHello class is defined below)
                    // SayHello data = new SayHello { Greeting = "Hello", Name = firstName + " " + lastName };
    
                    System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
                    return js.Serialize(data);
                }
    
    
                [WebMethod]
                public string SayHello(string firstName, string lastName)
                {
                    return "Hello " + firstName + " " + lastName;
                }
    
                [WebMethod]
                public string SayHelloJson(string firstName, string lastName)
                {
                    var data = new { Greeting = "Hello", Name = firstName + " " + lastName };
    
                    // We are using an anonymous object above, but we could use a typed one too (SayHello class is defined below)
                    // SayHello data = new SayHello { Greeting = "Hello", Name = firstName + " " + lastName };
    
                    System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
                    return js.Serialize(data);
                }
    
    
    
                [WebMethod]
                [ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
                public Employee[] TestXML()
                {
                    Employee[] e = new Employee[2];
                    e[0] = new Employee();
                    e[0].Name = "Ajay Singh";
                    e[0].Company = "Birlasoft Ltd.";
                    e[0].Address = "LosAngeles California";
                    e[0].Phone = "310-235-1535";
                    e[0].Country = "US";
                    e[1] = new Employee();
                    e[1].Name = "Ajay Singh";
                    e[1].Company = "Birlasoft Ltd.";
                    e[1].Address = "D-195 Sector Noida";
                    e[1].Phone = "120-467500";
                    e[1].Country = "India";
                    return e;
                }
            }
        }
    

    I created a class named employee.cs

                using System;
                using System.Collections;
                using System.ComponentModel;
                using System.Data;
                using System.Linq;
                using System.Web;
                using System.Web.Services;
                using System.Web.Services.Protocols;
                using System.Xml.Linq;
                using System.Collections.Generic;
                using System.Web.Script.Services;
                using System.Web.Script.Serialization;
    
                public class Employee
                {
                    public string Name { get; set; }
                    public string Company { get; set; }
                    public string Address { get; set; }
                    public string Phone { get; set; }
                    public string Country { get; set; }
                }
                public class feedback
                {
                    public string response { get; set; }
                }
    
                public class SayHello
                {
                    public string Greeting { get; set; }
                    public string Name { get; set; }
                }
    

    I created a html page that will consume the webservice within the same project folder. (if placed outside, it wont work). Notice the link to a jquery-2.js within the html markup. You can get it from a jquery site.

            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
            <html xmlns="http://www.w3.org/1999/xhtml" >
            <head runat="server">
                <title>Untitled Page</title>
            </head>
            <body>
            <script src="jquery-2.js"></script>
    
                <form id="form1" runat="server">
                <div>
                <div><br />Example A</div>
                <div id="searchresultsA"></div>
                <div><br />Example B</div>
                <div id="searchresultsB"></div>
                <div><br />Example C</div>
                <div id="searchresultsC"></div>
                <div><br />Example D</div>
                <div id="searchresultsD"></div>
                <div><br />Example E</div>
                <div id="searchresultsE"></div>
                </div>
                </form>  
    
            </body>
    
            <script type="text/javascript">
            $(document).ready(function () {
    
                        // Example A - call a function that returns a string.
                        // Params are sent as form-encoded, data that comes back is text
                        $.ajax({
                            type: "POST",
                            url: "http://localhost:65039/json.asmx/TestJSON",
                            data: "firstName=Aidy&lastName=F", // the data in form-encoded format, ie as it would appear on a querystring
                            //contentType: "application/x-www-form-urlencoded; charset=UTF-8", // if you are using form encoding, this is default so you don't need to supply it
                            dataType: "text", // the data type we want back, so text.  The data will come wrapped in xml
                            success: function (data) {
                                $("#searchresultsA").html(data); // show the string that was returned, this will be the data inside the xml wrapper
                            }
                        });
    
                                    $.ajax({
                            type: "POST",
                            url: "http://localhost:65039/json.asmx/SayHello",
                            data: "{firstName:'Aidy', lastName:'F'}", // the data in JSON format.  Note it is *not* a JSON object, is is a literal string in JSON format
                            contentType: "application/json; charset=utf-8", // we are sending in JSON format so we need to specify this
                            dataType: "json", // the data type we want back.  The data will come back in JSON format
                            success: function (data) {
                                $("#searchresultsB").html(data.d); // it's a quirk, but the JSON data comes back in a property called "d"; {"d":"Hello Aidy F"}
                            }
                        });
    
                                     $.ajax({
                            type: "POST",
                            url: "http://localhost:65039/json.asmx/TestJSON",
                            data: { firstName: 'Aidy', lastName: 'F' }, // here we are specifing the data as a JSON object, not a string in JSON format
                                    // this will be converted into a form encoded format by jQuery
                            // even though data is a JSON object, jQuery will convert it to "firstName=Aidy&lastName=F" so it *is* form encoded
                            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                            dataType: "text", // the data type we want back, so text.  The data will come wrapped in xml
                            success: function (data) {
                                $("#searchresultsC").html(data); // show the data inside the xml wrapper
                            }
                        });
    
                        $.ajax({
                            type: "POST",
                            url: "http://localhost:65039/json.asmx/SayHelloJson",
                            data: "{ firstName: 'Aidy', lastName: 'F' }",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (data) {
                                var myData = JSON.parse(data.d); // data.d is a JSON formatted string, to turn it into a JSON object
                                                                 // we use JSON.parse
    
                                // now that myData is a JSON object we can access its properties like normal
                                $("#searchresultsD").html(myData.Greeting + " " + myData.Name);
                            }
                        });
    
                                    $.ajax({
                            type: "POST",
                            url: "http://localhost:65039/json.asmx/FeedbackD",
                            data: "{ firstName: 'Aidy', lastName: 'F' }", 
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (data) {
                                var myData = JSON.parse(data.d); // data.d is a JSON formatted string, to turn it into a JSON object
                                                                 // we use JSON.parse
    
                                // now that myData is a JSON object we can access its properties like normal
                                $("#searchresultsE").html(myData.sresponse);
                            }
                        });
    
    
                                        });
    
    
            </script>
    
    
    
            </html>
    

    eventually it worked. You may need to change the url properties of the ajax on client's html page the the appropriate urls.

    when the page loads, it generates the server contents in the ajax fields as intended

            Example A
            [{"Name":"Ajay Singh","Company":"Birlasoft Ltd.","Address":"LosAngeles California","Phone":"1204675","Country":"US"},{"Name":"Ajay Singh","Company":"Birlasoft Ltd.","Address":"D-195 Sector Noida","Phone":"1204675","Country":"India"}]
    
    
            Example B
            Hello Aidy F
    
    
            Example C
            [{"Name":"Ajay Singh","Company":"Birlasoft Ltd.","Address":"LosAngeles California","Phone":"1204675","Country":"US"},{"Name":"Ajay Singh","Company":"Birlasoft Ltd.","Address":"D-195 Sector Noida","Phone":"1204675","Country":"India"}]
    
    
            Example D
            Hello Aidy F
    
    
            Example E
            success
    

  2. Server Side

    Public Class WebForm1
        Inherits System.Web.UI.Page
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
        End Sub
        <Services.WebMethod()>
        Public Shared  Function Hello(name As String) As String
            Return "hello " + name
    
        End Function
    End Class
    

    Client Side

    <script>
            $(document).ready(function () {
                $.ajax({
                    type: "POST",
                    url: "webform1.aspx/Hello",
                    data: "{name:'Raj'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        console.log(msg);
                    },
                    error: function (msg) {
                        console.log("error:" + JSON.stringify(msg));
                    }
                });
            });
    
        </script>
    
    Login or Signup to reply.
  3. There are a number of potential issues with the solution as shown. Firstly, the page_load event isn’t really the place to handle the ajax request. “{success:true}” is probably being written to your page when it first loads, not just when the ajax runs. Secondly I’m not convinced that a .NET forms .aspx page will be very happy about receiving an ajax-style postback to itself – they are fussy. It’s a while since I’ve used them (do everything in MVC now, much nicer!) but to handle the ajax post you can either define an entirely separate WCF webservice within your web app (good if you’ll have several ajax methods) or use WebMethods within your .aspx page.

    This example uses WebMethod. I have assumed you also have some class named ContactDetails which the form can be serialized to (i.e. it has public properties with the same names and data types as the form fields):

    VB code:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
    End Sub
    
    <System.Web.Services.WebMethod()> _
    Public Shared Function SubmitContactForm(ByVal data As ContactDetails) As String
      'Do some data validation here - don't rely on client-side validation alone!
      'do whatever you need to do to save the data, the at the end:
      Return "{ 'response': 'success' }" 'Once this works, think about using a more formal structure like an object containing your response values (e.g. validation errors)
    End Function
    

    Javascript:

    $("#contactForm").validate(function()
    {
      submitHandler: function(form) {
        alert("about to submit form"); //just for testing :-)
    
        var $form = $(form);
    
        // Ajax Submit
        $.ajax({
            type: 'POST',
            url: $form.attr('action'),
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ "data": $form.serializeArray() }), //this should automatically grab all the fields from your form
            success: function(response) { //ajax request succeeds
              alert(response); //just for testing :-)
              //do whatever else you need to with the response here. 
            },
            error: function (jQXHR, textStatus, errorThrown) { //ajax request fails (i.e. a HTTP error, not a validation error)
                        alert("An error occurred whilst attempting to contact the server: " + jQXHR.status + " " + errorThrown);
             }
        });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search