Search Results

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

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

  • jQuery - google chrome won't get updated textarea value

    - by Phil Jackson
    Hi, I have a textarea with default text 'write comment...'. when a user updates the textarea and clicks 'add comment' Google chrome does not get the new text. heres my code; function add_comment( token, loader ){ $('textarea.n-c-i').focus(function(){ if( $(this).html() == 'write a comment...' ) { $(this).html(''); } }); $('textarea.n-c-i').blur(function(){ if( $(this).html() == '' ) { $(this).html('write a comment...'); } }); $(".add-comment").bind("click", function() { try{ var but = $(this); var parent = but.parents('.n-w'); var ref = parent.attr("ref"); var comment_box = parent.find('textarea'); var comment = comment_box.val(); alert(comment); var con_wrap = parent.find('ul.com-box'); var contents = con_wrap .html(); var outa_wrap = parent.find('.n-c-b'); var outa = outa_wrap.html(); var com_box = parent.find('ul.com-box'); var results = parent.find('p.com-result'); results.html(loader); comment_box.attr("disabled", "disabled"); but.attr("disabled", "disabled"); $.ajax({ type: 'POST', url: './', data: 'add-comment=true&ref=' + encodeURIComponent(ref) + '&com=' + encodeURIComponent(comment) + '&token=' + token + '&aj=true', cache: false, timeout: 7000, error: function(){ $.fancybox(internal_error, internal_error_fbs); results.html(''); comment_box.removeAttr("disabled"); but.removeAttr("disabled"); }, success: function(html){ auth(html); if( html != '<span class="error-msg">Error, message could not be posted at this time</span>' ) { if( con_wrap.length == 0 ) { outa_wrap.html('<ul class="com-box">' + html + '</ul>' + outa); outa_wrap.find('li:last').fadeIn(); add_comment( token, loader ); }else{ com_box.html(contents + html); com_box.find('li:last').fadeIn(); } } results.html(''); comment_box.removeAttr("disabled"); but.removeAttr("disabled"); } }); }catch(err){alert(err);} return false; }); } any help much appreciated.

    Read the article

  • decodeURIComponent for postgres

    - by maletin
    I use decodeURIComponent and encodeURIComponent in Javascript. Before I store this data in a UTF-8-PostgreSQL-Database, I should decode them: $my_data = pg_escape_string(utf8_encode($_POST['my_data'])); I'm looking for a PostgreSQL-Function to convert Javascript-Encoded Data.

    Read the article

  • Anti-Forgery Request Helpers for ASP.NET MVC and jQuery 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 in 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" /> <% } %> This invocation generates a token then writes inside 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 also writes into the cookie: __RequestVerificationToken_Lw__= J56khgCvbE3bVcsCSZkNVuH9Cclm9SSIT/ywruFsXEgmV8CL2eW5C/gGsQUf/YuP When the above form is submitted, they are both sent to server. In the server side, [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, some problems are encountered. Specify validation on controller (not on each action) The server side problem is, It is expected to declare [ValidateAntiForgeryToken] on controller, but actually it has be to declared on each POST actions. Because POST actions are usually much more then controllers, this is a little crazy Problem Usually a controller contains actions for HTTP GET and actions for 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 invalid:[ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public class SomeController : Controller // One [ValidateAntiForgeryToken] attribute. { [HttpGet] public ActionResult Index() // Index() cannot work. { // ... } [HttpPost] public ActionResult PostAction1(/* ... */) { // ... } [HttpPost] public ActionResult PostAction2(/* ... */) { // ... } // ... } If browser sends an HTTP GET request by clicking 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 POST action:public class SomeController : Controller // Many [ValidateAntiForgeryToken] attributes. { [HttpGet] public ActionResult Index() // Works. { // ... } [HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult PostAction1(/* ... */) { // ... } [HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult PostAction2(/* ... */) { // ... } // ... } This is a little bit crazy, because one application can have a lot of POST actions. Solution To avoid a large number of [ValidateAntiForgeryToken] attributes (one for each POST action), the following ValidateAntiForgeryTokenAttribute wrapper class can be helpful, 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 { // GET actions are not affected. // Only HTTP POST requests are validated. } Now one single attribute on controller turns on validation for all POST actions. Maybe it would be nice if HTTP verbs can be specified on the built-in [ValidateAntiForgeryToken] attribute, which is easy to implemented. Submit token via AJAX The browser side problem is, if server side turns on anti-forgery validation for POST, then AJAX POST requests will fail be default. Problem For AJAX scenarios, when request is sent by jQuery 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 tokens are printed to browser then sent back to server. So first of all, HtmlHelper.AntiForgeryToken() must be called somewhere. Now the browser has token in HTML and cookie. Then jQuery must find the printed token in the HTML, and append token to the data before sending:$.post(url, { productName: "Tofu", categoryId: 1, __RequestVerificationToken: getToken() // Token is posted. }, callback); To be reusable, this can be encapsulated into a tiny jQuery plugin:/// <reference path="jquery-1.4.2.js" /> (function ($) { $.getAntiForgeryToken = function (tokenWindow, appPath) { // HtmlHelper.AntiForgeryToken() must be invoked to print the token. tokenWindow = tokenWindow && typeof tokenWindow === typeof window ? tokenWindow : window; appPath = appPath && typeof appPath === "string" ? "_" + appPath.toString() : ""; // The name attribute is either __RequestVerificationToken, // or __RequestVerificationToken_{appPath}. tokenName = "__RequestVerificationToken" + appPath; // Finds the <input type="hidden" name={tokenName} value="..." /> from the specified. // var inputElements = $("input[type='hidden'][name='__RequestVerificationToken" + appPath + "']"); var inputElements = tokenWindow.document.getElementsByTagName("input"); for (var i = 0; i < inputElements.length; i++) { var inputElement = inputElements[i]; if (inputElement.type === "hidden" && inputElement.name === tokenName) { return { name: tokenName, value: inputElement.value }; } } return null; }; $.appendAntiForgeryToken = function (data, token) { // Converts data if not already a string. if (data && typeof data !== "string") { data = $.param(data); } // Gets token from current window by default. token = token ? token : $.getAntiForgeryToken(); // $.getAntiForgeryToken(window). data = data ? data + "&" : ""; // If token exists, appends {token.name}={token.value} to data. return token ? data + encodeURIComponent(token.name) + "=" + encodeURIComponent(token.value) : data; }; // Wraps $.post(url, data, callback, type). $.postAntiForgery = function (url, data, callback, type) { return $.post(url, $.appendAntiForgeryToken(data), callback, type); }; // Wraps $.ajax(settings). $.ajaxAntiForgery = function (settings) { settings.data = $.appendAntiForgeryToken(settings.data); return $.ajax(settings); }; })(jQuery); In most of the scenarios, it is Ok to just replace $.post() invocation with $.postAntiForgery(), and replace $.ajax() with $.ajaxAntiForgery():$.postAntiForgery(url, { productName: "Tofu", categoryId: 1 }, callback); // Token is posted. There might be some scenarios of custom token. Here $.appendAntiForgeryToken() is provided:data = $.appendAntiForgeryToken(data, token); // Token is already in data. No need to invoke $.postAntiForgery(). $.post(url, data, callback); And there are scenarios that the token is not in the current window. For example, an HTTP POST request can be sent by iframe, while the token is in the parent window. Here window can be specified for $.getAntiForgeryToken():data = $.appendAntiForgeryToken(data, $.getAntiForgeryToken(window.parent)); // Token is already in data. No need to invoke $.postAntiForgery(). $.post(url, data, callback); If you have better solution, please do tell me.

    Read the article

  • Bookmarking n Joomla

    - by Aruna
    Hi, i am using the Plugin Content Bookmarker downloaded from http://dev.aarthikaindia.com/downloads/category/3-plugins.html for my site. Some of the Articles are able to Bookmark like if i click on the Bookmark (twitter) , it directly bookmarks in Twitter with Some description of the Article where some of the Articles are not bookmarked instead it just links to http://www.twitter.com.. Code : <?php // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ); $mainframe->registerEvent( 'onAfterDisplayContent', 'plgContentBookmarker' ); function plgContentBookmarker( &$row, &$params, $page=0 ) { $plugin = & JPluginHelper::getPlugin('content', 'bookmarker'); // Load plugin params info $pluginParams = new JParameter($plugin->params); $id = $row-id; $desc_tags = addslashes(str_replace("\n","", $row->title )); $desc_tags = trim($desc_tags); $desc_tags_space= str_replace(',', ' ', @$desc_tags_space); $desc_tags_semi = str_replace(',', ';', @$desc_tags_semi); $desc_tags_space = str_replace(' ', ' ', @$desc_tags_space); $description1 = strip_tags( $row->introtext ); $description2 = str_replace("'", '', strip_tags($description1)); $description = str_replace('"', '', strip_tags($description2)); $markme_title = $desc_tags; $markme_ddesc = substr($description,0,400).'...'; $baseurl = JURI::base(); $title = $pluginParams->def('title', 'Book Mark this Article'); $facebook = $pluginParams->def('facebook', '1'); $twitter = $pluginParams->def('twitter', '1'); $html.= '<div onmouseover="javascript:if(document.getElementById(\'divShowAddBookmarker'.$id.'\').style.display ==\'none\'){document.getElementById(\'divShowAddBookmarker'.$id.'\').style.display =\'block\';}" onmouseout="javascript:if(document.getElementById(\'divShowAddBookmarker'.$id.'\').style.display ==\'block\'){document.getElementById(\'divShowAddBookmarker'.$id.'\').style.display =\'none\';}" id="divShowAddBookmarker'.$id.'" style="display:none;position:absolute; background-color:#F4F4F4;width:240px;padding:3px;border:2px solid #999999;z-index:999"> <div style="padding:2px;">'; if( $facebook == 1 ) { $html.= '<div style="width:115px;float:left"> <a style="text-decoration:none;" href="http://www.facebook.com/" onclick="window.open(\'http://www.facebook.com/share.php?u=\'+encodeURIComponent(location.href)+\'&amp;t='.$markme_title.'&amp;d='.$markme_ddesc.'\');return false;"> <img style="vertical-align:bottom;padding:1px;" src="'.$baseurl."plugins/content/smart_bookmarker/facebook.gif".'" title="Facebook" name="facebook" border="0" id="facebook" alt="" /> '.JText::_( 'Facebook' ).' </a> </div>'; } if( $twitter == 1 ) { $html.= '<div style="width:115px;float:left"> <a style="text-decoration:none;" href="http://www.twitter.com/" onclick="window.open(\'http://twitter.com/home/?status=\'+encodeURIComponent(location.href)+\'-'.$markme_ddesc.'\');return false;"> <img style="vertical-align:bottom;padding:1px;" src="'.$baseurl."plugins/content/smart_bookmarker/twitter.gif".'" title="twitter" name="twitter" border="0" id="twitter" alt="" /> '.JText::_( 'Twitter' ).' </a> </div>'; } $html.= '<div style="clear:both"></div> </div> </div>'; return $html; } ? In the CODE $markme_ddesc is used to give the status message which is the actual portion of the content which is tweeted .. I had a doubt whether this $markme_ddesc is used to make the issue.. Is it so.. Please suggest me..

    Read the article

  • Anti-Forgery Request Recipes For 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 in 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" /> <% } %> This invocation generates a token then writes inside 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 also writes into the cookie: __RequestVerificationToken_Lw__= J56khgCvbE3bVcsCSZkNVuH9Cclm9SSIT/ywruFsXEgmV8CL2eW5C/gGsQUf/YuP When the above form is submitted, they are both sent to server. In the server side, [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, some problems are encountered. Specify validation on controller (not on each action) The server side problem is, It is expected to declare [ValidateAntiForgeryToken] on controller, but actually it has be to declared on each POST actions. Because POST actions are usually much more then controllers, the work would be a little crazy. Problem Usually a controller contains actions for HTTP GET and actions for 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 invalid:[ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public class SomeController : Controller // One [ValidateAntiForgeryToken] attribute. { [HttpGet] public ActionResult Index() // Index() cannot work. { // ... } [HttpPost] public ActionResult PostAction1(/* ... */) { // ... } [HttpPost] public ActionResult PostAction2(/* ... */) { // ... } // ... } If browser sends an HTTP GET request by clicking 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 POST action:public class SomeController : Controller // Many [ValidateAntiForgeryToken] attributes. { [HttpGet] public ActionResult Index() // Works. { // ... } [HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult PostAction1(/* ... */) { // ... } [HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult PostAction2(/* ... */) { // ... } // ... } This is a little bit crazy, because one application can have a lot of POST actions. Solution To avoid a large number of [ValidateAntiForgeryToken] attributes (one for each POST action), the following ValidateAntiForgeryTokenWrapperAttribute wrapper class can be helpful, 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 { // GET actions are not affected. // Only HTTP POST requests are validated. } Now one single attribute on controller turns on validation for all POST actions. Maybe it would be nice if HTTP verbs can be specified on the built-in [ValidateAntiForgeryToken] attribute, which is easy to implemented. Specify Non-constant salt in runtime By default, the salt should be a compile time constant, so it can be used for the [ValidateAntiForgeryToken] or [ValidateAntiForgeryTokenWrapper] attribute. Problem One Web product might be sold to many clients. If a constant salt is evaluated in compile time, after the product is built and deployed to many clients, they all have the same salt. Of course, clients do not like this. Even some clients might want to specify a custom salt in configuration. In these scenarios, salt is required to be a runtime value. Solution In the above [ValidateAntiForgeryToken] and [ValidateAntiForgeryTokenWrapper] attribute, the salt is passed through constructor. So one solution is to remove this parameter:public class ValidateAntiForgeryTokenWrapperAttribute : FilterAttribute, IAuthorizationFilter { public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs) { this._verbs = new AcceptVerbsAttribute(verbs); this._validator = new ValidateAntiForgeryTokenAttribute() { Salt = AntiForgeryToken.Value }; } // Other members. } But here the injected dependency becomes a hard dependency. So the other solution is moving validation code into controller to work around the limitation of attributes:public abstract class AntiForgeryControllerBase : Controller { private readonly ValidateAntiForgeryTokenAttribute _validator; private readonly AcceptVerbsAttribute _verbs; protected AntiForgeryControllerBase(HttpVerbs verbs, string salt) { this._verbs = new AcceptVerbsAttribute(verbs); this._validator = new ValidateAntiForgeryTokenAttribute() { Salt = salt }; } protected override void OnAuthorization(AuthorizationContext filterContext) { base.OnAuthorization(filterContext); string httpMethodOverride = filterContext.HttpContext.Request.GetHttpMethodOverride(); if (this._verbs.Verbs.Contains(httpMethodOverride, StringComparer.OrdinalIgnoreCase)) { this._validator.OnAuthorization(filterContext); } } } Then make controller classes inheriting from this AntiForgeryControllerBase class. Now the salt is no long required to be a compile time constant. Submit token via AJAX For browser side, once server side turns on anti-forgery validation for HTTP POST, all AJAX POST requests will fail by default. Problem In AJAX scenarios, the HTTP POST request is not sent by form. Take jQuery as an example:$.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 Basically, the tokens must be printed to browser then sent back to server. So first of all, HtmlHelper.AntiForgeryToken() need to be called somewhere. Now the browser has token in both HTML and cookie. Then jQuery must find the printed token in the HTML, and append token to the data before sending:$.post(url, { productName: "Tofu", categoryId: 1, __RequestVerificationToken: getToken() // Token is posted. }, callback); To be reusable, this can be encapsulated into a tiny jQuery plugin:/// <reference path="jquery-1.4.2.js" /> (function ($) { $.getAntiForgeryToken = function (tokenWindow, appPath) { // HtmlHelper.AntiForgeryToken() must be invoked to print the token. tokenWindow = tokenWindow && typeof tokenWindow === typeof window ? tokenWindow : window; appPath = appPath && typeof appPath === "string" ? "_" + appPath.toString() : ""; // The name attribute is either __RequestVerificationToken, // or __RequestVerificationToken_{appPath}. tokenName = "__RequestVerificationToken" + appPath; // Finds the <input type="hidden" name={tokenName} value="..." /> from the specified. // var inputElements = $("input[type='hidden'][name='__RequestVerificationToken" + appPath + "']"); var inputElements = tokenWindow.document.getElementsByTagName("input"); for (var i = 0; i < inputElements.length; i++) { var inputElement = inputElements[i]; if (inputElement.type === "hidden" && inputElement.name === tokenName) { return { name: tokenName, value: inputElement.value }; } } return null; }; $.appendAntiForgeryToken = function (data, token) { // Converts data if not already a string. if (data && typeof data !== "string") { data = $.param(data); } // Gets token from current window by default. token = token ? token : $.getAntiForgeryToken(); // $.getAntiForgeryToken(window). data = data ? data + "&" : ""; // If token exists, appends {token.name}={token.value} to data. return token ? data + encodeURIComponent(token.name) + "=" + encodeURIComponent(token.value) : data; }; // Wraps $.post(url, data, callback, type). $.postAntiForgery = function (url, data, callback, type) { return $.post(url, $.appendAntiForgeryToken(data), callback, type); }; // Wraps $.ajax(settings). $.ajaxAntiForgery = function (settings) { settings.data = $.appendAntiForgeryToken(settings.data); return $.ajax(settings); }; })(jQuery); In most of the scenarios, it is Ok to just replace $.post() invocation with $.postAntiForgery(), and replace $.ajax() with $.ajaxAntiForgery():$.postAntiForgery(url, { productName: "Tofu", categoryId: 1 }, callback); // Token is posted. There might be some scenarios of custom token, where $.appendAntiForgeryToken() is useful:data = $.appendAntiForgeryToken(data, token); // Token is already in data. No need to invoke $.postAntiForgery(). $.post(url, data, callback); And there are scenarios that the token is not in the current window. For example, an HTTP POST request can be sent by an iframe, while the token is in the parent window. Here, token's container window can be specified for $.getAntiForgeryToken():data = $.appendAntiForgeryToken(data, $.getAntiForgeryToken(window.parent)); // Token is already in data. No need to invoke $.postAntiForgery(). $.post(url, data, callback); If you have better solution, please do tell me.

    Read the article

  • JSON htmlentities javascript

    - by Wessel Rossing
    Hi! I am using an XMLHttpRequest to POST a JSON string to PHP. The JSON object is created in JavaScript and using the JSON2.js from json.org to create an JSON string representing the object. JSON.stringify(object); Whenever the object contains a string which has a special character in it, e.g. é, JavaScript does not give any error but PHP receives an empty array [] Is there a JavaScript function which produces the exact same resutls as the PHP function htmlentities() The data is send via POST, so the following functions escape() encodeURI() encodeURIComponent() are a bit overkill. Thanks!

    Read the article

  • Error on change form action

    - by Thomas
    Hi, I'm changing the form action with: window.onload = function() { document.getElementById('pdf').onclick = addExportEvent; document.getElementById('xls').onclick = addExportEvent; document.getElementById('xml').onclick = addExportEvent; document.getElementById('csv').onclick = addExportEvent; } function addExportEvent() { data = grid.getAllGridData(); document.getElementById('dados').setAttribute('value', encodeURIComponent(JSON.stringify(data))); formulario = document.getElementById('formulario'); // Line 55! formulario.action = 'php/' + this.id + '.php'; formulario.submit(); return false; } But it doesn't work with Internet Explorer. It returns the following error: Message: The object doesn't support the property or method. Line: 55 Character: 2 Code: 0 URI: http://www.site.com/javascript/scripts.js

    Read the article

  • safely encode and pass a string from a html link to PHP program

    - by bert
    What series of steps would be reqired to safely encode and pass a string from a html href using javascript to construct the link to a php program. in javascript set up URL // encodes a URI component. path = "mypgm.php?from=" + encodeURIComponent(myvar) ; in php: // get passed variables $myvar = isset($_GET['myvar']) ? ($_GET['myvar']) : ''; // decode - (make the string readable) $myvar = (rawurldecode($myvar)); // converts characters to HTML entities (reduce risk of attack) $myvar = htmlentities($myvar); // maybe custom sanitize program as well? // see [http://stackoverflow.com/questions/2668854/php-sanitizing-strings-to-make-them-url-and-filename-safe][1] $myvar = sanitize($myvar);

    Read the article

  • Javascript: Link with Chinese characters in Internet Explorer

    - by Dennis Coretree
    I have a problem with a link containing Chinese characters that is send to a javascript file in Internet Explorer. Generally that link is created by PHP and looks like this in IE: www.example.com/%E6%B7%AC%E7%81%AB%E6%B2%B9_ASIN5034CN.pdf In firefox it looks like this: www.example.com/???_ASIN5034CN.pdf Both work in that direct way. I need to pass that link to a javascript that popups on the page and it will be displayed after the user entered her/his contact information. This also works on firefox and other browsers but in IE that link is transfered to this which does not work anymore: www.example.com/æ·¬ç«æ²¹_ASIN5034CN.pdf I tried to do some encoding on it with encodeURIComponent but still no success. So the link is passed correctly to the javascript but it is totally screwed up only by IE. Thx for any advice on that problem.

    Read the article

  • Php variable in several files including jquery

    - by vipinsahu
    i created two variable and these two variable are using everywhere . i don't want to store these variable in to database e.g ( $username ,$password and there are 3 files using these variable load.php,index.php and add.php , i am also using jquery to load the add.php as in ajax (to add the user in JSON) $.ajax({ type: "POST", url: "add.php", data: "twitter="+encodeURIComponent(twitter), /* Sending the filled in twitter name */ success: function(msg){ /* PHP returns 1 on success, and 0 on error */ var status = parseInt(msg); if(status) { $('#response').html('Thank you '); $('#twitterName').val(''); } else $('#response').html('<span style="color:red">There is no user.</span>'); } }); how can i use these two variable in a single file to perform the whole operation Thanks

    Read the article

  • jQuery.param() - doesn't serialize javascript Date objects?

    - by ehahn9
    jQuery.param({foo: 1}); // => "foo=1" - SUCCESS! jQuery.param({bar: new Date()}); // => "" - OUCH! There is no problem with encodeURIComponent(new Date()), which is what I would have thought param is calling for each member. Also, explicitly using "traditional" param (e.g. jQuery.param(xxx, true)) DOES serialize the date, but alas, that isn't of much help since my data structure isn't flat. Is this because typeof(Date) == "object" and param tries to descend into it to find scalar values? How might one realistically serialize an object that happens to have Date's in it for $.post() etc.?

    Read the article

  • attaching the link of the article in href

    - by Aruna
    hi , i am having the link like <a href="http://twitter.com/home/?status='.$markme_ddesc.'" onclick="OpenPopup(this.href); return false">Click Here to See Popup</a> for bookmarking the article clicked to twitter .. The above one just add the articles message to twitter.. But i am trying to add my article link also to twitter,.. so i am using the location.href but its not working tat is its not showing me the articles site name.. THe below is the one i tried.. <a href="http://twitter.com/home/?status=\'+encodeURIComponent(location.href)+\'-'.$markme_ddesc.'" onclick="OpenPopup(this.href); return false">Click Here to See Popup</a> Thanks i advance.. Help me to get out of this...

    Read the article

  • passing url in parameters mvc4

    - by user516883
    I have a site that collects urls. A full http url is enter into a texbox. I am getting a 400 error when a url is being passed in the parameter, It works fine with regular text. Using jquery how can I pass the full URL in my application. Thanks for any help. MVC Routing Config routes.MapRoute("UploadLinks", "media/upload_links/{link}/{albumID}", new { controller = "Media", action = "WebLinkUpload" }); Controller Action public ActionResult WebLinkUpload(string link, string albumID){} Jquery ajax call $('#btnUploadWebUpload').click(function () { $.ajax({ type: "GET", url: "/media/upload_links/" + encodeURIComponent($('#txtWebUrl').val().trim()) + "/" + currentAlbumID, contentType: "application/json; charset=utf-8", dataType: "json", success: function (result) { } }); });

    Read the article

  • Convert ISO/Windows charsets to UTF-8 in Javascript

    - by Amir
    I'm developing a firefox plugin and i fetch web pages to do some analysis for the user. The problem is when i try to get (XMLHttpRequest) pages that are not utf-8 encoded the string i see is messed up. For example hebrew pages with windows-1125 or Chinese pages with gb2312. I already tried the following: var uDecoder=Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].getService(Components.interfaces.nsIScriptableUnicodeConverter); uDecoder.charset="windows-1255"; alert( xhr.responseText ); var decoder=Components.classes["@mozilla.org/intl/utf8converterservice;1"].getService(Components.interfaces.nsIUTF8ConverterService); alert(decoder.convertStringToUTF8(xhr.responseText,"WINDOWS-1255",true)); I also tried escape/unescape/encodeURIComponent any ideas???

    Read the article

  • Error after passing variable from jquery to code in c#

    - by Moraru Viorel
    I try to pass variable from jquery to code c# but something is wrong. I have in js this code: <script type="text/javascript"> var mySerial = '12345'; var fooUrl = '@Url.Action("Foo", "Home")'; window.location.href = fooUrl + '?mySerial' + encodeURIComponent(mySerial); </script> in controller : [HttpPost] public ActionResult Foo(string mySerial) { return View(); } After execution I keep this url: http://localhost:2214/@Url.Action("Foo",%20"Home")?mySerial12345 and I don't understand where's the problem, can someone help me?

    Read the article

  • Dynamic path in new.AjaxRequest with Rails

    - by Robbie
    Hello, I was wondering if there's anyway to get a 'dynamic path' into a .js file through Ruby on Rails. For example, I have the following: new Ajax.Request('/tokens/destroy/' + GRID_ID, {asynchronous:true, evalScripts:true, onComplete:function(request){load('26', 'table1', request.responseText)}, parameters:'token=' + dsrc.id + '&authenticity_token=' + encodeURIComponent(AUTH_TOKEN)}) The main URL is '/tokens/destroy/:id', however on my production server this app runs as a sub folder. So the URL for this ajax call needs to be '/qrpsdrail/tokens/destroy/:id' The URL this is being called from would be /grids/1 or /qrpsdrail/grids/1 I could, of course, do ../../path -- but that seems a bit hackish. It is also dependent on the routing never changing, which at this stage I can't guarantee. I'm just interested in seeing what other solutions there might be to this problem. Thanks in advance :)

    Read the article

  • link_to_remote in rails, problem pass :id

    - by nakada
    i have problem use link_to_remote link_to_remote document example say link_to_remote "Delete this post", :update => "posts", :url => { :action => "destroy", :id => post.id } this code make below html code <a href="#" onclick="new Ajax.Updater('posts', '/blog/destroy/3', {asynchronous:true, evalScripts:true}); return false;">Delete this post</a> but my app don't. my html is <a href="#" onclick="new Ajax.Updater('posts', '/blog/6', {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + encodeURIComponent('2C4Yo8OIDN+dm9oieL37uRg++PuWa8LCz18gW5Cu+Vg=')}); return false;">Delete this post</a> where is destroy in url? i expected '/blog/destroy/6' but actually 'blog/6' what's the problem? my rails version is 2.3.5

    Read the article

  • Ruby and jQuery -- $(document).ajaxSend() not modifying the params as expected

    - by Jason
    I cannot get jquery's ajaxSend (http://api.jquery.com/ajaxSend/) to properly modify the parameters. I have: $(document).ajaxSend(function(event, request, settings) { settings.data = $.deparam(settings.data); settings.data['random'] = new Date().getTime(); settings.data['_method'] = 'get'; settings.data = $.param(settings.data) $.log(settings); }); $(document).ready(function() { //...snip... $.ajaxSetup({ data : { remote : 1, authenticity_token : encodeURIComponent(AUTH_TOKEN) } }); }); The idea here is that we always want 4 param sent across: remote and auth_token always get set properly. However, random and _method (both needed for IE issues) do not get set. Logging settings inside ajaxSend shows me that they are set to settings.data: "remote=1&authenticity_token=6GA9R_snip_253D&random=1270584905846&_method=get" but when it gets sent across the wire, I only have the following: authenticity_token 6GA9R_snip_253D remote 1 Why in the world is this not working?

    Read the article

  • Ajax request with prototype - what is transport if not only responseText?

    - by Delirium tremens
    This is an example code from the prototype site. var url = '/proxy?url=' + encodeURIComponent('http://www.google.com/search?q=Prototype'); // notice the use of a proxy to circumvent the Same Origin Policy. new Ajax.Request(url, { method: 'get', onSuccess: function(transport) { var notice = $('notice'); if (transport.responseText.match(/href="http:\/\/prototypejs.org/)) notice.update('Yeah! You are in the Top 10!').setStyle({ background: '#dfd' }); else notice.update('Damn! You are beyond #10...').setStyle({ background: '#fdd' }); } }); The data that comes from the ajax request is available at transport.responseText, but what is transport if not only responseText?

    Read the article

  • Ampersand in JSON/PHP in POST

    - by svenkapudija
    I'm having a text field which is send via JSON and jQuery (wrapped with .toJSON function) to my server via AJAX and POST request. On PHP side I'm doing json_decode . Everything works but if I put ampersand (&) inside it splits up the POST parameter so its incomplete on PHP side (at least what var_dump($_POST) is writing out). Shouldn't the toJSON and json_decode do all the job (escaping)? I tried encodeURIComponent, & to &amp;, & to \u0026 and it's not working. What I'm doing wrong? AJAX call function execute() { this.setupUrl(); return $.ajax({ type: this.requestMethod, data: this.getDataParams(), url: this.url }); } function getDataParams() { if(this.data != undefined) { if(this.requestMethod == 'POST' || this.requestMethod == 'PUT') { return "data=" + $.toJSON(this.data); } else if (this.requestMethod == 'GET') { return this.data; } } else { return null; } }

    Read the article

  • How to display values from another website to an new html page?

    - by user3098728
    How to display the value in a new html file from different website? This an example field of values that need to display into new html file and I want to display the said values in the input box (Contract ID) of this page JSFiddle. I have 2 JS code that would display that values, but unfortunately its not working and I dont know how to display that value in html input box. Please help me. Thank you I want to display the said value in this input box: Here the JS file to read the values: function scanLapVerification() { try { var page_title = "Title"; var el = getElement(document, "class", "view-operator-verification-title", ""); if (!el || el.length == 0) return; if (el[0].innerText != page_title) return; var page_title = ''; var el = getElement(document, "class", "workflowActivityDetailPanel", ""); if (el && el.length > 0) { var eltr = getElement(el[0], "tag", "tr", ""); if (eltr && eltr.length > 0) { //Read Contract ID var contractId = { CI: { id: null } }; var con_id = null; for (var i = 0; i < eltr.length; i++) { tr_text = eltr[i].innerText; if (tr_text.substr(0, "Contract ID".length) == "Contract ID") con_id = "CI"; if (con_id && tr_text.substr(0, "Contract ID".length) == "Contract ID") { contractId[con_id].id = tr_text.substr("Contract ID".length + 1, tr_text.length - "Contract ID".length - 1); } } var contract_id = contractId.CI.id; return { content: "cid_check", con_id: con_id }; } return { status: "KO" }; } catch (e) { alert("Exception: scanLapVerification\n" + e.Description); return { status: "KO", message: e }; } }; And here's the 2nd JS that display to a new html page: function scanLapVerification() { chrome.tabs.sendRequest(tabLapVerification, { method: "scanLapVerification" }, function (response) { msgbox("receiveResponse: scanLapVerification " + jsonToString(response, "JSON")); //maintaining state in the background if (response.data.content == "cid_check") { //Popup window features var popupWindow = null; var name; var width = 550; var height = 200; var left = parseInt((screen.availWidth / 2) - (width / 2)); var top = parseInt((screen.availHeight / 2) - (height / 2)); var windowFeatures = "width=" + width + ",height=" + height + ",left=" + left + ",top=" + top + "screenX=" + left + ",screenY=" + top; //Input new address with popup window if (confirm("Does the client has new address?") == true) { popupWindow = window.open('/htmlname.htm', "title", windowFeatures + encodeURIComponent(response.data.contract_id)); popupWindow.focus(); } else { name = ""; } }); }

    Read the article

  • HTML client-side portable file generation - no external resources or server calls

    - by awashburn
    I have the following situation: I have set up a series of Cron jobs on an internal company server to run various PHP scripts designed to check data integrity. Each PHP script queries a company database, formats the returned query data into an HTML file containing one or more <tables>, and then mails the HTML file to several client emails as an attachment. From my experience, most of the PHP scripts generate HTML files with only a few tables, however there are a few PHP scripts the create HTML files with around 30 tables. HTML files have been chosen as the distribution format of these scans because HTML makes it easy to view many tables at once in a browser window. I would like to add the functionality for the clients to download a table in the HTML file as a CSV file. I anticipate clients using this feature when they suspect a data integrity issue based on the table data. It would be ideal for them to be able to take the table in question, export the data out to a CSV file, and then study it further. Because need for exporting the data to CSV format is at the discretion of the client, unpredictable as to what table will be under scrutiny, and intermittently used I do not want to create CSV files for every table. Normally creating a CSV file wouldn't be too difficult, using JavaScript/jQuery to preform DOM traversal and generate the CSV file data into a string utilizing a server call or flash library to facilitate the download process; but I have one limiting constraint: The HTML file needs to be "portable." I would like the clients to be able to take their HTML file and preform analysis of the data outside the company intranet. Also it is likely these HTML files will be archived, so making the export functionality "self contained" in the HTML files is a highly desirable feature for the two previous reasons. The "portable" constraint of CSV file generation from a HTML file means: I cannot make a server call. This means ALL the file generation must be done client-side. I want the single HTML file attached to the email to contain all the resources to generate the CSV file. This means I cannot use jQuery or flash libraries to generate the file. I understand, for obvious security reasons, that writing out files to disk using JavaScript isn't supported by any browser. I don't want to create a file without the user knowledge; I would like to generate the file using JavaScript in memory and then prompt the user the "download" the file from memory. I have looked into generating the CSV file as a URI however, according to my research and testing, this approach has a few problems: URIs for files are not supported by IE (See Here) URIs in FireFox saves the file with a random file name and as a .part file As much as it pains me, I can accept the fact the IE<=v9 won't create a URI for files. I would like to create a semi-cross-browser solution in which Chrome, Firefox, and Safari create a URI to download the CSV file after JavaScript DOM traversal compiles the data. My Example Table: <table> <thead class="resulttitle"> <tr> <th style="text-align:center;" colspan="3"> NameOfTheTable</th> </tr> </thead> <tbody> <tr class="resultheader"> <td>VEN_PK</td> <td>VEN_CompanyName</td> <td>VEN_Order</td> </tr> <tr> <td class='resultfield'>1</td> <td class='resultfield'>Brander Ranch</td> <td class='resultfield'>Beef</td> </tr> <tr> <td class='resultfield'>2</td> <td class='resultfield'>Super Tree Produce</td> <td class='resultfield'>Apples</td> </tr> <tr> <td class='resultfield'>3</td> <td class='resultfield'>John's Distilery</td> <td class='resultfield'>Beer</td> </tr> </tbody> <tfoot> <tr> <td colspan="3" style="text-align:right;"> <button onclick="doSomething(this);">Export to CSV File</button></td> </tr> </tfoot> </table> My Example JavaScript: <script type="text/javascript"> function doSomething(inButton) { /* locate elements */ var table = inButton.parentNode.parentNode.parentNode.parentNode; var name = table.rows[0].cells[0].textContent; var tbody = table.tBodies[0]; /* create CSV String through DOM traversal */ var rows = tbody.rows; var csvStr = ""; for (var i=0; i < rows.length; i++) { for (var j=0; j < rows[i].cells.length; j++) { csvStr += rows[i].cells[j].textContent +","; } csvStr += "\n"; } /* temporary proof DOM traversal was successful */ alert("Table Name:\t" + name + "\nCSV String:\n" + csvStr); /* Create URI Here! * (code I am missing) */ /* Approach 1 : Auto-download * downloads CSV data but: * In FireFox downloads as randomCharacers.part instead of name.csv * In Chrome downloads without prompting the user * In Safari opens the files in browser (textfile) */ //var hrefData = "data:text/csv;charset=US-ASCII," + encodeURIComponent(csvStr); //document.location.href = hrefData; /* Approach 2 : Right-Click Save As... */ var hrefData = "data:text/csv;charset=US-ASCII," + encodeURIComponent(csvStr); var fileLink = document.createElement("a"); fileLink.href = hrefData; fileLink.innerHTML = "download"; parentTD = inButton.parentNode; parentTD.appendChild(fileLink); parentTD.removeChild(inButton); } </script> I am looking for an example solution in which the above example table can be downloaded as a CSV file: using a URI the user is prompted to save the file the default filename is the name of the table. code works as described in modern versions of FireFox, Safari, & Chrome I have added a <script> tag with the DOM traversal function doSomething(). The real help I need is with formatting the URI to what I want within the doSomething() function.

    Read the article

  • jQuery: AJAX umlauts & special characters are a mess

    - by rayne
    I've just created my first ajax function with jQuery which actually works, but unfortunately the character encoding (for characters like ä, ö, ü, ß, c, c, å, ø) is a nightmare. My files and my database are all UTF-8. I've tried a multitude of options in the ajax function and the PHP function, none of which were satisfactory. This is my ajax var dataString = { 'name': name, 'mail': mail // other stuff } $.ajax({ type: "POST", url: "/post.php", data: dataString, contentType: "application/x-www-form-urlencoded;charset=UTF-8", cache: false, success: function(html){ // do stuff } I've tried it without contentType: "application/x-www-form-urlencoded;charset=UTF-8" and I've tried to wrap the affected data in encodeURIComponent(), none of which worked. When I use that AJAX with htmlentities() in my php, my umlauts look like this in plain text: UE Ã?, AE Ã?, OE Ã?, ue ü, ae ä, oe o And like this in the database: UE Ãœ , AE Ä, OE Ö, ue ü, ae ä, oe o If I don't use htmlentities() but mysql_real_escape_string() instead (or neither), they look good in plain text, but they look like this in the database: AE Ä, OE Ö, UE Ãœ, ae ä oe ö ue ü I've been trying tons of options for hours now, but I can't find a solution that works. So far the only option I seem to have is having them look like a total mess in the database, but that would be very contraproductive if those data sets need to be edited.

    Read the article

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