Search Results

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

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

  • encodeURIComponent is really useful?

    - by Marco Demaio
    Something I still don't understand when perfoming an http-get request to the server is what the advantage is in using JS fucntion encodeURIcomponent to encode each component of the http-get. Doing some tests I saw the server (using PHP) gets the values of the http-get request properly also if I don't use encodeURIcomponent!!! Obviuosly I still need to encode at client level the special character & ? = / : otherwise an http-get value like this "peace&love=virtue" would be considered as new key value pair of the http-get request instead of a one single value. But why does encodeURIcompenent encodes also many other charcaters like 'è' for example wich is translated into %C3%A8 that must be decoded on a PHP server using the utf8_decode function. By using encodeURIcomponent all values of the http-get request are utf8 encoded, therefor when getting them in PHP I have to call each time the utf8_decode function on each $_GET value which is quite annoying. Why can't we just encode only the & ? = / : charcaters??? see also: http://stackoverflow.com/questions/2607946/js-encodeuricomponent-result-different-from-the-one-created-by-form It shows that encodeURIComponent does not even encode properly because a simple browser FORM GET encodes charactrs like '€', in different way. So I still wonder what does this encodeURIComponent is for?

    Read the article

  • JS encodeURIComponent result different from the one created by FORM

    - by Marco Demaio
    I thought values entered in forms are properly encoded by browsers. But this simple test shows it's not true: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html><head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <title></title> </head><body> <form id="test" action="test_get_vs_encodeuri.html" method="GET" onsubmit="alert(encodeURIComponent(this.one.value));"> <input name="one" type="text" value="Euro-€"> <input type="submit" value="SUBMIT"> </form> </body></html> When hitting submit button: encodeURICompenent encodes input value into "Euro-%E2%82%AC" while browser into the GET query writes only a simple "Euro-%80" Could somone explain? Or is encodeURIComponent doing unnecessary conversions?

    Read the article

  • Does C# have an equivalent to JavaScript's encodeURIComponent()?

    - by travis
    In JavaScript: encodeURIComponent("©v") == "%C2%A9%E2%88%9A" Is there an equivalent for C# applications? For escaping HTML characters I used: txtOut.Text = Regex.Replace(txtIn.Text, @"[\u0080-\uFFFF]", m => @"&#" + ((int)m.Value[0]).ToString() + ";"); But I'm not sure how to convert the match to the correct hexadecimal format that JS uses. For example this code: txtOut.Text = Regex.Replace(txtIn.Text, @"[\u0080-\uFFFF]", m => @"%" + String.Format("{0:x}", ((int)m.Value[0]))); Returns "%a9%221a" for "©v" instead of "%C2%A9%E2%88%9A". It looks like I need to split the string up into bytes or something. Edit: This is for a windows app, the only items available in System.Web are: AspNetHostingPermission, AspNetHostingPermissionAttribute, and AspNetHostingPermissionLevel.

    Read the article

  • Encoding GBK2312 Condundrum

    - by user792271
    I am an amateur coder and I have a small problem. My goal is to have one text input with two buttons. The first button uses a bit of Javascript called SundayMorning to translate the text (to Chinese) The second button submits the text to a URL. The URl requires that Chinese text be encoded it in GBK2312 character set. I have duct taped together various found code to the result I have now. Due to the finicky behavior of the SundayMorning Javascript, my solution is to have two input boxes, the second of which I will hide. Right now, this doesn't work: I am unable to encode the Chinese in GBK2312, no matter what I try. BONUS CONUNDRUM: The second box copies my input letter by letter as I type, but does not copy the Chinese translation that the Javascript returns. Sorry for my janky amateur code. I defer to those more clever, if you have any kind suggestions. <head> <meta http-equiv="Content-Type" content="text/html; charset=GB2312" /> <script type='text/javascript' Src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'> </script> ///THIS JS TRANSLATES THE TEXT INLINE <script type="text/javascript" src="jquery.sundaymorning.js"> </script> <script type="text/javascript"> $(function() { $('#example3').sundayMorningReset(); $('#example3 input[type=image]').click(function(evt) { $.sundayMorning( $('#example3 input[type=text]').val(),{source:'en', destination:'ZH', menuLeft:evt.pageX, menuTop:evt.pageY},function(response) {$('#example3 input[type=text]').val(response.translation);});});}); </script> /// ///THIS PUTS THE CONTENT OF THE TRANSLATION BOX INTO THE SUBMISSION BOX <script type="text/javascript"> $(document).ready(function(){ var $url = $("#url"); $("#track").keyup(function() { $url.val(this.value);}); $("#track").blur(function() { $url.val(this.value);});}); </script> ///THIS PUTS THE CONTENT OF THE SUBMISSION INSIDE A URL <SCRIPT type="text/javascript"> function goToPage(url) { var initial = "http://example.com/"; var extension = ".html"; document.something.action=initial+url+extension; } </SCRIPT> </head> <body> <div id="featured"> <div id="example3"> <input type="text" name="track" id="track" value="" class="box"onkeydown="javascript:if (event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('mama').click();}};"/> <input type="image" src="http://taobaofieldguide.com/images/orange-translate-button.png" id="searchsubmit" value="Translate" class="btn" /> </div> <FORM name="something" method="post" onsubmit="goToPage(this.url.value);"> <input type="text" id="url";> <INPUT type="submit" id="mama" value="GO" > </FORM> </div> </body>

    Read the article

  • Curl, twitter oauth problem

    - by Darxval
    Does anyone see a problem with the following Curl call / how the Oauth request is built? (i am trying to get a correctly setup request so i can finish my app) So i am calling the following CURL call: C:\>curl -v -k --data-urlencode "status=Testing2" -H "Authorization: OAuth realm='', oauth_nonce=1276107867blah, oauth_timestamp=1276107867, oauth_consumer_key=yJDLH7BDdVi1OKIINSV7Q, oauth_signature_method=HMAC-SHA1, oauth_version=1.0, oauth_signature=NWU4MDdlNjk0OGIxYWQ1YTkyNmU5YjU1NGYyOTczMmU5ZDg5 YWNkNA==, staus=Testing2 " http://twitter.com/statuses/update.xml?status=Testing2 and i recieve this: * About to connect() to twitter.com port 80 (#0) * Trying 168.143.162.68... connected * Connected to twitter.com (168.143.162.68) port 80 (#0) > POST /statuses/update.xml?status=Testing2 HTTP/1.1 > User-Agent: curl/7.20.1 (i386-pc-win32) libcurl/7.20.1 OpenSSL/0.9.8n zlib/1.2.5 libidn/1.18 libssh2/1.2.5 > Host: twitter.com > Accept: */* > Authorization: OAuth realm='', oauth_nonce=1276106370blah, oauth_timestamp=1276106370, oauth_consumer_key=yJDLH7BDdVi1OKIINSV7Q, oauth_signature_method=HMAC-SHA1, oauth_version=1.0, oauth_signature=MjQzNDA1MGU4NGRmMWVjMzUwZmQ4YzE5NzMzY2I1ZDJlOTRkNmQ2Zg==, staus=Testing2 > Content-Length: 15 > Content-Type: application/x-www-form-urlencoded > < HTTP/1.1 401 Unauthorized < Date: Wed, 09 Jun 2010 18:00:22 GMT < Server: hi < Status: 401 Unauthorized < WWW-Authenticate: Basic realm="Twitter API" < X-Runtime: 0.00548 < Content-Type: application/xml; charset=utf-8 < Content-Length: 164 < Cache-Control: no-cache, max-age=1800 < Set-Cookie: k=209.234.229.21.1276106420885412; path=/; expires=Wed, 16-Jun-10 18:00:20 GMT; domain=.twitter.com < Set-Cookie: guest_id=127610642214871948; path=/; expires=Fri, 09 Jul 2010 18:00:22 GMT < Set-Cookie: _twitter_sess=BAh7CDoPY3JlYXRlZF9hdGwrCIm33h0pAToHaWQiJTkyMjllODE0NTdiYWE1%250AMWU1MzBmNjgwMTFiMDhkYjdlIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVy%250AOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--8ebb3c62d461d28f8fda7b8adab642af66969f7e; domain=.twitter.com; path=/ < Expires: Wed, 09 Jun 2010 18:30:20 GMT < Vary: Accept-Encoding < Connection: close < <?xml version="1.0" encoding="UTF-8"?> <hash> <request>/statuses/update.xml?status=Testing2</request> <error>Could not authenticate with OAuth.</error> </hash> * Closing connection #0 my Parameters are setup like so: var parameters = [encodeURIComponent("status="+status),encodeURIComponent("oauth_token="+ac_token),encodeURIComponent("oauth_consumer_key="+"yJDLH7BDdVi1OKIINSV7Q"),encodeURIComponent("oauth_nonce="+nonce,"oauth_signature_method=HMAC-SHA1"),encodeURIComponent("oauth_timestamp="+timestamp),encodeURIComponent("oauth_version=1.0")] var join = parameters.join("&"); var eparamjoin =encodeURIComponent(join); The key is like so: var key=con_secret+"&"+ac_secret; Signature base string is: var signaturebs = "POST&"+encodeURIComponent(url)+"&"+eparamjoin; giving this: POST&http%3A%2F%2Ftwitter.com%2Fstatuses%2Fupdate.xml&status%253DTesting2%26oauth_token%253D142715285-yi2ch324S3zfyKyJby6WDUZOhCsiQuKNUtc3nAGe%26oauth_consumer_key%253DyJDLH7BDdVi1OKIINSV7Q%26oauth_nonce%253D1276107867blah%26oauth_timestamp%253D1276107867%26oauth_version%253D1.0 and signature built like so: var hmac = Crypto.HMAC(Crypto.SHA1, signaturebs,key ); var signature=Base64.encode(hmac); making the signature: NWU4MDdlNjk0OGIxYWQ1YTkyNmU5YjU1NGYyOTczMmU5ZDg5YWNkNA== Any help would be appreciated thank you!

    Read the article

  • Value is not changing in the javascript variable on the onClick event

    - by Chetan sharma
    I am trying to implement a dynamic search jquery and php, but I am not able to change the value of a javascript variable on my onclick event. <script type="text/javascript"> var main_category = '<?php echo $main_category?>'; var main_url = '<?php echo $url?>get/' + encodeURIComponent(main_category) + '/'; var container_id = '<?php echo $unique_id?>content_area'; //name $('#<?php echo $unique_id?>search_by_name').autocomplete('<?php echo $url?>get_autocomplete_data/' + encodeURIComponent(main_category) + '/names/', { matchContains: "word", autoFill: true, width: 310 });$('#<?php echo $unique_id?>search_by_name').result(function (event, data){ var url = main_url + 'search/title/' + encodeURIComponent(data); load_div(container_id, url); }); //on click of displayed categories $('[rel="<?php echo $unique_id?>sub_category"]').click(function (){ window['main_category'] = this.title; $('#<?php echo $unique_id?>category').html('' +main_category+ ''); return false; }); }); </script> It changes the value when on click is fired //on click of displayed categories $('[rel="<?php echo $unique_id?>sub_category"]').click(function (){ window['main_category'] = this.title; $('#<?php echo $unique_id?>category').html('' +main_category+ ''); return false; }); but when after that i add data for the search it still searches for the old category $('#<?php echo $unique_id?>search_by_name').result(function (event, data){ var url = main_url + 'search/title/' + encodeURIComponent(data); load_div(container_id, url); }); "main_category" value is not changing in the "main_url"

    Read the article

  • Prefilling an SMS on Mobile Devices with the sms: Uri Scheme

    - by Rick Strahl
    Popping up the native SMS app from a mobile HTML Web page is a nice feature that allows you to pre-fill info into a text for sending by a user of your mobile site. The syntax is a bit tricky due to some device inconsistencies (and quite a bit of wrong/incomplete info on the Web), but it's definitely something that's fairly easy to do.In one of my Mobile HTML Web apps I need to share a current location via SMS. While browsing around a page I want to select a geo location, then share it by texting it to somebody. Basically I want to pre-fill an SMS message with some text, but no name or number, which instead will be filled in by the user.What worksThe syntax that seems to work fairly consistently except for iOS is this:sms:phonenumber?body=messageFor iOS instead of the ? use a ';' (because Apple is always right, standards be damned, right?):sms:phonenumber;body=messageand that works to pop up a new SMS message on the mobile device. I've only marginally tested this with a few devices: an iPhone running iOS 6, an iPad running iOS 7, Windows Phone 8 and a Nexus S in the Android Emulator. All four devices managed to pop up the SMS with the data prefilled.You can use this in a link:<a href="sms:1-111-1111;body=I made it!">Send location via SMS</a>or you can set it on the window.location in JavaScript:window.location ="sms:1-111-1111;body=" + encodeURIComponent("I made it!");to make the window pop up directly from code. Notice that the content should be URL encoded - HTML links automatically encode, but when you assign the URL directly in code the text value should be encoded.Body onlyI suspect in most applications you won't know who to text, so you only want to fill the text body, not the number. That works as you'd expect by just leaving out the number - here's what the URLs look like in that case:sms:?body=messageFor iOS same thing except with the ;sms:;body=messageHere's an example of the code I use to set up the SMS:var ua = navigator.userAgent.toLowerCase(); var url; if (ua.indexOf("iphone") > -1 || ua.indexOf("ipad") > -1) url = "sms:;body=" + encodeURIComponent("I'm at " + mapUrl + " @ " + pos.Address); else url = "sms:?body=" + encodeURIComponent("I'm at " + mapUrl + " @ " + pos.Address); location.href = url;and that also works for all the devices mentioned above.It's pretty cool that URL schemes exist to access device functionality and the SMS one will come in pretty handy for a number of things. Now if only all of the URI schemes were a bit more consistent (damn you Apple!) across devices...© Rick Strahl, West Wind Technologies, 2005-2013Posted in IOS  JavaScript  HTML5   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • How do I correctly decode unicode parameters passed to a servlet

    - by Grant Wagner
    Suppose I have: <a href="http://www.yahoo.com/" target="_yahoo" title="Yahoo!&#8482;" onclick="return gateway(this);">Yahoo!</a> <script type="text/javascript"> function gateway(lnk) { window.open(SERVLET + '?external_link=' + encodeURIComponent(lnk.href) + '&external_target=' + encodeURIComponent(lnk.target) + '&external_title=' + encodeURIComponent(lnk.title)); return false; } </script> I have confirmed external_title gets encoded as Yahoo!%E2%84%A2 and passed to SERVLET. If in SERVLET I do: Writer writer = response.getWriter(); writer.write(request.getParameter("external_title")); I get Yahoo!â„¢ in the browser. If I manually switch the browser character encoding to UTF-8, it changes to Yahoo!TM (which is what I want). So I figured the encoding I was sending to the browser was wrong (it was Content-type: text/html; charset=ISO-8859-1). I changed SERVLET to: response.setContentType("text/html; charset=utf-8"); Writer writer = response.getWriter(); writer.write(request.getParameter("external_title")); Now the browser character encoding is UTF-8, but it outputs Yahoo!â?¢ and I can't get the browser to render the correct character at all. My question is: is there some combination of Content-type and/or new String(request.getParameter("external_title").getBytes(), "UTF-8"); and/or something else that will result in Yahoo!TM appearing in the SERVLET output?

    Read the article

  • Create a Dellicious Bookmarklet in Firefox using Delicious API

    - by Steve
    I want to create a Delicious bookmarklet in Firefox that bookmarks the current page with a predefined tag. For proof of concept, if I enter this url, it works: https://john:[email protected]/v1/posts/add?url=http://www.google.com& description=http://www.google.com&tags=testtag But this as a bookmark doesn't, I get access denied: javascript:( function() { location.href = 'https://john:[email protected]/v1/posts/add?' + encodeURIComponent(window.location.href) + '&description=' + encodeURIComponent(document.title) + '&tags=testtag'; } )() Is this possible via a javascript bookmark?

    Read the article

  • jQuery AJAX call undefined error with special characters

    - by David
    Hi, I tried to make an AJAX call using jQuery, the data has special characters, e.g {'data':'<p>test</p>'}. It seems failed to pass this data in the first place. It will work if i just pass {'data':'test'}. encodeURIComponent and JSON.stringify failed here due to the special character < > /. Could anyone please help with it? Thanks. $.ajax({ type: "POST", url: "services.aspx", data: "data=" + encodeURIComponent(JSON.stringify(obj)), dataType: "text", error: function(xhr, textStatus, errorThrown) { alert("ERROR"); }, success: function(data) { } }); Regards, David

    Read the article

  • apostrophe issue with ajax post to php

    - by Ahmet vardar
    hi there, i am posting data with jquery ajax to php but if input has ' inside, data wont be posted. I tried encodeURIComponent but wont work. any idea on this ? thanks EDIT: my code var name = $("input#name_add").val(); name = encodeURIComponent(name); $.post("function.php", { name: name }, function(data) { //codes }); $query = "UPDATE `table` SET name = '" . stripslashes($_POST['name']) . "' WHERE ID = '$id'"; $result = mysql_query($query); if ($result){ print "ok"; }

    Read the article

  • Unicode and URI encoding, decoding and escaping in JavaScript

    - by apphacker
    If you look at this table here, it has a list of escape sequences for Unicode characters that don't actually work for me. For example for "%96", which should be a –, I get an error when trying decode: decodeURIComponent("%96"); URIError: URI malformed If I attempt to encode "–" I actually get: encodeURIComponent("–"); "%E2%80%93" I searched through the internet and I saw this page, which mentions using escape and unescape with decodeURIComponent and encodeURIComponent respectively. This doesn't seem to help because %96 doesn't show up as "–" no matter what I try and this of course wouldn't work: decodeURIComponent(escape("%96)); "%96" Not very helpful. How can I get "%96" to be a "–" with JavaScript (without hardcoding a map for every single possible unicode character I may run into)?

    Read the article

  • greasemonkey insert javascript

    - by Kaartz
    I have a bookmarklet, clicking the bookmarklet includes a PHP script (evaluated as a JavaScript file) to the page few table values and select values passed as GET parameters. The PHP script writes the page data to the MySQL database, and outputs a success message that is treated as JavaScript code and executed by the browser. Is there any possibility to do this using greasemonkey and call this function when a existing button is clicked on the web page. I wrote the above bookmarklet inspired by this tutorial. http://tutorialzine.com/2010/04/simple-bookmarking-app-php-javascript-mysql/ This is the bookmarklet code: (function () { var jsScript = document.createElement('script'); jsScript.setAttribute('type', 'text/javascript'); jsScript.setAttribute('src', '/bookmark.php?url=' + encodeURIComponent(location.href) + '&title=' + encodeURIComponent(document.title)); document.getElementsByTagName('head')[0].appendChild(jsScript); })(); Please help me.

    Read the article

  • How to encode content to send them via jquery to a php file?

    - by phpheini
    I am trying to send a form to a php file via jquery. The problem is, that the content, which has to be sent to the php file, contains slashes (/) since there is bb code inside. So I tried the following: $.ajax( { type: "POST", url: "create.php", data: "content=" + encodeURIComponent(content), cache: false, success: function(message) { $("#somediv").html(message); } }); In the php file I use rawurldecode to decode the content and get my bb codes back which I can then transform into html. The problem is as soon as I put the encodeURIComponent() it will ouput: [object HTMLTextAreaElement] What does that mean, where is my mistake? Thanks for your help! phpheini

    Read the article

  • what does calling ´this´ outside of a jquery plugin refer to

    - by Richard
    Hi, I am using the liveTwitter plugin The problem is that I need to stop the plugin from hitting the Twitter api. According to the documentation I need to do this $("#tab1 .container_twitter_status").each(function(){ this.twitter.stop(); }); Already, the each does not make sense on an id and what does this refer to? Anyway, I get an undefined error. I will paste the plugin code and hope it makes sense to somebody MY only problem thusfar with this plugin is that I need to be able to stop it. thanks in advance, Richard /* * jQuery LiveTwitter 1.5.0 * - Live updating Twitter plugin for jQuery * * Copyright (c) 2009-2010 Inge Jørgensen (elektronaut.no) * Licensed under the MIT license (MIT-LICENSE.txt) * * $Date: 2010/05/30$ */ /* * Usage example: * $("#twitterSearch").liveTwitter('bacon', {limit: 10, rate: 15000}); */ (function($){ if(!$.fn.reverse){ $.fn.reverse = function() { return this.pushStack(this.get().reverse(), arguments); }; } $.fn.liveTwitter = function(query, options, callback){ var domNode = this; $(this).each(function(){ var settings = {}; // Handle changing of options if(this.twitter) { settings = jQuery.extend(this.twitter.settings, options); this.twitter.settings = settings; if(query) { this.twitter.query = query; } this.twitter.limit = settings.limit; this.twitter.mode = settings.mode; if(this.twitter.interval){ this.twitter.refresh(); } if(callback){ this.twitter.callback = callback; } // ..or create a new twitter object } else { // Extend settings with the defaults settings = jQuery.extend({ mode: 'search', // Mode, valid options are: 'search', 'user_timeline' rate: 15000, // Refresh rate in ms limit: 10, // Limit number of results refresh: true }, options); // Default setting for showAuthor if not provided if(typeof settings.showAuthor == "undefined"){ settings.showAuthor = (settings.mode == 'user_timeline') ? false : true; } // Set up a dummy function for the Twitter API callback if(!window.twitter_callback){ window.twitter_callback = function(){return true;}; } this.twitter = { settings: settings, query: query, limit: settings.limit, mode: settings.mode, interval: false, container: this, lastTimeStamp: 0, callback: callback, // Convert the time stamp to a more human readable format relativeTime: function(timeString){ var parsedDate = Date.parse(timeString); var delta = (Date.parse(Date()) - parsedDate) / 1000; var r = ''; if (delta < 60) { r = delta + ' seconds ago'; } else if(delta < 120) { r = 'a minute ago'; } else if(delta < (45*60)) { r = (parseInt(delta / 60, 10)).toString() + ' minutes ago'; } else if(delta < (90*60)) { r = 'an hour ago'; } else if(delta < (24*60*60)) { r = '' + (parseInt(delta / 3600, 10)).toString() + ' hours ago'; } else if(delta < (48*60*60)) { r = 'a day ago'; } else { r = (parseInt(delta / 86400, 10)).toString() + ' days ago'; } return r; }, // Update the timestamps in realtime refreshTime: function() { var twitter = this; $(twitter.container).find('span.time').each(function(){ $(this).html(twitter.relativeTime(this.timeStamp)); }); }, // Handle reloading refresh: function(initialize){ var twitter = this; if(this.settings.refresh || initialize) { var url = ''; var params = {}; if(twitter.mode == 'search'){ params.q = this.query; if(this.settings.geocode){ params.geocode = this.settings.geocode; } if(this.settings.lang){ params.lang = this.settings.lang; } if(this.settings.rpp){ params.rpp = this.settings.rpp; } else { params.rpp = this.settings.limit; } // Convert params to string var paramsString = []; for(var param in params){ if(params.hasOwnProperty(param)){ paramsString[paramsString.length] = param + '=' + encodeURIComponent(params[param]); } } paramsString = paramsString.join("&"); url = "http://search.twitter.com/search.json?"+paramsString+"&callback=?"; } else if(twitter.mode == 'user_timeline') { url = "http://api.twitter.com/1/statuses/user_timeline/"+encodeURIComponent(this.query)+".json?count="+twitter.limit+"&callback=?"; } else if(twitter.mode == 'list') { var username = encodeURIComponent(this.query.user); var listname = encodeURIComponent(this.query.list); url = "http://api.twitter.com/1/"+username+"/lists/"+listname+"/statuses.json?per_page="+twitter.limit+"&callback=?"; } $.getJSON(url, function(json) { var results = null; if(twitter.mode == 'search'){ results = json.results; } else { results = json; } var newTweets = 0; $(results).reverse().each(function(){ var screen_name = ''; var profile_image_url = ''; if(twitter.mode == 'search') { screen_name = this.from_user; profile_image_url = this.profile_image_url; created_at_date = this.created_at; } else { screen_name = this.user.screen_name; profile_image_url = this.user.profile_image_url; // Fix for IE created_at_date = this.created_at.replace(/^(\w+)\s(\w+)\s(\d+)(.*)(\s\d+)$/, "$1, $3 $2$5$4"); } var userInfo = this.user; var linkified_text = this.text.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) { return m.link(m); }); linkified_text = linkified_text.replace(/@[A-Za-z0-9_]+/g, function(u){return u.link('http://twitter.com/'+u.replace(/^@/,''));}); linkified_text = linkified_text.replace(/#[A-Za-z0-9_\-]+/g, function(u){return u.link('http://search.twitter.com/search?q='+u.replace(/^#/,'%23'));}); if(!twitter.settings.filter || twitter.settings.filter(this)) { if(Date.parse(created_at_date) > twitter.lastTimeStamp) { newTweets += 1; var tweetHTML = '<div class="tweet tweet-'+this.id+'">'; if(twitter.settings.showAuthor) { tweetHTML += '<img width="24" height="24" src="'+profile_image_url+'" />' + '<p class="text"><span class="username"><a href="http://twitter.com/'+screen_name+'">'+screen_name+'</a>:</span> '; } else { tweetHTML += '<p class="text"> '; } tweetHTML += linkified_text + ' <span class="time">'+twitter.relativeTime(created_at_date)+'</span>' + '</p>' + '</div>'; $(twitter.container).prepend(tweetHTML); var timeStamp = created_at_date; $(twitter.container).find('span.time:first').each(function(){ this.timeStamp = timeStamp; }); if(!initialize) { $(twitter.container).find('.tweet-'+this.id).hide().fadeIn(); } twitter.lastTimeStamp = Date.parse(created_at_date); } } }); if(newTweets > 0) { // Limit number of entries $(twitter.container).find('div.tweet:gt('+(twitter.limit-1)+')').remove(); // Run callback if(twitter.callback){ twitter.callback(domNode, newTweets); } // Trigger event $(domNode).trigger('tweets'); } }); } }, start: function(){ var twitter = this; if(!this.interval){ this.interval = setInterval(function(){twitter.refresh();}, twitter.settings.rate); this.refresh(true); } }, stop: function(){ if(this.interval){ clearInterval(this.interval); this.interval = false; } } }; var twitter = this.twitter; this.timeInterval = setInterval(function(){twitter.refreshTime();}, 5000); this.twitter.start(); } }); return this; }; })(jQuery);

    Read the article

  • XMLHttpRequest leak in javascript. please help.

    - by Raja
    Hi everyone, Below is my javascript code snippet. Its not running as expected, please help me with this. <script type="text/javascript"> function getCurrentLocation() { console.log("inside location"); navigator.geolocation.getCurrentPosition(function(position) { insert_coord(new google.maps.LatLng(position.coords.latitude,position.coords.longitude)); }); } function insert_coord(loc) { var request = new XMLHttpRequest(); request.open("POST","start.php",true); request.onreadystatechange = function() { callback(request); }; request.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); request.send("lat=" + encodeURIComponent(loc.lat()) + "&lng=" + encodeURIComponent(loc.lng())); return request; } function callback(req) { console.log("inside callback"); if(req.readyState == 4) if(req.status == 200) { document.getElementById("scratch").innerHTML = "callback success"; window.setTimeout("getCurrentLocation()",5000); } } getCurrentLocation(); //called on body load </script> What i'm trying to achieve is to send my current location to the php page every 5 seconds or so. i can see few of the coordinates in my database but after sometime it gets weird. Firebug show very weird logs like simultaneous POST's at irregular intervals. Here's the firebug screenshot: IS there a leak in the program. please help.

    Read the article

  • Can't get data with spaces into the database from Ajax POST request

    - by J Jones
    I have a real simple form with a textbox and a button, and my goal is to have an asynchronous request (jQuery: $.ajax) send the text to the server (PHP/mysql a la Joomla) so that it can be added to a database table. Here's the javascript that is sending the data from the client: var value= $('#myvalue').val(); $.ajax( { type: "POST", url: "/administrator/index.php", data: { option: "com_mycomponent", task: "enterValue", thevalue: value, format: "raw"}, dataType: "text", success: reportSavedValue } ); The problem arises when the user enters text with a space in it. The $_POST variable that I receive has all the spaces stripped out, so that if the user enters "This string has spaces", the server gets the value "Thisstringhasspaces". I have been googling around, and have found lots of references that I need to use encodeURIComponent. So I have tried it, but now the value that I get from $_POST is "This20string20has20spaces". So it appears to be encoding it the way I would expect, only to have the percent signs stripped instead of the spaces, and leaving the hex numbers. I'm really confused. It seems that this sort of question is asked and answered everywhere on the web, and everywhere encodeURIComponent is hailed as the silver bullet. But apparently I'm fighting a different breed of lycanthrope. Does anyone have any suggestions?

    Read the article

  • Can I combine two functions into one using Javascript?

    - by Melissa
    I have the following code that I would like to simplify. With javascript and jQuery is there an easy way that I could combine these two functions? Most of the code is the same but I am not sure how I could create a single function that works differently depending on what is clicked. $(document).ready(function () { $('#ListBooks').click(ListBooks); $('#Create').click(Create); }); function Create() { var dataSourceID = $('#DataSourceID').val(); var subjectID = $('#SubjectID').val(); var contentID = $('#ContentID').val(); if (dataSourceID && dataSourceID != '00' && subjectID && subjectID != "00" && contentID && contentID != "00") { var e = encodeURIComponent, arr = ["dataSourceID=" + e(dataSourceID), "subjectID=" + e(subjectID), "contentID=" + e(contentID)]; window.location.href = '/Administration/Books/Create?' + arr.join("&"); } else { alert('Datasource, Subject and Content must be selected.'); } return false; } function ListBooks() { var dataSourceID = $('#DataSourceID').val(); var subjectID = $('#SubjectID').val(); var contentID = $('#ContentID').val(); if (dataSourceID && dataSourceID != '00' && subjectID && subjectID != "00" && contentID && contentID != "00") { var e = encodeURIComponent, arr = ["dataSourceID=" + e(dataSourceID), "subjectID=" + e(subjectID), "contentID=" + e(contentID)]; window.location.href = '/Administration/Books/ListBooks?' + arr.join("&"); } else { alert('Datasource, Subject and Content must be selected.'); } return false; }

    Read the article

  • How to implement a 'safe' periodical executer without using the Rails helpers?

    - by Robbie
    I am very new to Ruby on Rails and was never really big on writing JavaScript, so the built in helpers were like a tiny silce of heaven. However I have recently learned that using the helper methods creates "obtrusive javascript" so I am doing a tiny bit of refactoring to get all this messy code out of my view. I'm also using the Prototype API to figure out what all these functions do. Right now, I have: <%= periodically_call_remote(:url => {:action => "tablerefresh", :id => 1 }, :frequency => '5', :complete => "load('26', 'table1', request.responseText)")%> Which produces: <script type="text/javascript"> //<![CDATA[ new PeriodicalExecuter(function() {new Ajax.Request('/qrpsdrail/grids/tablerefresh/1', {asynchronous:true, evalScripts:true, onComplete:function(request){load('26', 'table1', request.responseText)}, parameters:'authenticity_token=' + encodeURIComponent('dfG7wWyVYEpelfdZvBWk7MlhzZoK7VvtT/HDi3w7gPM=')})}, 5) //]]> </script> My concern is that the "encodeURIComponent" and the presence of "authenticity_token" are generated by Rails. I'm assuming these are used to assure the validity of a request. (Ensuring a request comes from a currently active session?) If that is the case, how can I implement this in application.js 'safely'? It seems that the built in method, although obtrusive, does add some beneficial security. Thanks, in advance, to all who answer.

    Read the article

  • Javascript and jQuery (Fancybox) question

    - by songdogtech
    Javascript and jQuery (Fancybox) question I'm using the Javascript function below for Twitter sharing (as well as other services; the function code is simplified to just Twitter for this question) that grabs the to-be-shared page URL and title and it is invoked in the link with onclick. That results in the Twitter share page loading in a pop up browser window, i.e.<img src="/images/twitter_16.png" onclick="share.tw()" /> In order to be consistent with other design aspects of the site, what I'd like to be able to do is have the Twitter share page open not in a standard browser window but in a Fancybox (jQuery) window. Fancybox can load an external page in an iFrame when the img or href link contains a class (in this case class="iframe" ) in the link and in the document ready function in the header. Right now, of course, when I give the iframe class to the link that also has the onclick share.tw(), I get two popups: one browser window popup with the correct Twitter share page loaded, and a Fancybox jQuery popup that shows a site 404. How can I change the function to use Fancybox to present the Twitter share page? Is that a correct way to approach it? Or is there a better way, such as implementing the share function in jQuery, too? Thanks... Javascript share function: var share = { tw:function(title,url) { this.share('http://twitter.com/home?status=##URL##+##TITLE##',title,url); }, share:function(tpl,title,url) { if(!url) url = encodeURIComponent(window.location); if(!title) title = encodeURIComponent(document.title); tpl = tpl.replace("##URL##",url); tpl = tpl.replace("##TITLE##",title); window.open(tpl,"sharewindow"+tpl.substr(6,15),"width=640,height=480"); } }; It is invoked, i.e.: <img src="/images/twitter_16.png" onclick="share.tw()" /> Fancybox function, invoked by adding class="iframe" in the img or href link $(".iframe").fancybox({ 'width' : '100%', 'height' : '100%', 'autoScale' : false, 'transitionIn' : 'none', 'transitionOut' : 'none', 'type' : 'iframe' });

    Read the article

  • XMLHttpRequest leak

    - by Raja
    Hi everyone, Below is my javascript code snippet. Its not running as expected, please help me with this. <script type="text/javascript"> function getCurrentLocation() { console.log("inside location"); navigator.geolocation.getCurrentPosition(function(position) { insert_coord(new google.maps.LatLng(position.coords.latitude,position.coords.longitude)); }); } function insert_coord(loc) { var request = new XMLHttpRequest(); request.open("POST","start.php",true); request.onreadystatechange = function() { callback(request); }; request.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); request.send("lat=" + encodeURIComponent(loc.lat()) + "&lng=" + encodeURIComponent(loc.lng())); return request; } function callback(req) { console.log("inside callback"); if(req.readyState == 4) if(req.status == 200) { document.getElementById("scratch").innerHTML = "callback success"; //window.setTimeout("getCurrentLocation()",5000); setTimeout(getCurrentLocation,5000); } } getCurrentLocation(); //called on body load </script> What i'm trying to achieve is to send my current location to the php page every 5 seconds or so. i can see few of the coordinates in my database but after sometime it gets weird. Firebug show very weird logs like simultaneous POST's at irregular intervals. Here's the firebug screenshot: IS there a leak in the program. please help. EDIT: The expected outcome in the firebug console should be like this :- inside location POST .... inside callback /* 5 secs later */ inside location POST ... inside callback /* keep repeating */

    Read the article

  • BING Search using ASP.NET and jQuery Ajax

    - by hajan
    The BING API provides extremely simple way to make search queries using BING. It provides nice way to get the search results as XML or JSON. In this blog post I will show one simple example on how to query BING and get the results as JSON in an ASP.NET website with help of jQuery’s getJSON ajax method. Basically we submit an HTTP GET request with the AppID which you can get in the BING Developer Center. To create new AppID, click here. Once you fill the form, submit it and you will get your AppID. Now, lets make this work in several steps. 1. Open VS.NET or Visual Web Developer.NET, create new sample project (or use existing one) and create new ASPX Web Form with name of your choice. 2. Add the following ASPX in your page body <body>     <form id="form1" runat="server">     <asp:TextBox ID="txtSearch" runat="server" /> <asp:Button ID="btnSearch" runat="server" Text="BING Search" />     <div id="result">          </div>     </form> </body> We have text box for search, button for firing the search event and div where we will place the results. 3. Next, I have created simple CSS style for the search result: <style type="text/css">             .item { width:600px; padding-top:10px; }             .title { background-color:#4196CE; color:White; font-size:18px;              font-family:Calibri, Verdana, Tahoma, Sans-Serif; padding:2px 2px 2px 2px; }     .title a { text-decoration:none; color:white}     .date { font-style:italic; font-size:10px; font-family:Verdana, Arial, Sans-Serif;}             .description { font-family:Verdana, Arial, Sans-Serif; padding:2px 2px 2px 2px; font-size:12px; }     .url { font-size: 10px; font-style:italic; font-weight:bold; color:Gray;}     .url a { text-decoration:none; color:gray;}     #txtSearch { width:450px; border:2px solid #4196CE; } </style> 4. The needed jQuery Scripts (v1.4.4 core jQuery and jQuery template plugin) <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.min.js" type="text/javascript"></script> <script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js" type="text/javascript"></script> Note: I use jQuery Templates plugin in order to avoid foreach loop in the jQuery callback function. JQuery Templates also simplifies the code and allows us to create nice template for the end result. You can read more about jQuery Templates here. 5. Now, lets create another script tag where we will write our BING search script <script language="javascript" type="text/javascript">     $(document).ready(function () {         var bingAPIKey = "<Your-BING-AppID-KEY-HERE>";                  //the rest of the script goes here              }); </script> 6. Before we do any searching, we need to take a look at the search URL that we will call from our Ajax function BING Search URL : http://api.search.live.net/json.aspx?JsonType=callback&JsonCallback=?&AppId={appId}&query={query}&sources={sourceType} The URL in our example is as follows: http://api.search.live.net/json.aspx?JsonType=callback&JsonCallback=?&Appid=" + bingAPIKey + "&query=" + keyWords + "&sources=web Lets split it up with brief explanation on each part of the URL http://api.search.live.net/json.aspx – is the main part of the URL which is used to call when we need to retrieve json result set. JsonType=callback&JsonCallback=? – using JsonType, we can control the format of the response. For more info about this, refer here. Appid=” + bingAPIKey +” – the AppID we’ve got from the BING website, explained previously query=” + keyWords + “ – the search query keywords sources=web – the type of source. Possible source types can be found here. 7. Before we continue with writing the last part of the script, lets see what search result BING will send us back: {"SearchResponse":     {         "Version":"2.2",         "Query":             {                 "SearchTerms":"hajan selmani aspnet weblog"             },         "Web":             {                 "Total":16,                 "Offset":0,                 "Results":[                     {                         "Title":"Hajan's Blog",                         "Description":"microsoft asp.net development blog ... Create nice animation on your ASP.NET Menu control using jQuery by hajan",                         "Url":"http:\/\/weblogs.asp.net\/hajan\/",                         "CacheUrl":"http:\/\/cc.bingj.com\/cache.aspx?q=hajan+selmani+aspnet+weblog&d=4760941354158132&w=c9535fb0,d1d66baa",                         "DisplayUrl":"weblogs.asp.net\/hajan",                         "DateTime":"2011-03-03T18:24:00Z"                     },                     {                         "Title":"codeasp.net",                         "Description":"... social community for ASP.NET bloggers - we are one of                                         the largest ASP.NET blog ... 2\/5\/2011 1:41:00 AM by Hajan Selmani - Comments ...",                         "Url":"http:\/\/codeasp.net\/blogs\/hajan",                         "CacheUrl":"http:\/\/cc.bingj.com\/cache.aspx?q=hajan+selmani+aspnet+weblog&d=4826710187311653&w=5b41c930,676a37f8",                         "DisplayUrl":"codeasp.net\/blogs\/hajan",                         "DateTime":"2011-03-03T07:40:00Z"                     }                     ...                         ]             }     } }  To get to the result of the search response, the path is: SearchResponse.Web.Results, where we have array of objects returned back from BING. 8. The final part of the code that performs the search is $("#<%= btnSearch.ClientID %>").click(function (event) {     event.preventDefault();     var keyWords = $("#<%= txtSearch.ClientID %>").val();     var encodedKeyWords = encodeURIComponent(keyWords);     //alert(keyWords);     var url = "http://api.search.live.net/json.aspx?JsonType=callback&JsonCallback=?&Appid="+ bingAPIKey              + "&query=" + encodedKeyWords              + "&sources=web";     $.getJSON(url, function (data) {         $("#result").html("");         $("#bingSearchTemplate").tmpl(data.SearchResponse.Web.Results).appendTo("#result");     }); }); The search happens once we click the Search Button with id btnSearch. We get the keywords from the Text Box with id txtSearch and then we use encodeURIComponent. The encodeURIComponent is used to encode the special characters such as: , / ? : @ & = + $ #, which might be part of the search query string. Then we construct the URL and call it using HTTP GET. The callback function returns the data, where we first clear the html inside div with id result and after that we render the data.SearchResponse.Web.Results array of objects using template with id bingSearchTemplate and append the result into div with id result. 9. The bingSearchTemplate Template <script id="bingSearchTemplate" type="text/html">     <div class="item">         <div class="title"><a href="${Url}" target="_blank">${Title}</a></div>         <div class="date">${DateTime}</div>         <div class="searchresult">             <div class="description">             ${Description}             </div>             <div class="url">                 <a href="${Url}" target="_blank">${Url}</a>             </div>         </div>     </div> </script> If you paid attention on the search result structure that BING creates for us, you have seen properties like Url, Title, Description, DateTime etc. In the above defined template, you see the same wrapped into template tags. Some are combined to create hyperlinked URLs. 10. THE END RESULT   As you see, it’s quite simple to use BING API and make search queries with ASP.NET and jQuery. In addition, if you want to make instant search, replace this line: $(“#<%= btnSearch.ClientID %>”).click(function(event) {        event.preventDefault(); with $(“#<%= txtSearch.ClientID %>”).keyup(function() { This will trigger search on each key up in your keyboard, so if you use this approach, you won’t event need a search button. If it’s your first time working with BING API, it’s very recommended to read the following API Basics PDF document. Hope this was helpful blog post for you.

    Read the article

1 2 3 4  | Next Page >