Showing posts with label jquery. Show all posts
Showing posts with label jquery. Show all posts

Friday, 23 September 2011

JQuery Ajax Call to Web service via POST

Have been used a lots of jquery in the recent real-time information web development project, I found this quite easy to initiate a POST HTTP call to web service through JQuery. Here are 2 sample code snippets.

Case 1: Pass no parameter

 
<script type="text/javascript">
    // in this case, we post nothing back to api but
    // just call it (no parameter required) and expected json object as result
    function callWebApiViaPost() {
        $.ajax({
            type: "POST",
            url: "yourwebapi",
            data: "{}",
            contentType: "application/json;",
            dataType: "json",
            success: function (t) {
                $("#your_result_display_div").text(t.d);
            }
        });
    }

</script>
 

Case 2: Pass parameter(s)

For example, you have a API like below:
 
[WebMethod]
public static string ToUpperCase(string yourparam)
{
    return yourparam.ToUpper();
}
 
The corresponding jquery ajax post call will be like this:
 
<script type="text/javascript">
    // in this case, we post nothing back to api but
    // just call it (no parameter required) and expected json object as result
    function callWebApiViaPost() {
        $.ajax({
            type: "POST",
            url: "yourweb/ToUpperCase",
            data: "{yourparam: 'hello-world'}",
            contentType: "application/json;",
            dataType: "json",
            success: function (t) {
                $("#your_result_display_div").text(t.d);
            }
        });
    }

</script>
 

Friday, 26 August 2011

JQuery Change Input Box Type

For security reason, some browsers such as IE don't allow modifying input type on the fly. Code snippet #1 won't know. In case you know exactly what you are doing and really want to modify the type dynamically for any good reasons. Here is a way to do so (see code snippet #2).

Code #1 - doesn't work in most of the browsers

 
Code #2 - works