working on it ...

Filters

Explore Public Snippets

Sort by

Found 3,369 snippets matching: ajax

    public by micurs modified Dec 23, 2013  747225  18  7  1

    JQuery typescript interface for $.ajax() callbacks

    To use JQuery $.ajax() you must define your callback functions with the following interfaces
    interface OnSuccessAjaxCallback {
      (data: any, textStatus?: string, jqXHR?: JQueryXHR): any;
    }
    interface OnErrorAjaxCallback {
      (jqXHR?: JQueryXHR, textStatus?: string, errorThrow?: string) : any;
    }
    

    public by sTiLL-iLL @ SniPitz-KND modified Dec 1, 2015  531815  2  8  21

    Ajax again?? Wrap it!! XHR Agent 4Ya

    XHR wrapper! object pooling and cueing!!! EveryOneZ dOing IT!
    
    var myXHR = {
           ESpec: function (wrap, evt) {
               return { xhrWrap: wrap, event: evt };
           },
           Agent: function(maxConnect) {
               var bCued = [], slf = this,
                   max = maxConnect || 3;
                   this.curCon = 0;
               function inCue() {
                   if (self.bCued < max) {
                       self.bCued++;
                       var itm = is.Readied.shift();
                       itm.evt.addEventListener(['EVENT_COMPLETE'], 
                         function (e) {
                             self.bCued--;
                             if (this.Readied.length !== 0) {
                               inCue();
                             }
                         });
                       itm.wrap.call(itm, args, itm.evt);
                    }
               }
               this.Readied = function (ESpec) {
                   bCued.push(ESpec);
                   inCue();
                   return ESpec.evt;
               };
            }
       };
    
                

    public by cynarasys modified Dec 20, 2014  488022  9  4  1

    AJAX Request

    AJAX Request: ajax.php
    <script type="text/javascript">
        $('form').submit(function () {
            $('form button').attr("disabled", "disabled");
            $('#loading').fadeIn();
            $('#msj').html('');
            $.post('<?php echo Flight::base_url('contacto'); ?>', $('form').serializeArray(), function (d) {
                $('#loading').fadeOut();
                $('form button').removeAttr('disabled');
                $('#msj').html(d.msj);
                $('html, body').animate({scrollTop: $("#msj").offset().top}, 500);
                if (d.status === true) {
                    $('form').slideUp();
                } else {
                    $('#captcha').attr('src','<?php echo Flight::base_url('captcha'); ?>?' + Math.random());
                }
            }, 'json');
            return false;
        });
    </script>
    
    

    public by alaindresse modified Feb 22, 2013  370544  3  6  0

    Gist to demonstrate ajax request on checkbox

    Gist to demonstrate ajax request on checkbox: ajax-checkbox.tag ajaxCheckbox.java main.js view.jsp
    // Tagfile to be placed in WEB-INF/tags/ui
    
    <%@tag import="com.liferay.portal.kernel.util.HtmlUtil"%>
    <%@tag import="com.liferay.portal.kernel.language.LanguageUtil"%>
    <%@tag import="com.liferay.portal.kernel.util.StringPool"%>
    <%@tag import="com.liferay.portal.util.PortalUtil"%>
    <%@ attribute 
    	name="resourceUrl"
    	description="URL to process the ajax call. ServeResource parameter: newValue (0 or 1 for unchecked, checked). responseData is not used. An alert is open on failure."
    	type="String" 
    	required="true" %>
    <%@ attribute
    	name="name"
    	description="Checkbox name. A random name is set if this is not provided."
    	type="String"%>
    <%@ attribute
    	name="label"
    	description="Checkbox label"
    	type="String"
    	required="true" %>
    <%@ attribute
    	name="initialValue"
    	description="Initial value of checkbox"
    	type="Boolean"
    	required="true" %>
    <%@ attribute
    	name="successCallback"
    	description="ajax callback on success. Parameters are: checkbox node, response data."
    	type="String" %>
    <%@ attribute
    	name="failureCallback"
    	description="Callback on failure. Parameter is checkbox name."
    	type="String" %>
    	
    <%@ taglib uri="http://liferay.com/tld/theme" prefix="theme" %>
    <%@ taglib uri="http://java.sun.com/portlet" prefix="portlet" %>
    <%@ taglib uri="http://alloy.liferay.com/tld/aui" prefix="aui" %>
    <portlet:defineObjects />
    <theme:defineObjects />
    
    <%
    if (name == null){
    	name = PortalUtil.generateRandomKey(request, "ajaxToggleKey");
    }
    String onclick = "bb_ajaxCheckbox('" + resourceUrl  + "', this, " + successCallback + "," + failureCallback + ")";
    %>
    <aui:input type="checkbox" onClick="<%=onclick%>" value="<%=initialValue%>" name="<%=name%>" label="<%=label%>" /> 
    
    
    	@Override
    	public void serveResource(ResourceRequest resourceRequest,
    			ResourceResponse resourceResponse) throws IOException,
    			PortletException {
    		
    		_log.info("processing resource");
    		Map<String, String[]> parameters = resourceRequest.getParameterMap();
    		for (String key : parameters.keySet()){
    			_log.info(key + ":[" + StringUtil.merge(parameters.get(key)) + "]");
    		}
    
    
    		String resourceId = resourceRequest.getResourceID();
    		if (Validator.isNotNull(resourceId)) {
    			String cmd = resourceRequest.getResourceID();
    			if (cmd.equals("testToggle")) {
    				try {
    					boolean newValue = ParamUtil.getBoolean(resourceRequest,"newValue");
    					_log.info(String.valueOf(newValue));
    					if (!newValue){
    						throw new IOException("simulate failure");
    					} else {
    						resourceResponse.setContentType("text/plain");
    						resourceResponse.getWriter().write("this is the response data");
    					}
    				} catch(Exception e){
    					throw new IOException(e);
    				}
    			}
    		}
    		super.serveResource(resourceRequest, resourceResponse);
    	}
    
    
    Liferay.provide(
    	window, 
    	"bb_ajaxCheckbox",
    	function(resourceUrl, checkbox, success, failure){
    		var A = AUI();
    		var checked = false;
    		var checkbox = A.one(checkbox);
    		var label = null;
    		if (checkbox) {
    			checked = checkbox.attr('checked');
    			var labelSelector = 'label[for="' + checkbox.attr("name") + '"]';
    			if (labelSelector) label = A.one(labelSelector);
    		}
    		var ajaxCallbacks = {
    			success: function(){
    				if (label) label.removeClass("ajax-loading");
    				if (success) success(checkbox, this.get('responseData'));
    			},
    			failure: function(){
    				if (failure) failure(checkbox);
    			}
    		};
    		if (label) label.addClass("ajax-loading");
    		A.io.request(resourceUrl, {
    			method: 'GET',
    			data: {newValue: checked,},
    			on : ajaxCallbacks,
    		});
    	}, [ 'aui-io-request' ]
    );
    
    <%@ taglib tagdir="/WEB-INF/tags/ui" prefix="bamboost-ui"%>
    <%@ include file="/html/init.jsp"%>
    
    <portlet:resourceURL id="testToggle" var="testToggleURl"/>
    <bamboost-ui:ajax-checkbox
    	name="myname" 
    	resourceUrl="<%=testToggleURl %>" 
    	initialValue="true"
    	label="no callback"/>
    <bamboost-ui:ajax-checkbox
    	resourceUrl="<%=testToggleURl %>" 
    	initialValue="true"
    	label="testSuccess"
    	successCallback="testSuccess"/>
    <bamboost-ui:ajax-checkbox
    	resourceUrl="<%=testToggleURl %>" 
    	initialValue="true"
    	label="testFailure"
    	failureCallback="testFailure"/>
    	
    	<script>
    	function testSuccess(checkbox, responseData) {
    		alert(checkbox.attr("name") + "\n" + responseData);
    	};
    	function testFailure() {alert("failure");};
    	</script>
    
    

    public by ulhas_c modified Nov 20, 2014  121494  1  5  0

    Ajax Helpers

    using System;
    using System.Collections.Generic;
    using System.Web.Mvc;
    using System.Web.Mvc.Ajax;
    using System.Web.Routing;
    
    namespace EBS.Recruitment.PL.Helpers
    {
        public static class AjaxHelperExtensions
        {
            public static MvcHtmlString RenderAction(this AjaxHelper ajaxHelper, string actionName, string controllerName, AjaxOptions ajaxOptions)
            {
                return ajaxHelper.RenderAction(null, actionName, controllerName, null, ajaxOptions, null);
            }
            public static MvcHtmlString RenderAction(this AjaxHelper ajaxHelper, string id, string actionName, string controllerName, AjaxOptions ajaxOptions)
            {
                return ajaxHelper.RenderAction(id, actionName, controllerName, null, ajaxOptions, null);
            }
            public static MvcHtmlString RenderAction(this AjaxHelper ajaxHelper, string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions)
            {
                var routeValues1 = new RouteValueDictionary(routeValues);
                return ajaxHelper.RenderAction(null, actionName, controllerName, routeValues1, ajaxOptions, null);
            }
            public static MvcHtmlString RenderAction(this AjaxHelper ajaxHelper, string id, string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions)
            {
                var routeValues1 = new RouteValueDictionary(routeValues);
                return ajaxHelper.RenderAction(id, actionName, controllerName, routeValues1, ajaxOptions, null);
            }
            public static MvcHtmlString RenderAction(this AjaxHelper ajaxHelper, string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes)
            {
                var routeValues1 = new RouteValueDictionary(routeValues);
                var routeValueDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
                return ajaxHelper.RenderAction(null, actionName, controllerName, routeValues1, ajaxOptions, routeValueDictionary);
            }
            public static MvcHtmlString RenderAction(this AjaxHelper ajaxHelper, string id, string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes)
            {
                var routeValues1 = new RouteValueDictionary(routeValues);
                var routeValueDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
                return ajaxHelper.RenderAction(id, actionName, controllerName, routeValues1, ajaxOptions, routeValueDictionary);
            }
            public static MvcHtmlString RenderAction(this AjaxHelper ajaxHelper, string actionName, string controllerName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)
            {
                return ajaxHelper.RenderAction(null, actionName, controllerName, routeValues, ajaxOptions, htmlAttributes);
            }
            public static MvcHtmlString RenderAction(this AjaxHelper ajaxHelper, string id, string actionName, string controllerName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)
            {
                string targetUrl = UrlHelper.GenerateUrl((string)null, actionName, controllerName, routeValues, ajaxHelper.RouteCollection, ajaxHelper.ViewContext.RequestContext, true);
                return MvcHtmlString.Create(GenerateDiv(ajaxHelper, id, targetUrl, ajaxOptions, htmlAttributes));
            }
            private static string GenerateDiv(AjaxHelper ajaxHelper, string id, string targetUrl, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)
            {
                id = string.IsNullOrEmpty(id) ? Guid.NewGuid().ToString() : id;
                var tagBuilder = new TagBuilder("div")
                {
                };
                if (string.IsNullOrEmpty(ajaxOptions.UpdateTargetId))
                {
                    ajaxOptions.UpdateTargetId = id;
                }
                else
                {
                    ajaxOptions.UpdateTargetId += ",#" + id;
                }
                tagBuilder.MergeAttribute("id", id);
                tagBuilder.MergeAttributes(htmlAttributes);
                tagBuilder.MergeAttribute("data-ajax-href", targetUrl);
                tagBuilder.MergeAttributes(ajaxOptions.ToUnobtrusiveHtmlAttributes());
                return tagBuilder.ToString(TagRenderMode.Normal);
            }
        }
    }

    public by bbatsche modified Oct 15, 2014  2700  1  6  19

    Ajax Request

    Ajax Request: laravel-ajax.php
    {{ link_to_action('PostsController@edit', 'Edit', $post->id, array('class' => 'btn btn-default')) }}
    <button type="button" class="btn btn-danger delete-btn" data-post-id="{{{ $post->id }}}">Delete</button>
    
    <script>
        var csrfToken = "{{{ Session::get('_token') }}}";
        
        $(".delete-btn").click(function() {
            var postId = $(this).data('post-id');
    
            if (confirm('Are you sure you want to delete this post?')) {
                $.ajax({
                    url: '/posts/' + postId,
                    type: 'post',
                    data: {
                        _token: csrfToken,
                        _method: 'delete'
                    },
                    success: function(data) {
                        // Alert success
                    }
                });
            }
        });
    </script>
    
    

    public by sTiLL-iLL modified Aug 31, 2014  2115  0  7  18

    XHR + a fallback...

    ...so krappy old browsers can do ajax to!
    // simple request with a fallback
    
    function getAjax() { 
      if (window.XMLHttpRequest) {
        return new XMLHttpRequest(); 
      } 
      try { 
        return new ActiveXObject('MSXML2.XMLHTTP.6.0');
      }
      catch (err) { 
        try { 
          // fallback.
          return new ActiveXObject('MSXML2.XMLHTTP.3.0');
        }
        catch (err) { 
          alert('AJAX is not enabled.'); 
          return null;
        } 
      } 
    }

    public by lando2319 modified Apr 21, 2014  2849  0  5  6

    ajax request

    ajax request: gistfile1.txt
    function ChangeStackupStatusPlayers(stackup_number) {
      $.ajax({
        type: "PUT",
        url: "/stackups/" + stackup_number,
        data: { stackup_status: false },
        dataType: 'script'
      })
    //  $('#stackup_button' + stackup_number).hide();
    
    //$('#stackup_button')
    //  stackup_id = parent().attr('id')
    //$("#player_button_span").html("Pending");
      //var = this.id;
      console.log(stackup_number);
    //  console.log(event.data.stackup_status);
    }
    
    
    
    html file
     <div id="<%= stackup.id %>">
                <button class="btn btn-xs" style="margin-top:0px;" id="stackup_button<%= stackup.id %>" onclick="ChangeStackupStatusPlayers(<%= stackup.id %>);"><i class="glyphicon glyphicon-tasks"></i><span id="button_span"> <%= stackup.status_message %></span></button>
              </div>
    
    

    public by zonaro modified Nov 18, 2015  3385  6  8  3

    AJAX port for C#

    This is not a genuine Ajax Request but have the same behavior. Simply call the AJAX.GET, AJAX.POST or AJAX.JSON methods.
    public class AJAX
       {
           public static string GET(string URL)
           {
               string data = "";
               if (!string.IsNullOrWhiteSpace(URL))
               {
                   try
                   {
                       WebClient client = new WebClient();
                       client.Encoding = Encoding.UTF8;
                       data = client.DownloadString(URL);
                       client.Dispose();
                   }
                   catch (Exception ex)
                   {
                       data = ex.Message;
                   }
               }
               return data;
    
           }
    
           public byte[] GETFile(string URL)
           {
               using (WebClient Client = new WebClient())
               {
                   return Client.DownloadData(URL);
               }
           }
    
           public object POST(string URL, string PostData)
           {
    
               WebRequest request = WebRequest.Create("");
               request.Method = "POST";
               byte[] byteArray = Encoding.UTF8.GetBytes(PostData);
               request.ContentType = "application/x-www-form-urlencoded";
               request.ContentLength = byteArray.Length;
               Stream dataStream = request.GetRequestStream();
               dataStream.Write(byteArray, 0, byteArray.Length);
               dataStream.Close();
               WebResponse response = request.GetResponse();
               Console.WriteLine(((HttpWebResponse)response).StatusDescription);
               dataStream = response.GetResponseStream();
               StreamReader reader = new StreamReader(dataStream);
               string responseFromServer = reader.ReadToEnd();
               reader.Close();
               dataStream.Close();
               response.Close();
               return responseFromServer;
           }
    
           public void POSTFile(string URL, FileInfo TheFile)
           {
               using (System.Net.WebClient wc = new System.Net.WebClient())
               {
                   wc.UploadFile(URL, TheFile.FullName);
               }
           } 
    
           public static dynamic JSON(string URL)
           {
               string json = GET(URL);
               dynamic result = new JavaScriptSerializer().Deserialize<dynamic>(json);
               return result;
           }
    
    
       }
    

    public by Aysad Kozanoglu modified Apr 10, 2016  1306  23  3  0

    Cordova Camera Plugin cordova-plugin-camera upload jquery ajax to server request

    Cordova Camera Plugin cordova-plugin-camera upload jquery ajax to server request: cordova-plugin-camera-index.html
    <!DOCTYPE html>
    <!-- Aysad Kozanoglu -->
    <html>
      <head>
        <title>foto cek</title>
    	<style>
    	html {
    		-webkit-user-select: none;
    	}
    	</style>
    	<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;" />
    	<script type="text/javascript" charset="utf-8" src="js/jquery.js"></script>
        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    
        <script type="text/javascript" charset="utf-8">
    
        var pictureSource;   // picture source
        var destinationType; // sets the format of returned value
    
        // Wait for device API libraries to load
        //
    		function onLoad() {
    			document.addEventListener("deviceready", onDeviceReady, false);
    		}
    
        // device APIs are available
        //
        function onDeviceReady() {
            pictureSource=navigator.camera.PictureSourceType;
            destinationType=navigator.camera.DestinationType;
    
        }
    
        // Called when a photo is successfully retrieved
        //
        function onPhotoDataSuccess(imageData) {
    		var smallImage = document.getElementById('smallImage');	
    	  
    		smallImage.style.display = 'block';
    		smallImage.src = "data:image/jpeg;base64," + imageData;
    		fotoUpload(imageData);
        }
    
        // A button will call this function
        //
        function capturePhotoEdit() {
          // Take picture using device camera, allow edit, and retrieve image as base64-encoded string
          navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
            destinationType: destinationType.DATA_URL });
        }
    
    
        // Called if something bad happens.
        //
        function onFail(message) {
          alert('Failed because: ' + message);
        }
    
        </script>
      </head>
      <body onload="onLoad()">
    	<center>
    	<img src="logo.png" width="50%" border=0>
    	<br>
    	<h1>Entwicklungsumgebung</h1>
    	<br>
    	Kamera Photoschuss und upload Server
    	<br><br><br><br>
    	 <button onclick="capturePhotoEdit();" style="height:60px;width:80%">Photo Schnappschuss</button>
    	 <br><br><br>
    	 <a href="http://5.45.96.121/upload/" target ="_blank"> <h2>Bilder auf dem Server ansehen </h2></a>
    	 <br><br><br>
    	<div id="ajaxStatus"></div>
    	<img style="display:none;width:50%" id="smallImage" src="" />
    	<br><br><font size="-2"> Erfinder: Levent Yakar <br> Architekt: Aysad Kozanoglu
    
    	<script type="text/javascript" charset="utf-8">
          	$(document).ready(function(){
            $("#ajaxStatus").html("ein Bild aufnehmen");
          
          });	
          function fotoUpload(imageData){
          	//alert(imageData);
          	$.ajax({
          		type: "POST",
          		url: "http://5.45.96.121/upload/up2.php",
          		data: { img_data:imageData},
          		cache: false,
          		contentType: "application/x-www-form-urlencoded",
          		success: function (result) {
          			alert("upload OK: "+ result);
          		}
          	});		
          	$("#ajaxStatus").html("bild hochgeladen");
          }
    	</script>
      </body>
    </html>
    
    
    • Public Snippets
    • Channels Snippets