Search Results

Search found 79 results on 4 pages for 'encodeuricomponent'.

Page 3/4 | < Previous Page | 1 2 3 4  | Next Page >

  • JQuery Ajax error handling, show custom exception messages

    Hey Folks, I am wondering if there is some way where I can show custom exception messages as an alert in my Jquery ajax error message. For example, say if I want to throw an exception in server side via Struts by "throw new ApplicationException("User name already exists");", I want to catch this message(User name already exists) in Jquery ajax error message. jQuery("#save").click(function(){ if(jQuery('#form').jVal()){ jQuery.ajax({ type: "POST", url: "saveuser.do", dataType:"html", data:"userId="+encodeURIComponent(trim(document.forms[0].userId.value)), success:function(response){ jQuery("#usergrid").trigger("reloadGrid"); clear(); alert("Details saved successfully!!!"); }, error:function (xhr, ajaxOptions, thrownError){ alert(xhr.status); alert(thrownError); } }); } } ); On the second alert where I alert thrown error, I am getting undefined and the status code is 500. I am not sure where I am going wrong. Please let me know on this. Thanks, Dukes

    Read the article

  • InvalidAuthenticityToken for JQuery despite setting authenticity token

    - by user117046
    I'm getting an InvalidAuthenticityToken despite adding in corresponding authenticity tokens in the jquery response. Is there an error in the code, or is there another, root problem? I appreciate any comments. Thanks! Using: Rails 2.3.3, Ruby 1.8.6, Webrick, JQuery 1.3.2 layout/networks.html.haml = token_tag = javascript_tag "window.AUTH_TOKEN = '#{form_authenticity_token}';" javascripts/application.js $(document).ready(function() { // All non-GET requests will add the authenticity token // if not already present in the data packet $(document).ajaxSend(function(event, request, settings) { if (typeof(window.AUTH_TOKEN) == "undefined") return; // <acronym title="Internet Explorer 6">IE6</acronym> fix for http://dev.jquery.com/ticket/3155 if (settings.type == 'GET' || settings.type == 'get') return; settings.data = settings.data || ""; settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(window.AUTH_TOKEN); }); ajaxLinks(); }); The rendered html has: <input name="authenticity_token" type="hidden" value="ZaXj3ACQl+8JKtaDAUoxtSsqzEagSPyHbS25ai9qWCw=" /> <script type="text/javascript"> //<![CDATA[ window.AUTH_TOKEN = 'ZaXj3ACQl+8JKtaDAUoxtSsqzEagSPyHbS25ai9qWCw='; //]]> </script> and breakpointing through, shows that window.AUTH_TOKEN has been set. Any help to resolve this would be great.

    Read the article

  • Uploadify and rails 3 authenticity tokens

    - by Ceilingfish
    Hi chaps, I'm trying to get a file upload progress bar working in a rails 3 app using uploadify (http://www.uploadify.com) and I'm stuck at authenticity tokens. My current uploadify config looks like <script type="text/javascript" charset="utf-8"> $(document).ready(function() { $("#zip_input").uploadify({ 'uploader': '/flash/uploadify.swf', 'script': $("#upload").attr('action'), 'scriptData': { 'format': 'json', 'authenticity_token': encodeURIComponent('<%= form_authenticity_token if protect_against_forgery? %>') }, 'fileDataName': "world[zip]", //'scriptAccess': 'always', // Incomment this, if for some reason it doesn't work 'auto': true, 'fileDesc': 'Zip files only', 'fileExt': '*.zip', 'width': 120, 'height': 24, 'cancelImg': '/images/cancel.png', 'onComplete': function(event, data) { $.getScript(location.href) }, // We assume that we can refresh the list by doing a js get on the current page 'displayData': 'speed' }); }); </script> But I am getting this response from rails: Started POST "/worlds" for 127.0.0.1 at 2010-04-22 12:39:44 ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken): Rendered /opt/local/lib/ruby/gems/1.8/gems/actionpack-3.0.0.beta3/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.0ms) Rendered /opt/local/lib/ruby/gems/1.8/gems/actionpack-3.0.0.beta3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (6.6ms) Rendered /opt/local/lib/ruby/gems/1.8/gems/actionpack-3.0.0.beta3/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (12.2ms) This appears to be because I'm not sending the authentication cookie along with the request. Does anyone know how I can get the values I should be sending there, and how I can make rails read it from HTTP POST rather than trying to find it as a cookie?

    Read the article

  • dynamic link_to_remote in rails with jquery

    - by Claus Lensbøl
    Hi I'm trying to pass a string with a link_to_remote call as the :id, and the string should be collected from an input field with and id of "movie_title". <div id="search_list">Nothing here yet</div> <br /> <% semantic_form_for @movie do |f| %> <% f.inputs do -%> <%= f.input :title, :class => "movie_title" %> <%= link_to_remote( 'Search...', { :url => { :action => :imdb_search, :id => "'+$('\#movie_title').value+'" } }, { :title => "Search for this movie", :class => "imdb_search" } ) -%> [...removed text that does not matter...] <% end -%> <%= f.buttons %> <% end %> I keep getting an javascript error, and if I remove the # from the jquery in the link, it returns "Undefined". The link I get is: <a class="imdb_search" href="#" onclick="jQuery.ajax({data:'authenticity_token=' + encodeURIComponent('yHPHYTZsPTQLi9JYSauUYcoie/pqPPk2uHBTN0PzNsQ='), dataType:'script', type:'post', url:'/movies/imdb_search/'+$('%23movie_title').value+''}); return false;" title="Search for this movie">Search...</a> So I want the link updated with the contents of movie_title. How do I do that?

    Read the article

  • Java to JavaScript (Encryption related)

    - by balexandre
    Hi guys, I'm having difficulties to get the same string in Javascript and I'm thinking that I'm doing something wrong... Java code: import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.GregorianCalendar; import sun.misc.BASE64Encoder; private static String getBase64Code(String input) throws UnsupportedEncodingException, NoSuchAlgorithmException { String base64 = ""; byte[] txt = input.getBytes("UTF8"); byte[] text = new byte[txt.length+3]; text[0] = (byte)239; text[1] = (byte)187; text[2] = (byte)191; for(int i=0; i<txt.length; i++) text[i+3] = txt[i]; MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text); byte digest[] = md.digest(); BASE64Encoder encoder = new BASE64Encoder(); base64 = encoder.encode(digest); return base64; } I'm trying this using Paj's MD5 script as well Farhadi Base 64 Encode script but my tests fail completely :( my code: function CalculateCredentialsSecret(type, user, pwd) { var days = days_between(new Date(), new Date(2000, 1, 1)); var str = type.toUpperCase() + user.toUpperCase() + pwd.toUpperCase() + days; var md5 = hex_md5(str); var b64 = base64Encode(md5); return encodeURIComponent(b64); } Does anyone know how can I convert this Java method into a Javascript one? Thank you Tests (for today, 3740 days after January 1st, 2000 var secret = CalculateCredentialsSecret('AAA', 'BBB', 'CCC'); // secret SHOULD be: S3GYAfGWlmrhuoNsIJF94w==

    Read the article

  • How to send parameters with same encoding from javascript?

    - by nimcap
    I have a javascript file that lots of people have embedded to their pages. Since I am hosting the file, I have control over that javascript file; I cannot control the way it is embedded because lots of people is using it already. This javascript file sends GET requests to my servlets, and the parameters passed with the request are recorded to DB. For example, javascript sends a request to http://myserver.com/servlet?p1=123&p2=aString and then servlet records 123 and aString to DB somehow. Before sending strings I use encodeURIComponent() to encode it. But what I figured out is every client sends the same string with different encodings depending on either their browser or the site they are visiting. As a result, same strings are represented with different characters when it reaches servlet (so they are different strings). What I am trying to do is to convert the strings to one kind of encoding from javascript so when they reach the client same words are represented with same characters. How is this possible? PS. If there is a way to convert the encoding from Java it is also applicable.

    Read the article

  • JavaScript cookie value can't be retrieved in Django

    - by Boris Rusev
    I am trying to build a web site in both English and Bulgarian using the Django framework. My idea is the user should click on a button, the page will reload and the language will be changed. This is how I am trying to do it: In my html I hava a the button tag <button id='btn' onclick="changeLanguage();" type="button"> ... </button> An excerpt from cookies.js: function changeLanguage() { if (getCookie('language') == 'EN') { document.getElementById('btn').innerHTML = getCookie('language'); setCookie("language", 'BG'); } else { document.getElementById('btn').innerHTML = getCookie('language'); setCookie("language", 'EN'); } } function setCookie(sName, sValue, oExpires, sPath, sDomain, bSecure) { var sCookie = sName + "=" + encodeURIComponent(sValue); if (oExpires) { sCookie += "; expires=" + oExpires.toGMTString(); } if (sPath) { sCookie += "; path=" + sPath; } if (sDomain) { sCookie += "; domain=" + sDomain; } if (bSecure) { sCookie += "; secure"; } document.cookie = sCookie; } And in my views.py file this is the situation @base def index(request): if request.session['language'] == 'EN': return """<b>%s</b>""" % "Home" else request.session['language'] == 'BG': return """<b>%s</b>""" % "??????" So I know that my JS changes the value of the language cookie but I think Django doesn't get that. On the other hand when I set and get the cookie in my Python code again the cookie is set. My question is whether there is a way to make JS and Django work together - JavaScript sets the cookie value and Python only reads it when asked and takes adequate actions? Thank you.

    Read the article

  • XMLHttpRequest POST Data Size

    - by usurper
    Hi, Is there a size limit to a XHR POST request? I am using the POST method for saving textdata into MySQL using PHP script and the data is cut off. Firebug sends me the following message: ... Firebug request size limit has been reached by Firebug. ... This is my code for sending the data: function makeXHR(recordData) { xmlhttp = createXHR(); var body = "q=" + encodeURIComponent(recordData); xmlhttp.open("POST", "insertRowData.php", true); xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlhttp.setRequestHeader("Content-length", body.length); xmlhttp.setRequestHeader("Connection", "close"); xmlhttp.onreadystatechange = function() { if(xmlhttp.readyState == 4 && xmlhttp.status == 200) { //alert(xmlhttp.responseText); alert("Records were saved successfully!"); } } xmlhttp.send(body); } The only solution I can think of is splitting the data and making a queue of XHR requests but I don't like it. Is there another way?

    Read the article

  • Get href tags in html data in c#

    - by Nani
    I am using web client class to HTML data from a web page. Now I want to get the complete href tags and there titles from the HTML data. Initially I used loops, Felling inefficient I switched to regExp, but dint got efficient solution. He is the initial code: for (int i = 0; i < htmldata.Length - 5; i++) { if (htmldata.Substring(i, 5) == "href=") { n1 = htmldata.Substring(i + 6, htmldata.Length - (i + 6)).IndexOf("\""); Sublink = htmldata.Substring(i + 6, n1); var absoluteUri = new Uri(baseUri, temp); n2 = htmldata.Substring(i + n1 + 1, htmldata.Length - (i + n1 + 1)).IndexOf("<"); subtitle = htmldata.Substring(i + 6 + n1 + 2, n2 - 7); } } This code is getting some of the links like this. /l.href.replace(new RegExp( /advanced_search?hl=en&q=&hl=en& and titles like this onclick=gbar.qs(this) class=gb2Photos ")+"q="+encodeURIComponent(b)})}i.qs=n;function o(a,b,d,c,f,e){var g=document.getElementById(a);if(g){var Which are absolutely invalid. Please suggest me the correct code for getting valid relative href links and titles. ThankYou.

    Read the article

  • Asynchronous javascript issue

    - by amit
    I am trying to create a function which takes values from various html elements of the page to create a string and pass on to a variable. now this works great for all browsers except IE 8 and 9. IE tends to skip the part of fetching the values and goes straight to the variable and finds nothing.. is there a way to sync it all so that it works in IE? function seturl() { var qstring = returnQString(); $('span.keyword').text($.trim($('#hdnKeyWord').attr('value'))); $('input.search_box').attr('value', $.trim($('#hdnKeyWord').attr('value'))); $('#hdnSearchKeyword').attr('value', $.trim($('#hdnKeyWord').attr('value'))); $(".search_box").val($.trim($("#hdn_span_hdnKeyWord").text())); $(".header_inner input[type='text']").focus(); $(".search_term input[type='text']").focus(); $('#locationurl').attr('value', qstring); } function returnQString(){ var qstring = $.trim($('#locationurl').attr('init')); //initial value of the url qstring += "?type=" + $('#hdnSTSearch').attr('value'); // type of handler hit qstring += "&keyword=" + encodeURIComponent($('#hdnKeyWord').attr('value')); // keyword addition qstring += "&pagestart=" + $('#current_page').attr('value'); // pagestart(current page) addition qstring += "&pagesize=" + $('#show_per_page').attr('value'); // per page size addition qstring += "&facets=" // facetsearch $.each(selectedFilter.items, function (index, value) { qstring += value.filter + ","; }); qstring += "&selectedSection=" + selectedSection // Section Select return qstring; }

    Read the article

  • Java to JavaScript (Encryptation related)

    - by balexandre
    Hi guys, I'm having dificulties to get the same string in Javascript and I'm thinking that I'm doing something wrong... Java code: import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.GregorianCalendar; import sun.misc.BASE64Encoder; private static String getBase64Code(String input) throws UnsupportedEncodingException, NoSuchAlgorithmException { String base64 = ""; byte[] txt = input.getBytes("UTF8"); byte[] text = new byte[txt.length+3]; text[0] = (byte)239; text[1] = (byte)187; text[2] = (byte)191; for(int i=0; i<txt.length; i++) text[i+3] = txt[i]; MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text); byte digest[] = md.digest(); BASE64Encoder encoder = new BASE64Encoder(); base64 = encoder.encode(digest); return base64; } I'm trying this using Paj's MD5 script as well Farhadi Base 64 Encode script but my tests fail completly :( my code: function CalculateCredentialsSecret(type, user, pwd) { var days = days_between(new Date(), new Date(2000, 1, 1)); var str = type.toUpperCase() + user.toUpperCase() + pwd.toUpperCase() + days; var md5 = any_md5('', str); var b64 = base64Encode(md5); return encodeURIComponent(b64); } Does anyone know how can I convert this Java method into a Javascript one? Thank you

    Read the article

  • Anti-Forgery Request in ASP.NET MVC and AJAX

    - by Dixin
    Background To secure websites from cross-site request forgery (CSRF, or XSRF) attack, ASP.NET MVC provides an excellent mechanism: The server prints tokens to cookie and inside the form; When the form is submitted to server, token in cookie and token inside the form are sent by the HTTP request; Server validates the tokens. To print tokens to browser, just invoke HtmlHelper.AntiForgeryToken():<% using (Html.BeginForm()) { %> <%: this.Html.AntiForgeryToken(Constants.AntiForgeryTokenSalt)%> <%-- Other fields. --%> <input type="submit" value="Submit" /> <% } %> which writes to token to the form:<form action="..." method="post"> <input name="__RequestVerificationToken" type="hidden" value="J56khgCvbE3bVcsCSZkNVuH9Cclm9SSIT/ywruFsXEgmV8CL2eW5C/gGsQUf/YuP" /> <!-- Other fields. --> <input type="submit" value="Submit" /> </form> and the cookie: __RequestVerificationToken_Lw__=J56khgCvbE3bVcsCSZkNVuH9Cclm9SSIT/ywruFsXEgmV8CL2eW5C/gGsQUf/YuP When the above form is submitted, they are both sent to server. [ValidateAntiForgeryToken] attribute is used to specify the controllers or actions to validate them:[HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult Action(/* ... */) { // ... } This is very productive for form scenarios. But recently, when resolving security vulnerabilities for Web products, I encountered 2 problems: It is expected to add [ValidateAntiForgeryToken] to each controller, but actually I have to add it for each POST actions, which is a little crazy; After anti-forgery validation is turned on for server side, AJAX POST requests will consistently fail. Specify validation on controller (not on each action) Problem For the first problem, usually a controller contains actions for both HTTP GET and HTTP POST requests, and usually validations are expected for HTTP POST requests. So, if the [ValidateAntiForgeryToken] is declared on the controller, the HTTP GET requests become always invalid:[ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public class SomeController : Controller { [HttpGet] public ActionResult Index() // Index page cannot work at all. { // ... } [HttpPost] public ActionResult PostAction1(/* ... */) { // ... } [HttpPost] public ActionResult PostAction2(/* ... */) { // ... } // ... } If user sends a HTTP GET request from a link: http://Site/Some/Index, validation definitely fails, because no token is provided. So the result is, [ValidateAntiForgeryToken] attribute must be distributed to each HTTP POST action in the application:public class SomeController : Controller { [HttpGet] public ActionResult Index() // Works. { // ... } [HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult PostAction1(/* ... */) { // ... } [HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult PostAction2(/* ... */) { // ... } // ... } Solution To avoid a large number of [ValidateAntiForgeryToken] attributes (one attribute for one HTTP POST action), I created a wrapper class of ValidateAntiForgeryTokenAttribute, where HTTP verbs can be specified:[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class ValidateAntiForgeryTokenWrapperAttribute : FilterAttribute, IAuthorizationFilter { private readonly ValidateAntiForgeryTokenAttribute _validator; private readonly AcceptVerbsAttribute _verbs; public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs) : this(verbs, null) { } public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs, string salt) { this._verbs = new AcceptVerbsAttribute(verbs); this._validator = new ValidateAntiForgeryTokenAttribute() { Salt = salt }; } public void OnAuthorization(AuthorizationContext filterContext) { string httpMethodOverride = filterContext.HttpContext.Request.GetHttpMethodOverride(); if (this._verbs.Verbs.Contains(httpMethodOverride, StringComparer.OrdinalIgnoreCase)) { this._validator.OnAuthorization(filterContext); } } } When this attribute is declared on controller, only HTTP requests with the specified verbs are validated:[ValidateAntiForgeryTokenWrapper(HttpVerbs.Post, Constants.AntiForgeryTokenSalt)] public class SomeController : Controller { // Actions for HTTP GET requests are not affected. // Only HTTP POST requests are validated. } Now one single attribute on controller turns on validation for all HTTP POST actions. Submit token via AJAX Problem For AJAX scenarios, when request is sent by JavaScript instead of form:$.post(url, { productName: "Tofu", categoryId: 1 // Token is not posted. }, callback); This kind of AJAX POST requests will always be invalid, because server side code cannot see the token in the posted data. Solution The token must be printed to browser then submitted back to server. So first of all, HtmlHelper.AntiForgeryToken() must be called in the page where the AJAX POST will be sent. Then jQuery must find the printed token in the page, and post it:$.post(url, { productName: "Tofu", categoryId: 1, __RequestVerificationToken: getToken() // Token is posted. }, callback); To be reusable, this can be encapsulated in a tiny jQuery plugin:(function ($) { $.getAntiForgeryToken = function () { // HtmlHelper.AntiForgeryToken() must be invoked to print the token. return $("input[type='hidden'][name='__RequestVerificationToken']").val(); }; var addToken = function (data) { // Converts data if not already a string. if (data && typeof data !== "string") { data = $.param(data); } data = data ? data + "&" : ""; return data + "__RequestVerificationToken=" + encodeURIComponent($.getAntiForgeryToken()); }; $.postAntiForgery = function (url, data, callback, type) { return $.post(url, addToken(data), callback, type); }; $.ajaxAntiForgery = function (settings) { settings.data = addToken(settings.data); return $.ajax(settings); }; })(jQuery); Then in the application just replace $.post() invocation with $.postAntiForgery(), and replace $.ajax() instead of $.ajaxAntiForgery():$.postAntiForgery(url, { productName: "Tofu", categoryId: 1 }, callback); // Token is posted. This solution looks hard coded and stupid. If you have more elegant solution, please do tell me.

    Read the article

  • ruby regex, parsing html

    - by danwoods
    Hello all, I'm trying to parse some returned html to look for currently playing movies. The pattern I'm trying to match looks like: <span dir=ltr>Clash of the Titans</span> Of which there are several in the returned html. (the html is huge, I've posted a sample at the bottom) I'm trying get an array of the movie titles with the following command: titles = listings_html.split(/(<span dir=ltr>).*(<\/span>)/) But I'm not getting the results I'm expecting. Can anyone see a problem with my approach or regex? Returned html (I believe the 'markdown'formating will render the some of the html, but this is just an example): <script>window.gbar={};(function(){function h(a,b,d){var c="on"+b;if(a.addEventListener)a.addEventListener(b,d,false);else if(a.attachEvent)a.attachEvent(c,d);else{var f=a[c];a[c]=function(){var e=f.apply(this,arguments),g=d.apply(this,arguments);return e==undefined?g:g==undefined?e:g&&e}}};var i=window.gbar,k,l,m;function n(a){var b=window.encodeURIComponent&&(document.forms[0].q||"").value;if(b)a.href=a.href.replace(/([?&])q=[^&]*|$/,function(d,c){return(c||"&")+"q="+encodeURIComponent(b)})}i.qs=n;function o(a,b,d,c,f,e){var g=document.getElementById(a);if(g){var j=g.style;j.left=c?"auto":b+"px";j.right=c?b+"px":"auto";j.top=d+"px";j.visibility=l?"hidden":"visible";if(f&&e){j.width=f+"px";j.height=e+"px"}else{o(k,b,d,c,g.offsetWidth,g.offsetHeight);l=l?"":a}}}i.tg=function(a){a=a||window.event;var b,d=a.target||a.srcElement;a.cancelBubble=true;if(k!=null)p(d);else{b=document.createElement(Array.every||window.createPopup?"iframe":"div");b.frameBorder="0";k=b.id="gbs";b.src="javascript:''";d.parentNode.appendChild(b);h(document,"click",i.close);p(d);i.alld&&i.alld(function(){var c=document.getElementById("gbli");if(c){var f=c.parentNode;q(f,c);var e=c.prevSibling;f.removeChild(c);i.removeExtraDelimiters(f,e);b.style.height=f.offsetHeight+"px"}})}};function r(a){var b,d=document.defaultView;if(d&&d.getComputedStyle){if(a=d.getComputedStyle(a,""))b=a.direction}else b=a.currentStyle?a.currentStyle.direction:a.style.direction;return b=="rtl"}function p(a){var b=0;if(a.className!="gb3")a=a.parentNode;var d=a.getAttribute("aria-owns")||"gbi",c=a.offsetWidth,f=a.offsetTop>20?46:24,e=false;do b+=a.offsetLeft||0;while(a=a.offsetParent);a=(document.documentElement.clientWidth||document.body.clientWidth)-b-c;c=r(document.body);if(d=="gbi"){var g=document.getElementById("gbi");q(g,document.getElementById("gbli")||g.firstChild);if(c){b=a;e=true}}else if(!c){b=a;e=true}l!=d&&i.close();o(d,b,f,e)}i.close=function(){l&&o(l,0,0)};function s(a,b,d){if(!m){m="gb2";if(i.alld){var c=i.findClassName(a);if(c)m=c}}a.insertBefore(b,d).className=m}function q(a,b){for(var d,c=window.navExtra;c&&(d=c.pop());)s(a,d,b)}i.addLink=function(a,b,d){if((b=document.getElementById(b))&&a){a.className="gb4";var c=document.createElement("span");c.appendChild(a);c.appendChild(document.createTextNode(" | "));c.id=d;b.appendChild(c)}}})();if(!window.google)window.google={};if(!window.google.movies)window.google.movies={};window.google.movies.registerFixdir=function(){var c="[\u0000- !-@[-{-\u00bf\u00d7\u00f7\u02b9-\u02ff\u2000-\u2bff]",g=new RegExp("^"+c+"([0-9]"+c+"$|[A-Za-z\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02b8\u0300-\u0590\u0800-\u1fff\u2c00-\ufb1c\ufdfe-\ufe6f\ufefd-\uffff])"),h=new RegExp("^"+c+"$");function e(d,a){if(!a)a=d&&d.target?d.target:window.event.srcElement;a.dir=g.test(a.value)?"ltr":(h.test(a.value)?"":"rtl")} var i=[document.getElementsByName("q")[0],document.getElementById("mtq")];for(var f=0,b;b=i[f];f++)if(b){b.onkeyup=e;e(null,b)}}; Movie Showtimes - Google Search.fl:link{}a:link,.w,a.w:link,.w a:link{color:#00c}a:visited{color:#551a8b}a:active{color:red}.t a:link,.t a:active,.t a:visited,.t{color:#000}.left{width:12em}.box{background:#fff}.nopadding{padding:0}.k{background:#36c}.z{display:none}.x{width:3em}.y{width:23em}.b{color:#00c;font-size:12pt;font-weight:bold}.i,.i:link{color:#a90a08}.n a{color:#000;font-size:10pt}.n .b a{color:#00c}.n .i{font-size:10pt;font-weight:bold}.h{cursor:pointer}body{background:#fff;font:82% Arial,Helvetica,sans-serif;margin:3px 0 0;padding:0}table{border-collapse:collapse;border-spacing:0}img{border:0}td,th{vertical-align:top}h1,h2{font-size:100%;margin:0}a{color:#00c}/ CSS for page */#title_bar{background:#f0f7f9;border-top:1px solid #6b90da;padding-bottom:4px;padding-left:8px;padding-top:4px}#google_bar{margin:3px 10px}#search_form{margin:3px 10px}#left_nav{border-right:1px solid #c9d7f1;margin-top:11px;position:absolute;left:9px;width:13.4em}#left_nav .section{margin-bottom:1.2em}.hidden{visibility:hidden}#results{height:auto !important;height:350px;margin-left:15em;min-height:350px;min-width:800px;width:expression(document.body.clientWidth<1000?"800px":"99.9%")}.name{font-size:124%;margin:0}.times{clear:both;margin:0}.address{margin:0}#movie_results{overflow:auto}.movie_results{margin-top:11px}.movie{clear:both;margin-bottom:40px}.movie .header{padding-left:8px}.movie .img{border:1px solid #ccc;float:left;margin-bottom:10px}.movie .desc{margin-bottom:15px;max-width:42em}.movie h2{font-size:124%;margin-bottom:2px}.movie .info{margin-bottom:10px}.movie .syn{margin-bottom:10px}.movie .section_title{background:#f0f7f9;clear:both;font-size:108%;margin-bottom:11px;margin-top:11px;padding-bottom:4px;padding-left:8px;padding-top:5px}.movie .showtimes{margin-bottom:8px;padding-left:8px}.movie .show_left{width:49%}.movie .show_right{width:49%}.movie .theater{padding-bottom:15px}.theater{clear:both;padding-bottom:1px}.theater_after_icon{padding-left:25px}.theater .show_left{width:49%}.theater .show_right{width:49%}.theater h2{font-size:124%;margin-bottom:2px}.theater .icon{float:left;height:3em;margin-right:5px}.theater .closure{font-size:100%}.theater .info{font-size:100%;padding-bottom:5px;padding-top:5px}.theater .movie{margin-bottom:8px;margin-right:8px;max-width:42em}.theater .movie .desc{margin-bottom:5px;margin-left:0}.theater .movie .info{margin-top:0}.theater .showtimes{margin-bottom:40px;margin-top:8px}#theater_map{right:0;left:0;position:relative;top:0}#theater_static_map{border:1px solid #c9d7f1;margin:10px}.map_marker .name{margin-top:10px}.photo{border:1px solid #ccc;margin-bottom:20px;margin-left:8px}.show_left{float:left;margin:0;width:49.999%}.show_right{float:right;margin:0;width:50%}.show_more{clear:both;font-size:124%;margin:0}.show_more a{color:#77c}.reviews{margin-bottom:8px;padding-left:8px}.review{margin-bottom:5px}.review .publisher{color:green}.review .date{color:#6f6f6f}.trailer{margin-bottom:8px;padding-left:8px}.clear{clear:both}.iconA{background:url(http://maps.gstatic.com/mapfiles/red_icons_A_J.png) repeat 0 0}.iconB{background:url(http://maps.gstatic.com/mapfiles/red_icons_A_J.png) repeat 0 -38px}.iconC{background:url(http://maps.gstatic.com/mapfiles/red_icons_A_J.png) repeat 0 -76px}.iconD{background:url(http://maps.gstatic.com/mapfiles/red_icons_A_J.png) repeat 0 -114px}.iconE{background:url(http://maps.gstatic.com/mapfiles/red_icons_A_J.png) repeat 0 -152px}.iconF{background:url(http://maps.gstatic.com/mapfiles/red_icons_A_J.png) repeat 0 -190px}.iconG{background:url(http://maps.gstatic.com/mapfiles/red_icons_A_J.png) repeat 0 -228px}.iconH{background:url(http://maps.gstatic.com/mapfiles/red_icons_A_J.png) repeat 0 -266px}.iconI{background:url(http://maps.gstatic.com/mapfiles/red_icons_A_J.png) repeat 0 -304px}.iconJ{background:url(http://maps.gstatic.com/mapfiles/red_icons_A_J.png) repeat 0 -342px}.iconK{background:url(http://maps.gstatic.com/mapfiles/red_icons_K_Z.png) repeat 0 0}.iconL{background:url(http://maps.gstatic.com/mapfiles/red_icons_K_Z.png) repeat 0 -38px}.iconM{background:url(http://maps.gstatic.com/mapfiles/red_icons_K_Z.png) repeat 0 -76px}.iconN{background:url(http://maps.gstatic.com/mapfiles/red_icons_K_Z.png) repeat 0 -114px}.iconO{background:url(http://maps.gstatic.com/mapfiles/red_icons_K_Z.png) repeat 0 -152px}.iconP{background:url(http://maps.gstatic.com/mapfiles/red_icons_K_Z.png) repeat 0 -190px}.iconQ{background:url(http://maps.gstatic.com/mapfiles/red_icons_K_Z.png) repeat 0 -228px}.iconR{background:url(http://maps.gstatic.com/mapfiles/red_icons_K_Z.png) repeat 0 -266px}.iconS{background:url(http://maps.gstatic.com/mapfiles/red_icons_K_Z.png) repeat 0 -304px}.iconT{background:url(http://maps.gstatic.com/mapfiles/red_icons_K_Z.png) repeat 0 -342px}.iconU{background:url(http://maps.gstatic.com/mapfiles/red_icons_K_Z.png) repeat 0 -380px}.iconV{background:url(http://maps.gstatic.com/mapfiles/red_icons_K_Z.png) repeat 0 -418px}.iconW{background:url(http://maps.gstatic.com/mapfiles/red_icons_K_Z.png) repeat 0 -456px}.iconX{background:url(http://maps.gstatic.com/mapfiles/red_icons_K_Z.png) repeat 0 -494px}.iconY{background:url(http://maps.gstatic.com/mapfiles/red_icons_K_Z.png) repeat 0 -532px}.iconZ{background:url(http://maps.gstatic.com/mapfiles/red_icons_K_Z.png) repeat 0 -570px}#gbar,#guser{font-size:13px;padding-top:1px !important}#gbar{float:left;height:22px}#guser{padding-bottom:7px !important;text-align:right}.gbh,.gbd{border-top:1px solid #c9d7f1;font-size:1px}.gbh{height:0;position:absolute;top:24px;width:100%}#gbs,.gbm{background:#fff;left:0;position:absolute;text-align:left;visibility:hidden;z-index:1000}.gbm{border:1px solid;border-color:#c9d7f1 #36c #36c #a2bae7;z-index:1001}.gb1{margin-right:.5em}.gb1,.gb3{zoom:1}.gb2{display:block;padding:.2em .5em;}.gb2,.gb3{text-decoration:none;border-bottom:none}a.gb1,a.gb2,a.gb3,a.gb4{color:#00c !important}.gbi .gb3,.gbi .gb2,.gbi .gb4{color:#dd8e27 !important}.gbf .gb3,.gbf .gb2,.gbf .gb4{color:#900 !important}a.gb2:hover{background:#36c;color:#fff !important}Web Images Videos Maps News Shopping Gmail more ▼Books Finance Translate Scholar Blogs YouTube Calendar Photos Documents Reader Sites Groups even more » [email protected] | Google Account settings | Sign out     Advanced Search  PreferencesShowtimes for Murfreesboro, TN 37130Change Location› Today › Tomorrow › Monday › Tuesday› Theaters › Movies› Show list view › Show map viewPremiere 6 Theater810 Northwest Broad Street, Murfreesboro, TN - (615) 896-4100Clash of the Titans? - 1hr 50min?? - Rated PG-13?? - Action/Adventure? - Trailer - IMDb2:10  4:15  6:15  8:20  10:25pmDiary of a Wimpy Kid? - 1hr 33min?? - Rated PG?? - Comedy/Drama? - Trailer - IMDb2:00  3:50  6:00  7:50  9:40pmHow to Train Your Dragon?1hr 38min?? - Rated PG?? - Family/Animation? - IMDb2:00  3:55  6:00  7:55  9:50pmThe Bounty Hunter? - 1hr 46min?? - Rated PG-13?? - Action/Adventure/Comedy/Romance? - Trailer - IMDb2:15  4:15  6:25  8:25  10:30pmThe Last Song? - 1hr 47min?? - Rated PG?? - Drama? - Trailer - IMDb2:20  4:15  6:30  8:35  10:35pmTyler Perry's Why Did I Get Married Too?2hr 1min?? - Rated PG-13?? - Comedy?2:20  4:35  7:30  9:45pmContinental Cinema 5450 US Highway 231 N, Troy, AL - (334) 808-4225Clash of the Titans 3D? - 1hr 50min?? - Rated PG-13?? - Action/Adventure? - IMDb1:00  4:00  7:00  9:30pmHow to Train Your Dragon 3D? - 1hr 38min?? - Rated PG?? - Family/Animation? - IMDb1:05  4:05  7:05  9:25pmThe Bounty Hunter? - 1hr 46min?? - Rated PG-13?? - Action/Adventure/Comedy/Romance? - Trailer - IMDb1:00  4:00  7:00  9:30pmThe Last Song? - 1hr 47min?? - Rated PG?? - Drama? - Trailer - IMDb1:05  4:05  7:05  9:25pmTyler Perry's Why Did I Get Married Too?2hr 1min?? - Rated PG-13?? - Comedy?12:55  3:55  6:55  9:35pmMall Cinema - Hartford KYUS Hwy 231 South 62 East, Hartford, KY - (270) 298-3315Clash of the Titans? - 1hr 50min?? - Rated PG-13?? - Action/Adventure? - Trailer - IMDb5:00  7:00  9:00pmHow to Train Your Dragon?1hr 38min?? - Rated PG?? - Family/Animation? - IMDb5:00  7:00  9:00pmCarmike Wynnsong 16 - Murfreesboro2626 Cason Square Boulevard, Murfreesboro, TN - (615) 893-2253The Last Song? - 1hr 47min?? - Rated PG?? - Drama? - Trailer - IMDb12:15  1:00  2:45  4:00  5:15  7:00  7:45 

    Read the article

  • Rails: AJAX Controller JS not firing...

    - by neezer
    I'm having an issue with one of my controller's AJAX functionality. Here's what I have: class PhotosController < ApplicationController # ... def create @photo = Photo.new(params[:photo]) @photo.image_content_type = MIME::Types.type_for(@photo.image_file_name).to_s @photo.image_width = Paperclip::Geometry.from_file(params[:photo][:image]).width.to_i @photo.image_height = Paperclip::Geometry.from_file(params[:photo][:image]).height.to_i @photo.save! respond_to do |format| format.js end end # ... end This is called through a POST request sent by this code: $(function() { // add photos link $('a.add-photos-link').colorbox({ overlayClose: false, onComplete: function() { wire_add_photo_modal(); } }); function wire_add_photo_modal() { <% session_key = ActionController::Base.session_options[:key] %> $('#upload_photo').uploadify({ uploader: '/swf/uploadify.swf', script: '/photos', cancelImg: '/images/buttons/cancel.png', buttonText: 'Upload Photo(s)', auto: true, queueID: 'queue', fileDataName: 'photo[image]', scriptData: { '<%= session_key %>': '<%= u cookies[session_key] %>', commit: 'Adding Photo', controller: 'photos', action: 'create', '_method': 'post', 'photo[gallery_id]': $('#gallery_id').val(), 'photo[user_id]': $('#user_id').val(), authenticity_token: encodeURIComponent('<%= u form_authenticity_token if protect_against_forgery? %>') }, multi: true }); } }); Finally, I have my response code in app/views/photos/create.js.erb: alert('photo added!'); My log file shows that the request was successful (the photo was successfully uploaded), and it even says that it rendered the create action, yet I never get the alert. My browser shows NO javascript errors. Here's the log AFTER a request from the above POST request is submitted: Processing PhotosController#create (for 127.0.0.1 at 2010-03-16 14:35:33) [POST] Parameters: {"Filename"=>"tumblr_kx74k06IuI1qzt6cxo1_400.jpg", "photo"=>{"user_id"=>"1", "image"=>#<File:/tmp/RackMultipart20100316-54303-7r2npu-0>}, "commit"=>"Adding Photo", "_edited_session"=>"edited", "folder"=>"/kakagiloon/", "authenticity_token"=>"edited", "action"=>"create", "_method"=>"post", "Upload"=>"Submit Query", "controller"=>"photos"} [paperclip] Saving attachments. [paperclip] saving /public/images/assets/kakagiloon/thumbnail/tumblr_kx74k06IuI1qzt6cxo1_400.jpg [paperclip] saving /public/images/assets/kakagiloon/profile/tumblr_kx74k06IuI1qzt6cxo1_400.jpg [paperclip] saving /public/images/assets/kakagiloon/original/tumblr_kx74k06IuI1qzt6cxo1_400.jpg Rendering photos/create Completed in 248ms (View: 1, DB: 6) | 200 OK [http://edited.local/photos] NOTE: I edited out all the SQL statements and I put "edited" in place of sensitive info. What gives? Why aren't I getting my alert();? Please let me know if you need anymore info to help me solve this issue! Thanks.

    Read the article

  • displaying the values in textbox based on AJAX fetched entries

    - by Anurag
    hello, I've a table in which addition rows can be generatred as per the user need by clicking a javascript function. Each row has a drop down list, and based on the values of this an AJAX script fetchs some values which has to be displayed in corresponding textfields of the same row.. here is the code for HTML.. <td><div align="center"> <label> <select name="gcno1" id="gcno1" onchange="fetch_gc(this)"> <option value="0">NIL</option> <option value="2">1</option> <?php while($row=mysql_fetch_array($result)) { ?> <option value="<?php echo $row[0]; ?>"><?php echo $row[0]; ?></option> <?php }?> </select> </label> </div></td> <td><div align="center"><input name="date1" id="date1" type="text" size="10" /> </div></td> and here is the AJAX which I'm writing... xmlhttp = new XMLHttpRequest(); var value=encodeURIComponent(document.getElementById('gcno1').value); var parameters="param1="+value; xmlhttp.open("POST", 'fetch_gc.php', true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send(parameters); xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState == 4 && xmlhttp.status == 200) { var detail=xmlhttp.responseText.split('+'); alert(detail[0]); document.getElementsByName('date1').value=String(detail[0]); alert("life " + document.getElementById('gcno1').value); } } The alert inside the AJAX shows the correct response text, detail[0] but is unable to put the value in corresponding textbox i.e. with name 'gcno1'...... Please help me with this problem...

    Read the article

  • Rails 3: How do I call a javascript function from a js.erb file

    - by user321775
    Now that I've upgraded to Rails 3, I'm trying to figure out the proper way to separate and reuse pieces of javascript. Here's the scenario I'm dealing with: I have a page with two areas: one with elements that should be draggable, the other with droppables. When the page loads I use jQuery to setup the draggables and droppables. Currently I have the script in the head portion of application.html.erb, which I'm sure is not the right solution but at least works. When I press a button on the page, an ajax call is made to my controller that replaces the draggables with a new set of elements that should also be draggable. I have a js.erb file that renders a partial in the correct location. After rendering I need to make the new elements draggable, so I'd like to reuse the code that currently lives in application.html.erb, but I haven't found the right way to do it. I can only make the new elements draggable by pasting the code directly into my js.erb file (yuck). What I'd like to have: - a javascript file that contains the functions prepdraggables() and prepdroppables() - a way to call either function from application.html.erb or from a js.erb file I've tried using :content_for to store and reuse the code, but can't seem to get it working correctly. What I currently have in the head section of application.html.erb <% content_for :drag_drop_prep do %> <script type="text/javascript" charset="utf-8"> $(document).ready(function () { // declare all DOM elements with class draggable to be draggable $( ".draggable" ).draggable( { revert : 'invalid' }); // declare all DOM elements with class legal to be droppable $(".legal").droppable({ hoverClass : 'legal_hover', drop : function(event, ui) { var c = new Object(); c['die'] = ui.draggable.attr("id"); c['cell'] = $(this).attr("id"); c['authenticity_token'] = encodeURIComponent(window._token); $.ajax({ type: "POST", url: "/placeDie", data: c, timeout: 5000 }); }}); }); </script> <% end %> undo.js.erb $("#board").html("<%= escape_javascript(render :partial => 'shared/board', :locals => { :playable => true, :restartable => !session[:challenge]}) %>") // This is where I want to prepare draggables. <%= javascript_include_tag "customdragdrop.js" %> // assuming this file had the draggables code from above in a prepdraggables() function prepdraggables();

    Read the article

  • Jetty servlet respons to Ajax always empty

    - by chris
    Hi I try to run a java server on Jetty which should respond to an ajax call. Unfortunately the response seems to be empty when I call it with ajax. When I call http://localhost:8081/?id=something I get an answer. The Java Server: public class Answer extends AbstractHandler { public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String id = request.getParameter("id"); response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.setContentLength(19+id.length()); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().write("<message>"+id+"</message>"); //response.setContentType("text/html;charset=utf-8"); response.flushBuffer(); baseRequest.setHandled(true); } public static void main(String[] args) throws Exception { Server server = new Server(8081); server.setHandler(new Answer()); server.start(); server.join(); } } The js and html: <html> <head> <script> var req; function validate() { var idField = document.getElementById("userid"); var url = "validate?id=" + encodeURIComponent(idField.value); if (typeof XMLHttpRequest != "undefined") { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); } req.open("GET", "http://localhost:8081?id=fd", true); req.onreadystatechange = callback; req.send(null); } function callback() { if (req.readyState == 4) { if (req.status == 200) { var message = req.responseXML.getElementsByTagName("message")[0]; document.getElementById("userid").innerHTML = "message.childNodes[0].nodeValue"; } } } </script> </head> <body onload="validate('foobar')"> <div id="userid">hannak</div> </body> </html> I'm actually don't know what I'm doing wrong here. Maybe someone has a good idea. greetings chris

    Read the article

  • Lift session valid ajax callback from a static javascript

    - by ChrisJamesC
    I am currently implementing a graph visualisation tool using lift on the server side and d3 ( a javascript visualisation framework) for all the visualisation. The problem I have is that in the script I want to get session dependent data from the server. So basically, my objective is to write lift-valid ajax callbacks in a static js script. Here is what I tried so far: What I have tried so far If you feel that the best solution is one that I already tried feel free to post a detailed answer telling me how to use it exactly and how it completely solves my problem. REST interface Usually what one would do to get data from a javascript function in lift is to create a REST interface. However this interface will not be linked to any session. This is the solution I got from my previous question: Get json data in d3 from lift snippet Give function as argument of script Another solution would be to give the ajaxcallback as an argument of the main script called to generate my graph. However I expect to have a lot of callbacks and I don't want to have to mess with the arguments of my script. Write the ajax callback in another script using lift and call it from the main script This solution, which is similar to a hidden text input is probably the more likely to work. However it is not elegant and it would mean that I would have to load a lot of scripts on load, which is not really conveniant. Write the whole script in lift and then serve it to the client This solution can be elegant, however my script is very long and I would really prefer that it remainss static. What I want On client side While reviewing the source code of my webpage I found that the callback for an ajaxSelect is: <select onchange="liftAjax.lift_ajaxHandler('F966066257023LYKF4=' + encodeURIComponent(this.value), null, null, null)" name="F96606625703QXTSWU" id="node_delete" class="input"> Moreover, there is a variable containing the state of the page in the end of the webpage: var lift_page = "F96606625700QRXLDO"; So, I am wondering if it is possible to simulate that my ajaxcall is valid using this liftAjax.lift_ajaxHandler function. However I don't know the exact synthax to use. On server side Since I "forged" a request on client side, I would now like to get the request on client side and to dispatch it to the correct function. This is where the LiftRules.dispatch object seems the best solution: when it is called, all the session management has been made (the request is authentified and linked to a session), however I don't know how to write the correct piece of code in the append function. Remark In lift all names of variables are changed to a random string in order to increase the security, I would like to have the same behavior in my application even if that will probably mean that I will have to "give" the javascript these values. However an array of 15 string values is still a better tradeoff than 15 functions as argument of a javascript function.

    Read the article

  • fieldWithErrors not wrapping every error field

    - by Teef L
    Notice the following result when I submit blank :title and :description fields The validations are in the controller: class Question < ActiveRecord::Base validates_presence_of :title validates_presence_of :description And, the form is generated with those names: -form_for(@question) do |f| = f.error_messages = f.label :title = f.text_field :title, :size => 50, :onchange => remote_function(:url => {:action => :display_tag_suggestions}, :with => 'Form.Element.serialize(this)') #suggestions = f.label :description = f.text_area :description ... But, for some reason, only :title gets wrapped in the error div tags: <form action="/questions" class="new_question" id="new_question" method="post"> <div style="margin:0;padding:0"><input name="authenticity_token" type="hidden" value="6HQaiu1D0gBQcKw2pLeZP6Jvn0FSClPD5Sk9HwegzPg=" /></div> <div class="errorExplanation" id="errorExplanation"> <h2>2 errors prohibited this question from being saved</h2> <p>There were problems with the following fields:</p> <ul> <li>Title can't be blank</li> <li>Description can't be blank</li> </ul> </div> <label for="question_title">Title</label> <div class="fieldWithErrors"><input id="question_title" name="question[title]" onchange="new Ajax.Request('/questions/display_tag_suggestions', {asynchronous:true, evalScripts:true, parameters:Form.Element.serialize(this) + '&amp;authenticity_token=' + encodeURIComponent('6HQaiu1D0gBQcKw2pLeZP6Jvn0FSClPD5Sk9HwegzPg=')})" size="50" type="text" value="" /></div> <label for="question_description">Description</label> <textarea cols="40" id="question_description" name="question[description]" rows="20"></textarea> ... I don't think that behavior is expected. The problem most people have is that it's wrapping things with divs, which won't display properly. My problem is that fields aren't being wrapped with divs to begin with! I haven't made any (conscious) changes to how errors are handled, so I'm not sure why it's not working properly.

    Read the article

  • Pass data to another page

    - by user2331416
    I am trying to pass some data from one page to another page by using jquery but it dose not working, below is the code which I want to click the text in source page and the destination page will hide the current text. Source page: <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript"> $(function () { $("a.pass").bind("click", function () { var url = "Destination.html?name=" + encodeURIComponent($("a.pass").text()); window.location.href = url; }); }); </script> </head> <body> <a class="pass">a</a><br /> <a class="pass">b</a><br /> <a class="pass">c</a><br /> <a class="pass">d</a> </body> </html> Destination page: <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript"> var queryString = new Array(); $(function () { if (queryString.length == 0) { if (window.location.search.split('?').length > 1) { var params = window.location.search.split('?')[1].split('&'); for (var i = 0; i < params.length; i++) { var key = params[i].split('=')[0]; var value = decodeURIComponent(params[i].split('=')[1]); queryString[key] = value; } } } if (queryString["name"] != null) { var data = queryString["name"] $("p.+'data'").hide(); } }); </script> </head> <body> <p class="a">a</p> <p class="b">b</p> <p class="c">c</p> <p class="d">d</p> </body> </html> Please Help.

    Read the article

  • how to use 3D map Actionscript class in mxml file for display map.

    - by nemade-vipin
    hello friends, I have created the application in which I have to use 3D map Action Script class in mxml file to display a map in form. that is in tab navigator last tab. My ActionScript 3D map class is(FlyingDirections):- package src.SBTSCoreObject { import src.SBTSCoreObject.JSONDecoder; import com.google.maps.InfoWindowOptions; import com.google.maps.LatLng; import com.google.maps.LatLngBounds; import com.google.maps.Map3D; import com.google.maps.MapEvent; import com.google.maps.MapOptions; import com.google.maps.MapType; import com.google.maps.MapUtil; import com.google.maps.View; import com.google.maps.controls.NavigationControl; import com.google.maps.geom.Attitude; import com.google.maps.interfaces.IPolyline; import com.google.maps.overlays.Marker; import com.google.maps.overlays.MarkerOptions; import com.google.maps.services.Directions; import com.google.maps.services.DirectionsEvent; import com.google.maps.services.Route; import flash.display.Bitmap; import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.display.Loader; import flash.display.LoaderInfo; import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.MouseEvent; import flash.events.TimerEvent; import flash.filters.DropShadowFilter; import flash.geom.Point; import flash.net.URLLoader; import flash.net.URLRequest; import flash.net.navigateToURL; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat; import flash.utils.Timer; import flash.utils.getTimer; public class FlyingDirections extends Map3D { /** * Panoramio home page. */ private static const PANORAMIO_HOME:String = "http://www.panoramio.com/"; /** * The icon for the car. */ [Embed("assets/car-icon-24px.png")] private static const Car:Class; /** * The Panoramio icon. */ [Embed("assets/iw_panoramio.png")] private static const PanoramioIcon:Class; /** * We animate a zoom in to the start the route before the car starts * to move. This constant sets the time in seconds over which this * zoom occurs. */ private static const LEAD_IN_DURATION:Number = 3; /** * Duration of the trip in seconds. */ private static const TRIP_DURATION:Number = 40; /** * Constants that define the geometry of the Panoramio image markers. */ private static const BORDER_T:Number = 3; private static const BORDER_L:Number = 10; private static const BORDER_R:Number = 10; private static const BORDER_B:Number = 3; private static const GAP_T:Number = 2; private static const GAP_B:Number = 1; private static const IMAGE_SCALE:Number = 1; /** * Trajectory that the camera follows over time. Each element is an object * containing properties used to generate parameter values for flyTo(..). * fraction = 0 corresponds to the start of the trip; fraction = 1 * correspondsto the end of the trip. */ private var FLY_TRAJECTORY:Array = [ { fraction: 0, zoom: 6, attitude: new Attitude(0, 0, 0) }, { fraction: 0.2, zoom: 8.5, attitude: new Attitude(30, 30, 0) }, { fraction: 0.5, zoom: 9, attitude: new Attitude(30, 40, 0) }, { fraction: 1, zoom: 8, attitude: new Attitude(50, 50, 0) }, { fraction: 1.1, zoom: 8, attitude: new Attitude(130, 50, 0) }, { fraction: 1.2, zoom: 8, attitude: new Attitude(220, 50, 0) }, ]; /** * Number of panaramio photos for which we load data. We&apos;ll select a * subset of these approximately evenly spaced along the route. */ private static const NUM_GEOTAGGED_PHOTOS:int = 50; /** * Number of panaramio photos that we actually show. */ private static const NUM_SHOWN_PHOTOS:int = 7; /** * Scaling between real trip time and animation time. */ private static const SCALE_TIME:Number = 0.001; /** * getTimer() value at the instant that we start the trip. If this is 0 then * we have not yet started the car moving. */ private var startTimer:int = 0; /** * The current route. */ private var route:Route; /** * The polyline for the route. */ private var polyline:IPolyline; /** * The car marker. */ private var marker:Marker; /** * The cumulative duration in seconds over each step in the route. * cumulativeStepDuration[0] is 0; cumulativeStepDuration[1] adds the * duration of step 0; cumulativeStepDuration[2] adds the duration * of step 1; etc. */ private var cumulativeStepDuration:/*Number*/Array = []; /** * The cumulative distance in metres over each vertex in the route polyline. * cumulativeVertexDistance[0] is 0; cumulativeVertexDistance[1] adds the * distance to vertex 1; cumulativeVertexDistance[2] adds the distance to * vertex 2; etc. */ private var cumulativeVertexDistance:Array; /** * Array of photos loaded from Panoramio. This array has the same format as * the &apos;photos&apos; property within the JSON returned by the Panoramio API * (see http://www.panoramio.com/api/), with additional properties added to * individual photo elements to hold the loader structures that fetch * the actual images. */ private var photos:Array = []; /** * Array of polyline vertices, where each element is in world coordinates. * Several computations can be faster if we can use world coordinates * instead of LatLng coordinates. */ private var worldPoly:/*Point*/Array; /** * Whether the start button has been pressed. */ private var startButtonPressed:Boolean = false; /** * Saved event from onDirectionsSuccess call. */ private var directionsSuccessEvent:DirectionsEvent = null; /** * Start button. */ private var startButton:Sprite; /** * Alpha value used for the Panoramio image markers. */ private var markerAlpha:Number = 0; /** * Index of the current driving direction step. Used to update the * info window content each time we progress to a new step. */ private var currentStepIndex:int = -1; /** * The fly directions map constructor. * * @constructor */ public function FlyingDirections() { key="ABQIAAAA7QUChpcnvnmXxsjC7s1fCxQGj0PqsCtxKvarsoS-iqLdqZSKfxTd7Xf-2rEc_PC9o8IsJde80Wnj4g"; super(); addEventListener(MapEvent.MAP_PREINITIALIZE, onMapPreinitialize); addEventListener(MapEvent.MAP_READY, onMapReady); } /** * Handles map preintialize. Initializes the map center and zoom level. * * @param event The map event. */ private function onMapPreinitialize(event:MapEvent):void { setInitOptions(new MapOptions({ center: new LatLng(-26.1, 135.1), zoom: 4, viewMode: View.VIEWMODE_PERSPECTIVE, mapType:MapType.PHYSICAL_MAP_TYPE })); } /** * Handles map ready and looks up directions. * * @param event The map event. */ private function onMapReady(event:MapEvent):void { enableScrollWheelZoom(); enableContinuousZoom(); addControl(new NavigationControl()); // The driving animation will be updated on every frame. addEventListener(Event.ENTER_FRAME, enterFrame); addStartButton(); // We start the directions loading now, so that we&apos;re ready to go when // the user hits the start button. var directions:Directions = new Directions(); directions.addEventListener( DirectionsEvent.DIRECTIONS_SUCCESS, onDirectionsSuccess); directions.addEventListener( DirectionsEvent.DIRECTIONS_FAILURE, onDirectionsFailure); directions.load("48 Pirrama Rd, Pyrmont, NSW to Byron Bay, NSW"); } /** * Adds a big blue start button. */ private function addStartButton():void { startButton = new Sprite(); startButton.buttonMode = true; startButton.addEventListener(MouseEvent.CLICK, onStartClick); startButton.graphics.beginFill(0x1871ce); startButton.graphics.drawRoundRect(0, 0, 150, 100, 10, 10); startButton.graphics.endFill(); var startField:TextField = new TextField(); startField.autoSize = TextFieldAutoSize.LEFT; startField.defaultTextFormat = new TextFormat("_sans", 20, 0xffffff, true); startField.text = "Start!"; startButton.addChild(startField); startField.x = 0.5 * (startButton.width - startField.width); startField.y = 0.5 * (startButton.height - startField.height); startButton.filters = [ new DropShadowFilter() ]; var container:DisplayObjectContainer = getDisplayObject() as DisplayObjectContainer; container.addChild(startButton); startButton.x = 0.5 * (container.width - startButton.width); startButton.y = 0.5 * (container.height - startButton.height); var panoField:TextField = new TextField(); panoField.autoSize = TextFieldAutoSize.LEFT; panoField.defaultTextFormat = new TextFormat("_sans", 11, 0x000000, true); panoField.text = "Photos provided by Panoramio are under the copyright of their owners."; container.addChild(panoField); panoField.x = container.width - panoField.width - 5; panoField.y = 5; } /** * Handles directions success. Starts flying the route if everything * is ready. * * @param event The directions event. */ private function onDirectionsSuccess(event:DirectionsEvent):void { directionsSuccessEvent = event; flyRouteIfReady(); } /** * Handles click on the start button. Starts flying the route if everything * is ready. */ private function onStartClick(event:MouseEvent):void { startButton.removeEventListener(MouseEvent.CLICK, onStartClick); var container:DisplayObjectContainer = getDisplayObject() as DisplayObjectContainer; container.removeChild(startButton); startButtonPressed = true; flyRouteIfReady(); } /** * If we have loaded the directions and the start button has been pressed * start flying the directions route. */ private function flyRouteIfReady():void { if (!directionsSuccessEvent || !startButtonPressed) { return; } var directions:Directions = directionsSuccessEvent.directions; // Extract the route. route = directions.getRoute(0); // Draws the polyline showing the route. polyline = directions.createPolyline(); addOverlay(directions.createPolyline()); // Creates a car marker that is moved along the route. var car:DisplayObject = new Car(); marker = new Marker(route.startGeocode.point, new MarkerOptions({ icon: car, iconOffset: new Point(-car.width / 2, -car.height) })); addOverlay(marker); transformPolyToWorld(); createCumulativeArrays(); // Load Panoramio data for the region covered by the route. loadPanoramioData(directions.bounds); var duration:Number = route.duration; // Start a timer that will trigger the car moving after the lead in time. var leadInTimer:Timer = new Timer(LEAD_IN_DURATION * 1000, 1); leadInTimer.addEventListener(TimerEvent.TIMER, onLeadInDone); leadInTimer.start(); var flyTime:Number = -LEAD_IN_DURATION; // Set up the camera flight trajectory. for each (var flyStep:Object in FLY_TRAJECTORY) { var time:Number = flyStep.fraction * duration; var center:LatLng = latLngAt(time); var scaledTime:Number = time * SCALE_TIME; var zoom:Number = flyStep.zoom; var attitude:Attitude = flyStep.attitude; var elapsed:Number = scaledTime - flyTime; flyTime = scaledTime; flyTo(center, zoom, attitude, elapsed); } } /** * Loads Panoramio data for the route bounds. We load data about more photos * than we need, then select a subset lying along the route. * @param bounds Bounds within which to fetch images. */ private function loadPanoramioData(bounds:LatLngBounds):void { var params:Object = { order: "popularity", set: "full", from: "0", to: NUM_GEOTAGGED_PHOTOS.toString(10), size: "small", minx: bounds.getWest(), miny: bounds.getSouth(), maxx: bounds.getEast(), maxy: bounds.getNorth() }; var loader:URLLoader = new URLLoader(); var request:URLRequest = new URLRequest( "http://www.panoramio.com/map/get_panoramas.php?" + paramsToString(params)); loader.addEventListener(Event.COMPLETE, onPanoramioDataLoaded); loader.addEventListener(IOErrorEvent.IO_ERROR, onPanoramioDataFailed); loader.load(request); } /** * Transforms the route polyline to world coordinates. */ private function transformPolyToWorld():void { var numVertices:int = polyline.getVertexCount(); worldPoly = new Array(numVertices); for (var i:int = 0; i < numVertices; ++i) { var vertex:LatLng = polyline.getVertex(i); worldPoly[i] = fromLatLngToPoint(vertex, 0); } } /** * Returns the time at which the route approaches closest to the * given point. * @param world Point in world coordinates. * @return Route time at which the closest approach occurs. */ private function getTimeOfClosestApproach(world:Point):Number { var minDistSqr:Number = Number.MAX_VALUE; var numVertices:int = worldPoly.length; var x:Number = world.x; var y:Number = world.y; var minVertex:int = 0; for (var i:int = 0; i < numVertices; ++i) { var dx:Number = worldPoly[i].x - x; var dy:Number = worldPoly[i].y - y; var distSqr:Number = dx * dx + dy * dy; if (distSqr < minDistSqr) { minDistSqr = distSqr; minVertex = i; } } return cumulativeVertexDistance[minVertex]; } /** * Returns the array index of the first element that compares greater than * the given value. * @param ordered Ordered array of elements. * @param value Value to use for comparison. * @return Array index of the first element that compares greater than * the given value. */ private function upperBound(ordered:Array, value:Number, first:int=0, last:int=-1):int { if (last < 0) { last = ordered.length; } var count:int = last - first; var index:int; while (count > 0) { var step:int = count >> 1; index = first + step; if (value >= ordered[index]) { first = index + 1; count -= step - 1; } else { count = step; } } return first; } /** * Selects up to a given number of photos approximately evenly spaced along * the route. * @param ordered Array of photos, each of which is an object with * a property &apos;closestTime&apos;. * @param number Number of photos to select. */ private function selectEvenlySpacedPhotos(ordered:Array, number:int):Array { var start:Number = cumulativeVertexDistance[0]; var end:Number = cumulativeVertexDistance[cumulativeVertexDistance.length - 2]; var closestTimes:Array = []; for each (var photo:Object in ordered) { closestTimes.push(photo.closestTime); } var selectedPhotos:Array = []; for (var i:int = 0; i < number; ++i) { var idealTime:Number = start + ((end - start) * (i + 0.5) / number); var index:int = upperBound(closestTimes, idealTime); if (index < 1) { index = 0; } else if (index >= ordered.length) { index = ordered.length - 1; } else { var errorToPrev:Number = Math.abs(idealTime - closestTimes[index - 1]); var errorToNext:Number = Math.abs(idealTime - closestTimes[index]); if (errorToPrev < errorToNext) { --index; } } selectedPhotos.push(ordered[index]); } return selectedPhotos; } /** * Handles completion of loading the Panoramio index data. Selects from the * returned photo indices a subset of those that lie along the route and * initiates load of each of these. * @param event Load completion event. */ private function onPanoramioDataLoaded(event:Event):void { var loader:URLLoader = event.target as URLLoader; var decoder:JSONDecoder = new JSONDecoder(loader.data as String); var allPhotos:Array = decoder.getValue().photos; for each (var photo:Object in allPhotos) { var latLng:LatLng = new LatLng(photo.latitude, photo.longitude); photo.closestTime = getTimeOfClosestApproach(fromLatLngToPoint(latLng, 0)); } allPhotos.sortOn("closestTime", Array.NUMERIC); photos = selectEvenlySpacedPhotos(allPhotos, NUM_SHOWN_PHOTOS); for each (photo in photos) { var photoLoader:Loader = new Loader(); // The images aren&apos;t on panoramio.com: we can&apos;t acquire pixel access // using "new LoaderContext(true)". photoLoader.load( new URLRequest(photo.photo_file_url)); photo.loader = photoLoader; // Save the loader info: we use this to find the original element when // the load completes. photo.loaderInfo = photoLoader.contentLoaderInfo; photoLoader.contentLoaderInfo.addEventListener( Event.COMPLETE, onPhotoLoaded); } } /** * Creates a MouseEvent listener function that will navigate to the given * URL in a new window. * @param url URL to which to navigate. */ private function createOnClickUrlOpener(url:String):Function { return function(event:MouseEvent):void { navigateToURL(new URLRequest(url)); }; } /** * Handles completion of loading an individual Panoramio image. * Adds a custom marker that displays the image. Initially this is made * invisible so that it can be faded in as needed. * @param event Load completion event. */ private function onPhotoLoaded(event:Event):void { var loaderInfo:LoaderInfo = event.target as LoaderInfo; // We need to find which photo element this image corresponds to. for each (var photo:Object in photos) { if (loaderInfo == photo.loaderInfo) { var imageMarker:Sprite = createImageMarker(photo.loader, photo.owner_name, photo.owner_url); var options:MarkerOptions = new MarkerOptions({ icon: imageMarker, hasShadow: true, iconAlignment: MarkerOptions.ALIGN_BOTTOM | MarkerOptions.ALIGN_LEFT }); var latLng:LatLng = new LatLng(photo.latitude, photo.longitude); var marker:Marker = new Marker(latLng, options); photo.marker = marker; addOverlay(marker); // A hack: we add the actual image after the overlay has been added, // which creates the shadow, so that the shadow is valid even if we // don&apos;t have security privileges to generate the shadow from the // image. marker.foreground.visible = false; marker.shadow.alpha = 0; var imageHolder:Sprite = new Sprite(); imageHolder.addChild(photo.loader); imageHolder.buttonMode = true; imageHolder.addEventListener( MouseEvent.CLICK, createOnClickUrlOpener(photo.photo_url)); imageMarker.addChild(imageHolder); return; } } trace("An image was loaded which could not be found in the photo array."); } /** * Creates a custom marker showing an image. */ private function createImageMarker(child:DisplayObject, ownerName:String, ownerUrl:String):Sprite { var content:Sprite = new Sprite(); var panoramioIcon:Bitmap = new PanoramioIcon(); var iconHolder:Sprite = new Sprite(); iconHolder.addChild(panoramioIcon); iconHolder.buttonMode = true; iconHolder.addEventListener(MouseEvent.CLICK, onPanoramioIconClick); panoramioIcon.x = BORDER_L; panoramioIcon.y = BORDER_T; content.addChild(iconHolder); // NOTE: we add the image as a child only after we&apos;ve added the marker // to the map. Currently the API requires this if it&apos;s to generate the // shadow for unprivileged content. // Shrink the image, so that it doesn&apos;t obcure too much screen space. // Ideally, we&apos;d subsample, but we don&apos;t have pixel level access. child.scaleX = IMAGE_SCALE; child.scaleY = IMAGE_SCALE; var imageW:Number = child.width; var imageH:Number = child.height; child.x = BORDER_L + 30; child.y = BORDER_T + iconHolder.height + GAP_T; var authorField:TextField = new TextField(); authorField.autoSize = TextFieldAutoSize.LEFT; authorField.defaultTextFormat = new TextFormat("_sans", 12); authorField.text = "author:"; content.addChild(authorField); authorField.x = BORDER_L; authorField.y = BORDER_T + iconHolder.height + GAP_T + imageH + GAP_B; var ownerField:TextField = new TextField(); ownerField.autoSize = TextFieldAutoSize.LEFT; var textFormat:TextFormat = new TextFormat("_sans", 14, 0x0e5f9a); ownerField.defaultTextFormat = textFormat; ownerField.htmlText = "<a href=\"" + ownerUrl + "\" target=\"_blank\">" + ownerName + "</a>"; content.addChild(ownerField); ownerField.x = BORDER_L + authorField.width; ownerField.y = BORDER_T + iconHolder.height + GAP_T + imageH + GAP_B; var totalW:Number = BORDER_L + Math.max(imageW, ownerField.width + authorField.width) + BORDER_R; var totalH:Number = BORDER_T + iconHolder.height + GAP_T + imageH + GAP_B + ownerField.height + BORDER_B; content.graphics.beginFill(0xffffff); content.graphics.drawRoundRect(0, 0, totalW, totalH, 10, 10); content.graphics.endFill(); var marker:Sprite = new Sprite(); marker.addChild(content); content.x = 30; content.y = 0; marker.graphics.lineStyle(); marker.graphics.beginFill(0xff0000); marker.graphics.drawCircle(0, totalH + 30, 3); marker.graphics.endFill(); marker.graphics.lineStyle(2, 0xffffff); marker.graphics.moveTo(30 + 10, totalH - 10); marker.graphics.lineTo(0, totalH + 30); return marker; } /** * Handles click on the Panoramio icon. */ private function onPanoramioIconClick(event:MouseEvent):void { navigateToURL(new URLRequest(PANORAMIO_HOME)); } /** * Handles failure of a Panoramio image load. */ private function onPanoramioDataFailed(event:IOErrorEvent):void { trace("Load of image failed: " + event); } /** * Returns a string containing cgi query parameters. * @param Associative array mapping query parameter key to value. * @return String containing cgi query parameters. */ private static function paramsToString(params:Object):String { var result:String = ""; var separator:String = ""; for (var key:String in params) { result += separator + encodeURIComponent(key) + "=" + encodeURIComponent(params[key]); separator = "&"; } return result; } /** * Called once the lead-in flight is done. Starts the car driving along * the route and starts a timer to begin fade in of the Panoramio * images in 1.5 seconds. */ private function onLeadInDone(event:Event):void { // Set startTimer non-zero so that the car starts to move. startTimer = getTimer(); // Start a timer that will fade in the Panoramio images. var fadeInTimer:Timer = new Timer(1500, 1); fadeInTimer.addEventListener(TimerEvent.TIMER, onFadeInTimer); fadeInTimer.start(); } /** * Handles the fade in timer&apos;s TIMER event. Sets markerAlpha above zero * which causes the frame enter handler to fade in the markers. */ private function onFadeInTimer(event:Event):void { markerAlpha = 0.01; } /** * The end time of the flight. */ private function get endTime():Number { if (!cumulativeStepDuration || cumulativeStepDuration.length == 0) { return startTimer; } return startTimer + cumulativeStepDuration[cumulativeStepDuration.length - 1]; } /** * Creates the cumulative arrays, cumulativeStepDuration and * cumulativeVertexDistance. */ private function createCumulativeArrays():void { cumulativeStepDuration = new Array(route.numSteps + 1); cumulativeVertexDistance = new Array(polyline.getVertexCount() + 1); var polylineTotal:Number = 0; var total:Number = 0; var numVertices:int = polyline.getVertexCount(); for (var stepIndex:int = 0; stepIndex < route.numSteps; ++stepIndex) { cumulativeStepDuration[stepIndex] = total; total += route.getStep(stepIndex).duration; var startVertex:int = stepIndex >= 0 ? route.getStep(stepIndex).polylineIndex : 0; var endVertex:int = stepIndex < (route.numSteps - 1) ? route.getStep(stepIndex + 1).polylineIndex : numVertices; var duration:Number = route.getStep(stepIndex).duration; var stepVertices:int = endVertex - startVertex; var latLng:LatLng = polyline.getVertex(startVertex); for (var vertex:int = startVertex; vertex < endVertex; ++vertex) { cumulativeVertexDistance[vertex] = polylineTotal; if (vertex < numVertices - 1) { var nextLatLng:LatLng = polyline.getVertex(vertex + 1); polylineTotal += nextLatLng.distanceFrom(latLng); } latLng = nextLatLng; } } cumulativeStepDuration[stepIndex] = total; } /** * Opens the info window above the car icon that details the given * step of the driving directions. * @param stepIndex Index of the current step. */ private function openInfoForStep(stepIndex:int):void { // Sets the content of the info window. var content:String; if (stepIndex >= route.numSteps) { content = "<b>" + route.endGeocode.address + "</b>" + "<br /><br />" + route.summaryHtml; } else { content = "<b>" + stepIndex + ".</b> " + route.getStep(stepIndex).descriptionHtml; } marker.openInfoWindow(new InfoWindowOptions({ contentHTML: content })); } /** * Displays the driving directions step appropriate for the given time. * Opens the info window showing the step instructions each time we * progress to a new step. * @param time Time for which to display the step. */ private function displayStepAt(time:Number):void { var stepIndex:int = upperBound(cumulativeStepDuration, time) - 1; var minStepIndex:int = 0; var maxStepIndex:int = route.numSteps - 1; if (stepIndex >= 0 && stepIndex <= maxStepIndex && currentStepIndex != stepIndex) { openInfoForStep(stepIndex); currentStepIndex = stepIndex; } } /** * Returns the LatLng at which the car should be positioned at the given * time. * @param time Time for which LatLng should be found. * @return LatLng. */ private function latLngAt(time:Number):LatLng { var stepIndex:int = upperBound(cumulativeStepDuration, time) - 1; var minStepIndex:int = 0; var maxStepIndex:int = route.numSteps - 1; if (stepIndex < minStepIndex) { return route.startGeocode.point; } else if (stepIndex > maxStepIndex) { return route.endGeocode.point; } var stepStart:Number = cumulativeStepDuration[stepIndex]; var stepEnd:Number = cumulativeStepDuration[stepIndex + 1]; var stepFraction:Number = (time - stepStart) / (stepEnd - stepStart); var startVertex:int = route.getStep(stepIndex).polylineIndex; var endVertex:int = (stepIndex + 1) < route.numSteps ? route.getStep(stepIndex + 1).polylineIndex : polyline.getVertexCount(); var stepVertices:int = endVertex - startVertex; var stepLeng

    Read the article

  • How to make a jQuery plugin (the right way)?

    - by macek
    I know there are jQuery cookie plugins out there, but I wanted to write one for the sake of better learning the jQuery plugin pattern. I like the separation of "work" in small, manageable functions, but I feel like I'm passing name, value, and options arguments around too much. Is there a way this can be refactored? I'm looking for snippets of code to help illustrate examples provided with in answers. Any help is appreciated. Thanks :) example usage $.cookie('foo', 'bar', {expires:7}); $.cookie('foo'); //=> bar $.cookie('foo', null); $.cookie('foo'); //=> undefined Edit: I did a little bit of work on this. You can view the revision history to see where this has come from. It still feels like more refactoring can be done to optimize the flow a bit. Any ideas? the plugin (function($){ $.cookie = function(name, value, options) { if (typeof value == 'undefined') { return get(name); } else { options = $.extend({}, $.cookie.defaults, options || {}); return (value != null) ? set(name, value, options) : unset(name, options); } }; $.cookie.defaults = { expires: null, path: '/', domain: null, secure: false }; var set = function(name, value, options){ console.log(options); return document.cookie = options_string(name, value, options); }; var get = function(name){ var cookies = {}; $.map(document.cookie.split(';'), function(pair){ var c = $.trim(pair).split('='); cookies[c[0]] = c[1]; }); return decodeURIComponent(cookies[name]); }; var unset = function(name, options){ value = ''; options.expires = -1; set(name, value, options); }; var options_string = function(name, value, options){ var pairs = [param.name(name, value)]; $.each(options, function(k,v){ pairs.push(param[k](v)); }); return $.map(pairs, function(p){ return p === null ? null : p; }).join(';'); }; var param = { name: function(name, value){ return name + "=" + encodeURIComponent(value); }, expires: function(value){ // no expiry if(value === null){ return null; } // number of days else if(typeof value == "number"){ d = new Date(); d.setTime(d.getTime() + (value * 24 * 60 * 60 * 1000)); } // date object else if(typeof value == "object" && value instanceof "Date") { d = value; } return "expires=" + d.toUTCString(); }, path: function(value){ return "path="+value; }, domain: function(value){ return value === null ? null : "domain=" + value; }, secure: function(bool){ return bool ? "secure" : null; } }; })(jQuery);

    Read the article

  • Imitating Mouse click - point with known coordinates on a fusion table layer - google maps

    - by Yavor Tashev
    I have been making a script using a fusion table's layer in google maps. I am using geocoder and get the coordinates of a point that I need. I put a script that changes the style of a polygon from the fusion table when you click on it, using the google.maps.event.addListener(layer, "click", function(e) {}); I would like to use the same function that I call in the case of a click on the layer, but this time with a click with the coordinates that I got. I have tried google.maps.event.trigger(map, 'click', {latLng: new google.maps.LatLng(42.701487,26.772308)}); As well as the example here Google Fusion Table Double Click (dblClick) I have tried changing map with layer... I am sorry if my question is quite stupid, but I have tried many options. P.S. I have seen many post about getting the info from the table, but I do not need that. I want to change the style of the KML element in the selected row, so I do not see it happening by a query. Here is the model of my script: function initialize() { geocoder = new google.maps.Geocoder(); map = new google.maps.Map(document.getElementById("map_canvas"),myOptions); layer = new google.maps.FusionTablesLayer({ suppressInfoWindows:true, map : map, query : { select: '??????????????', from: '12ZoroPjIfBR4J-XwM6Rex7LmfhzCDJc9_vyG5SM' } }); google.maps.event.addListener(layer, "click", function(e) { SmeniStilRaionni(layer,e); marker.setMap(null); }); } function SmeniStilRaionni(layer,e) { ... } function showAddress(address) { geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { var point = results[0].geometry.location; //IMITATE THE CLICK } }); } In response to geocodezip This way you hide all the other elements... I do not wish that. It is like if I want to change the border of the selected element. And I do not wish for a new layer. In the function that I use now I push the style of the options of the layer and then set the option. I use the e from google.maps.event.addListener(layer, "click", function(e)); by inserting e.row['Name'].value inside the where rule. I would like to ask you if there is any info on the e variable in google.maps.event.addListener(layer, "click", function(e)); I found out how to get the results I wanted: For my query after I get the point I use this: var queryText ="SELECT '??????? ???','??????? ???','?????????? ???','??????????????' FROM "+FusionTableID+" WHERE ST_INTERSECTS(\'??????????????\', CIRCLE(LATLNG(" + point.toUrlValue(6) + "),0.5));"; queryText = encodeURIComponent(queryText); document.getElementById("vij query").innerHTML = queryText; var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText); And then I get these results: var rsyd = response.getDataTable().getValue(0,0); var osyd = response.getDataTable().getValue(0,1); var apsyd = response.getDataTable().getValue(0,2); And then, I use the following: where: "'??????? ???' = '"+rsyd+"'", Which is the same as: where: "'??????? ???' = '"+e.row['??????? ???'].value+"'", in the click function. This is a working solution for my problem. But still, I cannot find a way to Imitate a Mouse click.

    Read the article

  • No Method Error in Ruby

    - by JayG
    Hi, I currently have a Rails Apps that lets users drag and drop certain elements of the webpage and updates the application based on the users choice. This is done with the help of the Rails helpers and AJAX. However I keep running into a "NoMethodError" in Ruby. NoMethodError in ProjectsController#member_change undefined method `symbolize_keys' for nil:NilClass Here is the method that is being called. My trace says that error is occurring in this line: before = u.functions_for(r.authorizable_id) u.roles << r unless u.roles.include? r u.save flag_changed = true after = u.functions_for(r.authorizable_id) And here is the function being called def member_change flag_changed = false params['u'] =~ /role_(\d+)_user_(\d+)/ drag_role_id = $1 user_id = $2 params['r'] =~ /role_(\d+)/ drop_role_id = $1 if u=User.find(user_id) if r=Role.find(drop_role_id) if drag_role_id.to_i !=0 and old_r=Role.find(drag_role_id) if drag_role_id == drop_role_id #fom A to A => nothing happen flash.now[:warning] = _('No Operation...') elsif r.authorizable_id == old_r.authorizable_id #the same project? old_r.users.delete(u) unless old_r.valid? flash.now[:warning] = _('Group "Admin" CAN NOT be EMPTY.') old_r.users << u #TODO: better recovery member_edit #if flag_changed render :action => :member_edit, :layout => 'module_with_flash' return end old_r.save r.users << u unless r.users.include? u r.save flag_changed = true before = u.functions_for(r.authorizable_id) after = u.functions_for(r.authorizable_id) added = after - before removed = before - after added.each do |f| ApplicationController::send_msg(:function,:create, {:function_name => f.name, :user_id => u.id, :project_id => r.authorizable_id }) end removed.each do |f| ApplicationController::send_msg(:function,:delete, {:function_name => f.name, :user_id => u.id, :project_id => r.authorizable_id }) end flash.now[:notice] = _( 'Move User to Group' ) + " #{ r.name }" else flash.now[:warning] = _('You can\'t move User between Groups that belong to different Projects.') end else before = u.functions_for(r.authorizable_id) u.roles << r unless u.roles.include? r u.save flag_changed = true after = u.functions_for(r.authorizable_id) added = after - before added.each do |f| ApplicationController::send_msg(:function,:create, {:function_name => f.name, :user_id => u.id, :project_id => r.authorizable_id }) end flash.now[:notice] = _( 'Add User into Group' ) + " #{ r.name }" end else flash.now[:warn] = _( 'Group doesn\'t exist!' ) + ": #{ r.name }" end else flash.now[:warning] = _( 'User doesn\'t exist!' ) + ": #{ u.login }" end member_edit #if flag_changed render :action => :member_edit, :layout => 'module_with_flash' end and the JavaScript used to call the function jQuery('#RemoveThisMember').droppable({accept:'.RolesUsersSelection', drop:function(ev,ui){ if (confirm("This will remove User from this Group, are you sure?")) {jQuery.ajax({data:'u=' + encodeURIComponent(jQuery(ui.draggable).attr('id')), success:function(request){jQuery('#module_content').html(request);}, type:'post', url:'/of/projects/11/member_delete'});} }, hoverClass:'ProjectRoleDropDelete_active'}) Any ideas? Thanks,

    Read the article

  • Should one replace the usage addJSONData of jqGrid to the usage of setGridParam(), and trigger('relo

    - by Oleg
    Hi everybody who use jqGrid! I am a new on stackoverflow.com and it seems to me that a lot of peoples who use stackoverflow.com are not only the persons who have a problem which must be quickly solved. A lot of people read stackoverflow.com to look at well-known things from the other side. Sometime perhaps the reason is a self-training (to stay in the good form) during solving of problems other people. For all these gays, who not want only to solve his problem is my question. I wrote recently an answer to the question "jqGrid display default “loading” message when updating a table / on custom update". During writing of the answer I thought: why he uses addJSONData() function for refresh of data in the grid instead of changing URL with respect of setGridParam() and refreshing jqGrid data with respect of trigger('reloadGrid')? At the beginning I wanted to recommend using of 'reloadGrid', but after thinking about this I understood, that I am not quite sure what the best way is. At least I can't explain in two sentences why I prefer the second way. So I decide that it could be an interesting subject of a discussion. So to be exactly: We have a typical situation. We have a web page with at least one jqGrid and some other controls like combo-boxes (selects), checkboxes etc. which give user possibilities to change scope on information displayed in a jqGrid. Typically we define some event handler like jQuery("#selector").change(myRefresh).keyup(myKeyRefresh) and we need reload the jqGrid contain based on users choose. After reading and analyzing of the information from additional users input we can refresh jqGrid contain in at least two ways: Make call of $.ajax() manual and then inside of success or complete handle of $.ajax call jQuery.parseJSON() (or eval) and then call addJSONData function of jqGrid. I found a lot of examples on stackoverflow.com who use addJSONData. Update url of jqGrid based on users input, reset current page number to 1 and optionally change the caption of the grid. All these can be done with respect of setGridParam(), and optionally setCaption() jqGrid methods. At the end one call trigger('reloadGrid') method of the grid. To construct the url, by the way I use mostly jQuery.param function to be sure, that I all url parameters packed correctly with respect of encodeURIComponent. I want that we discuss advantages and disadvantages of both ways. I use currently the second way, so I start with advantages of this one. One can say me: I call existing Web Service, convert received data to the jqGrid format and call addJSONData. This is the reason why I use addJSONData method! OK, I choose another way. jqGrid can make a call of the Web Service directly and fill results inside of grid. There are a lot of jqGrid options, which allow you to customize this process. First of all, one can delete or rename any standard parameter sent to server with respect of prmNames option of jqGrid or add any more additional parameters with respect of postData option (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options). One can modify all constructed parameters immediately before jqGrid makes corresponding $.ajax request by defining of serializeGridData() function (one more option of jqGrid). More than that, one can change every $.ajax parameter by setting ajaxGridOptions option of jqGrid. I use ajaxGridOptions: {contentType: "application/json"} for example as a general setting of $.jgrid.defaults. The ajaxGridOptions option is very powerful. With respect of ajaxGridOptions option one can redefine any parameter of $.ajax request sending by jqGrid, like error, complete and beforeSend events. I see potentially interesting to define dataFilter event to be able makes any modification of the row data responded from the server. One more argument for using of trigger('reloadGrid') way is blocking of jqGrid during ajax request processing. Mostly I use parameter loadui: 'block' to block jqGrid during JSON request sending to server. With respect of jQuery blockUI plugin http://malsup.com/jquery/block/ one can block more parts of web page as the grid only. To do this one can call jQuery('#main').block({ message: '<h1>Die Daten werden vom Server geladen...</h1>' }); before calling of trigger('reloadGrid') method and jQuery('#main').unblock() inside of loadComplete and loadError functions. The loadui option could be set to 'disable' in this case. So I don’t see why the function addJSONData() should be used. Can somebody who use addJSONData() function explain me advantages of its usage? Should one replace the usage addJSONData of jqGrid to the usage of setGridParam(), and trigger('reloadGrid')? I am opened to the discussion.

    Read the article

< Previous Page | 1 2 3 4  | Next Page >