Showing posts with label JQuery. Show all posts
Showing posts with label JQuery. Show all posts

Monday, 22 August 2016

Custom File manager in CKEditor


Let’s take CKEditorTest.html. Write below code to use CKEditor in your html page.

<script src="~/Scripts/ckeditor/ckeditor.js"></script>
<script src="~/Scripts/ckeditor/adapters/jquery.js"></script>

<div class="row">    
    <textarea id="txtEditor"></textarea>
</div>

<script>
$(document).ready(function () {

 // Change in CKEditor config allow to set custom file browser Url 
        CKEDITOR.editorConfig = function (config) {

            // Enter Url of your target page which 
                you wants to open on browse button click.
            config.filebrowserBrowseUrl = "http://localhost:12081/filemanager.html";
        }        

        $('#txtEditor').ckeditor();
    });
</ script>

The above script will create instance of CKEditor and also set custom file browser window.

Now in filemanager.html page, Add below script to select file and set in parent CKEditor window. 

<script>
    $(document).ready(function () {
        $("jquery selector").click(function () {

            //  Source path of file
            var url = this.src;
            var parentWindow = (window.parent == window) ? window.opener : window.parent;

            // Find Function number from Querystring
            var funcNum = QueryString('CKEditorFuncNum');

            if (parentWindow['CKEDITOR']) {
                // Invoke function
                parentWindow['CKEDITOR'].tools.callFunction(funcNum, url);
                window.close();
            }
        });
    });

    function QueryString(name) {
        name = name.replace(/[\[]/"\\[").replace(/[\]]/"\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g" "));
    }
</script>

Hooray ! Now you can create your custom file manager with your own settings.

Friday, 8 April 2016

Allow Cross-Origin Requests in Web API

Let’s see how to allow web API to be called from JQuery. 

Browser prevents a web page from making AJAX requests to another domain. This is called the same-origin policy, and prevents a malicious site from reading sensitive data from another site.

But What will do if you create a web API to be called by other websites. You have to allow then to call your API.  Cross Origin Resource Sharing (CORS) allows a server to come over this policy. You can allow specific origins to access your web API.  

Let’s understand with an example.

Let’s create a Web API first :  I am not going to spoon feed you to create web API. I hope you know how to create web API application. Great.. 

Let’s take a APIController :

      using System.Web.Http.Cors;
[EnableCors(origins: "http://localhost:12081", headers: "*", methods: "*")]
public class ValuesController : ApiController
      {        
         public IEnumerable<string> Get()
         {
            return new string[] { "value1""value2" };
         }       
 }

Ooops, what is EnableCors ?
You have to install a nuget package to get this. Write below command in package manager console :
Install-Package Microsoft.AspNet.WebApi.Cors

 Next step to register CORS from global.asax :

         public static void Register(HttpConfiguration config)
        {
            config.EnableCors();                    
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }

Yeah, Your web API is ready to be accessed from origin ‘http://localhost:12081’.

Do I have any option to allow multiple origin ?  
  
Of course Yes.    You can set number of origin by comma separated value like http://localhost:12081http://www.heros.com, http://www.xyss.com’. Or you can allow all origin by putting ‘*

[EnableCors(origins: "*", headers: "*", methods: "*")]

Note : Don’t include forward slash at the end of url. E.g ‘http://localhost:12081/


Now call API from JQuery :
 jQuery.ajax({
            type: "GET",
            url: 'http://192.168.1.118:85/api/values',                        
            success: function (data) {
                alert(JSON.stringify(data));
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("error");
            }
        });


Hooray!! it’s working...

Thursday, 6 November 2014

JQuery issue after partial postback

I came to know this theory after much R&D. I was not aware why JQuery is not get fired after partial postback. Then from google, I found solution as below. We have to register JQuery events after end of partial postback.

<asp:ScriptManager ID="smngr" runat="server"></asp:ScriptManager>
        <asp:UpdatePanel ID="upanel" runat="server">
            <ContentTemplate>
                <asp:Button ID="btn" Text="Test" runat="server" OnClick="btn_Click" />
                <input type="button" value="check" id="btncheck" />
            </ContentTemplate>
        </asp:UpdatePanel>

<script>

        Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequestHandler)
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler)

        function beginRequestHandler() {
            var btn = document.getElementById('<%= btn.ClientID %>');
            btn.disabled = "disabled";
        }

        function endRequestHandler() {
            var btn = document.getElementById('<%= btn.ClientID %>');
            btn.disabled = "";
            register();
        }

        $(document).ready(function () {
            register();
        });

        function register()
        {
            $("#btncheck").click(function () {
                alert("Hello");
            });
        }


    </script>

Wednesday, 11 June 2014

Select / DeSelect Checkbox using JQuery


HTML:


<table>
            <tr>
                <th>
                    <input type="checkbox" class="cbHeader" />
                </th>
                <th>Name
                </th>
                <th>City
                </th>
            </tr>
            <tr>
                <td>
                    <input type="checkbox" class="cbItems" />
                </td>
                <td>Ajay
                </td>
                <td>Mehsana
                </td>
            </tr>
            <tr>
                <td>
                    <input type="checkbox" class="cbItems" />
                </td>
                <td>Hitesh
                </td>
                <td>Kalol
                </td>
            </tr>
            <tr>
                <td>
                    <input type="checkbox" class="cbItems" />
                </td>
                <td>Vishal
                </td>
                <td>Ahmedabad
                </td>
            </tr>
            <tr>
                <td>
                    <input type="checkbox" class="cbItems" />
                </td>
                <td>Matang
                </td>
                <td>Bopal
                </td>
            </tr>
        </table>


Javascript:


     $(document).ready(function () {
            $(".cbHeader").change(function () {
                $(".cbItems").prop("checked", $(this).is(":checked"));
            });

            $(".cbItems").change(
            function () {
                if ($(".cbItems").length == $(".cbItems:checked").length) {
                    $(".cbHeader").prop("checked", true);
                }
                else {
                    $(".cbHeader").prop("checked", false);
                }
            });

        })