Showing posts with label Jquery. Show all posts
Showing posts with label Jquery. Show all posts

Monday, May 27, 2013

Jquery Ajax post Custom Object as Json to Wcf Service


function LoadMore() {

    var myData =
    {
        arguments : {
            Category: "Main",
            SearchText: "",
        }
    };


    var jsonedArguments = JSON.stringify(myData);

    $.ajax({
        type: "POST",
        url: "/PublicService.svc/LoadMore",
        contentType: "application/json; charset=utf-8",
        cache: false,
        data: jsonedArguments,
        dataType: "json",
        processdata: true,
        success: function (data) {
         
            debugger;
            var xx = data;

        },
        error: function (msg) {
            alert('CallFiles failed!!!!');
        }
    });
}



 [OperationContract]
        [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public GetFilesResult LoadMore(GetFilesArguments arguments)
        {
            return new GetFilesResult() { TotalCount = 100 };
        }

Thursday, May 2, 2013

jquery ajax enabled wcf Service call sample



    <script language="javascript" type="text/javascript">

        $(function () {
            CallSiblingMenu();
        });

        function getUrlParts(url) {
            var a = document.createElement('a');
            a.href = url;

            return {
                href: a.href,
                host: a.host,
                hostname: a.hostname,
                port: a.port,
                pathname: a.pathname,
                protocol: a.protocol,
                hash: a.hash,
                search: a.search
            };
        }

        function getNavigationUrl()
        {
            var url = window.location.href;
            var navigationUrl = getUrlParts(url).pathname;
            return navigationUrl;
        }

     

        function CallSiblingMenu() {

            var relativeUrl = getNavigationUrl();
            var baseControl = "#siblingsMenu";
            var html = '';

            //clear
            $(baseControl).html('');

            //add loading
            html = html + '<div id="loading" style="margin-left:50px;margin-top:50px;">';
            html = html + '<img src="/App_Themes/Common/Images/loading.gif"  /></div>';
            $(baseControl).append(html);

            $.ajax({
                type: "POST",
                url: "/PublicService.svc/GetSiblings",
                data: '{"relativeUrl": "' + relativeUrl + '"}',
                cache: false,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                processdata: true,
                success: function (data) {
                   
                    //remove loading
                    $('#loading').remove();

                    $.each(data.d, function (i, item) {

                        $(baseControl).append('<a class="" href="' + item.Url + '" ><div>' + item.Title + '</div></a>');
                    });

                },
                error: function (msg) {
                    $(baseControl).html('');

                    alert('CallSiblingMenu failed!!!!');
                }
            });
        }



    </script>



</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="LeftNavigationContent" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
    <div id="dynamic-wrapper">
        <div id="siblingsMenu"></div>

        <div id="content" runat="server" clientidmode="static">
        </div>

        <div class="clearfix"></div>

    </div>
</asp:Content>

Saturday, July 28, 2012

Jquery Document Ready


$(document).ready(function() {
  // Handler for .ready() called.
});

$(function() {
 // Handler for .ready() called.
});

jQuery(document).ready(function($) {
  // Code using $ as usual goes here.
});

Friday, July 6, 2012

jquery hashchange event not working

every browser is not supporting the hashchange event.
to be able to manage the issue, add the benalman plugin the your project.

http://benalman.com/projects/jquery-hashchange-plugin/


$(function(){

  // Bind the event.
  $(window).hashchange( function(){
    // Alerts every time the hash changes!
    alert( location.hash );
  })

  // Trigger the event (useful on page load).
  $(window).hashchange();

})

Jquery Load Specific Portion Of content



$(function () {
    var newHash = '';
    $cssmenu = $('#cssmenu');
    $('nav').delegate('a', 'click', function () {
        window.location.hash = this.attr('href');
        return false;

    });

    $(window).bind('hashchange', function () {
        newHash = window.location.hash.substring(1);
        $cssmenu.load(newHash + " #guts");
        console.log(newHash);
    });
})


it will change the div (id="guts") in cssmenu div

Thursday, July 5, 2012

WCF Json Service Method Argument null Problem

Do NOT use "url" as a argument name.

Wcf Service Method

 [OperationContract]
 [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json,
         RequestFormat= WebMessageFormat.Json)]
PageDTO PageByUrl(String url,String language);  --> PageDTO PageByUrl(String title,String language); 


-----------------------------------------------------------------------

Requested Url:

http://localhost:2222/tr-TR/test-page-1
-----------------------------------------------------------------------


Jquery Ajax Call


<script type="text/javascript">

    $(document).ready(function () {
     
        data = window.location.pathname.split("/");
        urlStr = data[data.length -1];
        languateStr = data[data.length - 2];

        var data = new Object();
        data.url = urlStr;   ---> data.title=urlStr;
        data.language = languateStr;

        //var xxx = $.toJSON(data);
        //result: {"url":" test-page-1","language":"tr-TR"}

        caller_dynamic(data);
    });


    var menuUrl = "http://localhost:9000/PublicService.svc/PageByUrl";

    function caller_dynamic(mydata) {
        $.support.cors = true;
        $.ajax({
            type: "POST",
            url: menuUrl,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: $.toJSON(mydata),
            success: function (data) {
                $("#content").html(data.Content);
            },
            error: function (xhr) {
                alert(xhr.responseText);
            }

        });
    }
     < /script>

---------------------------------------------------------------------

public PageDTO PageByUrl(String url, String language) --> (String title, String language)
        {
            try
            {
                var publicBS = unityContainer.Resolve();
                var page = publicBS.PageByUrl(title);
                return page;
            }
            catch (Exception ex)
            {
                throw DynFaultException.Instance.CreateFault(ex);
            }
        }



Conclusion

if url is null, do NOT panic. just change the name of the argument name url to title.





Tuesday, July 3, 2012

Javascript Page Document ready, PageLoad, Application Init


$(document).ready()
  • Ideal for onetime initialization.
  • Optimization black magic; may run slightly earlier than pageLoad().
  • Does not re-attach functionality to elements affected by partial postbacks.
pageLoad()
  • Unsuitable for onetime initialization if used with UpdatePanels.
  • Slightly less optimized in some browsers, but consistent.
  • Perfect for re-attaching functionality to elements within UpdatePanels.
Application.Init
  • Useful for onetime initialization if only ASP.NET AJAX is available.
  • More work required to wire the event up.
  • Exposes you to the “sys is undefined” error if you aren’t careful.

Monday, July 2, 2012

WCF Method not Allowed

Check type of the method call.

GET - It must be uppercase

        [OperationContract]
        [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
        String Test();
     
$.ajax({
                     cache: false,
                     type: "GET",
                     async: false,
                     dataType: "json",
                     url: "PublicService.svc/Test",
                     success: function (data) {
                         debugger;
                         $("#containerDiv").html(data);
                     },
                     error: function (xhr) {
                         debugger;
                         alert(xhr.responseText);
                     }

                 });


POST - It must be uppercase



  [OperationContract]
        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
        String Test2();


$.ajax({
                     cache: false,
                     type: "POST",
                     async: false,
                     dataType: "json",
                     url: "PublicService.svc/Test2",
                     success: function (data) {
                         debugger;
                         $("#containerDiv").html(data);
                     },
                     error: function (xhr) {
                         debugger;
                         alert(xhr.responseText);
                     }

                 });



jquery no transport


Jquery Code

<script type="text/javascript">

             var menuUrl = "http://localhost:3648/PublicService.svc/MenuList";

             function caller() {
                 $.support.cors = true;
                 $.ajax({
                     cache: false,
                     type: "POST",
                     async: false,
                     dataType: "json",
                     url: menuUrl,
                     success: function (data) {
                         debugger;
                         $("#containerDiv").html(data);
                     },
                     error: function (xhr) {
                         debugger;
                         alert(xhr.responseText);
                     }

                 });
             }

             $(document).ready(function () {
                 debugger;
                 caller();
             });
       
    </script>


SYMPTON: Message:No Transport Code:0
REASON: You're trying to make cross-domain request

SOLUTION: $.support.cors = true;



Thursday, March 15, 2012

jquery minified ne demektir?


kısaca  minified  sıkıştırılmış demektir.

Jquery ile ilgili en beğendiğim kitap olan  EARLE CASTLEDINE AND CRAIG SHARKIE 'in yazmış olduğu Sitepoint jQuery Novice to Ninja kitaptan bir alıntı yaparak açıklayacağım.

"minified olan versiyonları genellikle canlı'ya çıkmış uygulamalarda kullanmak isteyeceksinizdir.
JQuery kaynak kodları sıkıştırılmış olacaktır, bunun anlamı, kod içerisindeki boşlukların ve yeni satır boşluklarının kaldırılması, değişken isimlerinin kısaltılmasıdır."

Bunu neden yaparız kısaca anlatmaya çalışayım.

Uygulama canlıya (production)'a geçtiğinden son kullanıcı (enduser) için hızlı çalışmasını isteriz. Bunun için temelde uygulamamızın ilk açılışta yüklemesi gereken css, javascript gibi dosyaların olabildiğince küçük olması için canlı 'da minified kullanırız.

Normal, daha büyük sürümleri ise uygulama geliştirme  (development) sırasında kod içerisinde  neler olduğunu ve işleyişin nasıl devam ettiğini görebilmek, gerektiğinde ya da hata ile karşılaşıldığında (bu kısım daha uzman arkadaşlar için geçerli) hatanın çevresinden dolanmak   (workaround),   vs.vs. için  kullanırız.

Bu yazıyı okuyorsanız son paragrafta yazan kısmı dikkate almadan minified kullanarak hayatınıza devam etmenizi tavsiye ediyorum.


Wednesday, March 14, 2012

JQuery öğrenmek için en iyi kaynak.


Şimdiye kadar jquery ile ilgili bir çok site, döküman ve e-kitap okudum fakat daha önce hiç  Earle Castledine ve Craig Sharkie 'in yazmış oldukları "Sitepoint jQuery Novice to Ninja" kitabı gibi bir kitap ya da döküman okumamıştım. Biraz abartılı bir ifade de olsa kitap gerçekten çok başarılı. Eğer jquery ile ilgili detaylı ve gelişmiş bilgi sahibi olmak istiyorsanız mutlaka bu kitaba sahip olmalısınız.

Aşağıda kitabı bulabileceğiniz link' li veriyorum.

Best Tutorial for JQuery

I've searched and read a lot of documents, web pages and e-books but I have never seen such a wonderful document like Sitepoint jQuery Novice to Ninja by Earle Castledine and Craig Sharkie.

Thanks a lot for great e-book.

this is the link you may find the book


What does "minified" mean for jquery?

shortly minified means compressed.

my favorite jquery e-book (Sitepoint jQuery Novice to Ninja by EARLE CASTLEDINE AND CRAIG SHARKIE) says,

"Typically, you’ll want to use the minified version for your production code, where the jQuery source code is compressed: spaces and line breaks have been removed and variable names are shortened.
The result is exactly the same jQuery library, but contained in a JavaScript file that’s much smaller than the original. This is great for reducing bandwidth costs for you, and speeding up page requests for the end user."