Sunday, January 27, 2019

#getjscookie

Stack Overflow sign up log in By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Questions Jobs Tags Users Badges Ask up vote 227 down vote favorite How do I create and read a value from cookie? javascript cookies How do I create and read a value from cookie in JavaScript? share improve this question asked Jan 28 '11 at 6:58 Venkatesh Appala 1,862●2●15●12 edited Dec 25 '12 at 12:36 Blachshma 14.8k●4●40●60 15 Quirks mode has a good guide to JavaScript and cookies. – Quentin Jan 28 '11 at 7:00 FWIW, js-cookie provides a very good API for handling it. – Fagner Brack Jun 13 '15 at 2:23 You can check this guide on JavaScript Cookie. – Shubham Kumar Jul 4 '16 at 11:57 Don't forget that the Web Storage API, could be a good alternative to cookies in some situations. – MattBianco Aug 3 '17 at 9:03 add a comment 16 Answers order by up vote 210 down vote accepted Here are functions you can use for creating and retrieving cookies. var createCookie = function(name, value, days) { var expires; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toGMTString(); } else { expires = ""; } document.cookie = name + "=" + value + expires + "; path=/"; } function getCookie(c_name) { if (document.cookie.length > 0) { c_start = document.cookie.indexOf(c_name + "="); if (c_start != -1) { c_start = c_start + c_name.length + 1; c_end = document.cookie.indexOf(";", c_start); if (c_end == -1) { c_end = document.cookie.length; } return unescape(document.cookie.substring(c_start, c_end)); } } return ""; } share improve this answer answered Jan 28 '11 at 6:59 Srinivas Sabbani edited Feb 1 '14 at 5:35 Kevin Burke 20k●44●129●236 20 This doesn't work if your cookie value contains anything that doesn't encode/decode well. The one at w3schools seems to work beautifly – Richard Rout May 20 '13 at 2:07 13 This simple wrapper from Mozilla has explicit unicode support mentioned as well – Brad Parks May 13 '14 at 11:40 4 @BradParks Too bad it's released on GPL. – jahu Aug 2 '14 at 22:09 1 This will not work on IE8 or 9 if the cookie does not have a value, because IE does not add the equal sign (=) after the cookie name. What we do is to check if indexOf("=")==-1, and if so use the entire cookie as the cookie name. – Mohoch Nov 26 '14 at 9:46 1 If you need ES6 version of this, scroll down for answer stackoverflow.com/a/36763672/1737158 – Lukas Apr 21 '16 at 8:17 show 6 more comments up vote 39 down vote JQuery Cookies or plain Javascript: function setCookie(c_name,value,exdays) { var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? "" : ("; expires="+exdate.toUTCString())); document.cookie=c_name + "=" + c_value; } function getCookie(c_name) { var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0; i { const expires = new Date(Date.now() + days * 864e5).toUTCString() document.cookie = name + '=' + encodeURIComponent(value) + '; expires=' + expires + '; path=' + path } const getCookie = (name) => { return document.cookie.split('; ').reduce((r, v) => { const parts = v.split('=') return parts[0] === name ? decodeURIComponent(parts[1]) : r }, '') } const deleteCookie = (name, path) => { setCookie(name, '', -1, path) } share improve this answer answered Aug 1 '16 at 12:42 artnikpro 2,539●1●25●27 edited Apr 23 '18 at 12:54 2 toGMTString() is deprecated, use toUTCString() instead. – Nguyen Thanh Jun 14 '17 at 8:38 @NguyenThanh Thx! Updated – artnikpro Sep 15 '17 at 18:05 Sometimes cookie value itself may contain = sign. In that case function getCookie will produce unexpected result. To avoid that consider using following arrow function body inside reduce const [n, ...val] = v.split('=') return n === name ? decodeURIComponent(val.join('=')) : r – Dmitriy Zhura Mar 7 '18 at 16:29 Would be nice to have an option to leave the expiry date unset though. This would allow the cookie to be automatically deleted upon browser exit. – xji Oct 23 '18 at 14:55 1 864e5 = 86400000 = 1000*60*60*24 represents the number of milliseconds in a 24 hour day. – Henrikh Kantuni Dec 2 '18 at 20:41 show 1 more comment up vote 14 down vote Mozilla provides a simple framework for reading and writing cookies with full unicode support along with examples of how to use it. Once included on the page, you can set a cookie: docCookies.setItem(name, value); read a cookie: docCookies.getItem(name); or delete a cookie: docCookies.removeItem(name); For example: // sets a cookie called 'myCookie' with value 'Chocolate Chip' docCookies.setItem('myCookie', 'Chocolate Chip'); // reads the value of a cookie called 'myCookie' and assigns to variable var myCookie = docCookies.getItem('myCookie'); // removes the cookie called 'myCookie' docCookies.removeItem('myCookie'); See more examples and details on Mozilla's document.cookie page. share improve this answer answered May 29 '14 at 23:54 Brendan Nee 2,483●1●23●28 edited Nov 20 '15 at 16:18 theUtherSide 1,666●1●18●27 2 Please note that the cookie library provided on MDN is released under the GPL, not LGPL. – cpburnz Apr 6 '15 at 17:11 What javascript file do I need to import? Couldn't find it :( – AlikElzin-kilaka Aug 19 '15 at 19:29 See the section under "Library" on this page: developer.mozilla.org/en-US/docs/Web/API/document/… - you can save it to a file and include it or paste it into an existing js file where you'd like to use it. – Brendan Nee Aug 21 '15 at 6:24 So no standalone javascript file? So it's a code snippet - not an actual library. – AlikElzin-kilaka Aug 21 '15 at 6:48 add a comment up vote 6 down vote I've used accepted answer of this thread many times already. It's great piece of code: Simple and usable. But I usually use babel and ES6 and modules, so if you are like me, here is code to copy for faster developing with ES6 Accepted answer rewritten as module with ES6: export const createCookie = ({name, value, days}) => { let expires; if (days) { let date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = '; expires=' + date.toGMTString(); } else { expires = ''; } document.cookie = name + '=' + value + expires + '; path=/'; }; export const getCookie = ({name}) => { if (document.cookie.length > 0) { let c_start = document.cookie.indexOf(name + '='); if (c_start !== -1) { c_start = c_start + name.length + 1; let c_end = document.cookie.indexOf(';', c_start); if (c_end === -1) { c_end = document.cookie.length; } return unescape(document.cookie.substring(c_start, c_end)); } } return ''; }; And after this you can simply import it as any module (path of course may vary): import {createCookie, getCookie} from './../helpers/Cookie'; share improve this answer answered Apr 21 '16 at 8:14 Lukas 9,863●3●63●67 edited May 23 '17 at 12:18 Community♦ 1●1 up vote 6 down vote For those who need save objects like {foo: 'bar'}, I share my edited version of @KevinBurke's answer. I've added JSON.stringify and JSON.parse, that's all. cookie = { set: function (name, value, days) { if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = "; expires=" + date.toGMTString(); } else var expires = ""; document.cookie = name + "=" + JSON.stringify(value) + expires + "; path=/"; }, get : function(name){ var nameEQ = name + "=", ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return JSON.parse(c.substring(nameEQ.length,c.length)); } return null; } } So, now you can do things like this: cookie.set('cookie_key', {foo: 'bar'}, 30); cookie.get('cookie_key'); // {foo: 'bar'} cookie.set('cookie_key', 'baz', 30); cookie.get('cookie_key'); // 'baz' share improve this answer answered Sep 26 '16 at 17:49 Angel 502●7●13 up vote 4 down vote Here's a code to Get, Set and Delete Cookie in JavaScript. function getCookie(name) { name = name + "="; var cookies = document.cookie.split(';'); for(var i = 0; i { let c = document.cookie.match(`(?:(?:^|.*; *)${name} *= *([^;]*).*$)|^.*$`)[1] if (c) return decodeURIComponent(c) } , set: (name, value, opts = {}) => { if (opts.days) { opts['max-age'] = opts.days * 60 * 60 * 24; delete opts.days } opts = Object.entries(opts).reduce((str, [k, v]) => `${str}; ${k}=${v}`, '') document.cookie = name + '=' + encodeURIComponent(value) + opts } , delete: (name, opts) => Cookie.set(name, '', {'max-age': -1, ...opts}) // path & domain must match cookie being deleted } Cookie.set('user', 'Jim', {path: '/', days: 10}) // Set the path to top level (instead of page) and expiration to 10 days (instead of session) Usage - Cookie.get(name, value [, options]): options supports all standard cookie options and adds "days": path: '/' - any absolute path. Default: current document location, domain: 'sub.example.com' - may not start with dot. Default: current host without subdomain. secure: true - Only serve cookie over https. Default: false. days: 2 - days till cookie expires. Default: End of session. Alternative ways of setting expiration: expires: 'Sun, 18 Feb 2018 16:23:42 GMT' - date of expiry as a GMT string. Current date can be gotten with: new Date(Date.now()).toUTCString() 'max-age': 30 - same as days, but in seconds instead of days. Other answers use "expires" instead of "max-age" to support older IE versions. This method requires ES7, so IE7 is out anyways (this is not a big deal). Note: Funny characters such as "=" and "{:}" are supported as cookie values, and the regex handles leading and trailing whitespace (from other libs). If you would like to store objects, either encode them before and after with and JSON.stringify and JSON.parse, edit the above, or add another method. Eg: Cookie.getJSON = name => JSON.parse(Cookie.get(name)) Cookie.setJSON = (name, value, opts) => Cookie.set(name, JSON.stringify(value), opts); share improve this answer answered Feb 9 '18 at 13:21 SamGoody 8,596●8●57●74 edited Nov 30 '18 at 12:13 Would the downvoters kindly explain what's wrong with my method? – SamGoody Nov 18 '18 at 9:50 looks good, what is better about this then other answers ? – Andrew Nov 29 '18 at 19:12 1. Shorter, and IMO easier to maintain. 2. More complete (is the only answer to accept secure, any order of arguments, max-age). 3. More standard defaults (path etc defaults to the standard, unlike most answers here). 4. Best practice (according to MDN, the regex is the most reliable way to extract the values). 5. Futureprook (if more options are added to cookies, they will be maintained). 6. One object pollutes the code less than a bunch of functions. 7. Get, set and delete and easy to add more methods. 8. ES7 (yummy buzzwords). – SamGoody Nov 29 '18 at 21:40 add a comment up vote 2 down vote I use this object. Values are encoded, so it's necessary to consider it when reading or writing from server side. cookie = (function() { /** * Sets a cookie value. seconds parameter is optional */ var set = function(name, value, seconds) { var expires = seconds ? '; expires=' + new Date(new Date().getTime() + seconds * 1000).toGMTString() : ''; document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/'; }; var map = function() { var map = {}; var kvs = document.cookie.split('; '); for (var i = 0; i < kvs.length; i++) { var kv = kvs[i].split('='); map[kv[0]] = decodeURIComponent(kv[1]); } return map; }; var get = function(name) { return map()[name]; }; var remove = function(name) { set(name, '', -1); }; return { set: set, get: get, remove: remove, map: map }; })(); share improve this answer answered Nov 4 '15 at 10:00 sinuhepop 13.2k●13●57●92 up vote 0 down vote Simple way to read cookies in ES6. function getCookies() { var cookies = {}; for (let cookie of document.cookie.split('; ')) { let [name, value] = cookie.split("="); cookies[name] = decodeURIComponent(value); } console.dir(cookies); } share improve this answer answered Mar 14 '17 at 8:22 naamadheya 451●3●7●18 up vote 0 down vote I've used js-cookie to success. share improve this answer answered Sep 13 '17 at 21:09 Greg 3,903●1●17●30 up vote -1 down vote An improved version of the readCookie: function readCookie( name ) { var cookieParts = document.cookie.split( ';' ) , i = 0 , part , part_data , value ; while( part = cookieParts[ i++ ] ) { part_data = part.split( '=' ); if ( part_data.shift().replace(/\s/, '' ) === name ) { value = part_data.shift(); break; } } return value; } This should break as soon as you have found your cookie value and return its value. In my opinion very elegant with the double split. The replace on the if-condition is a white space trim, to make sure it matches correctly share improve this answer answered Mar 4 '15 at 7:21 Mattijs 1,802●3●20●26 edited Mar 4 '15 at 9:16 up vote -1 down vote function setCookie(cname,cvalue,exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires=" + d.toGMTString(); document.cookie = cname+"="+cvalue+"; "+expires; } function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i=0; i How can I write the equivalent using an XMLHttpRequest in JavaScript? share improve this question asked Mar 15 '12 at 2:09 Jack Greenhill 3,989●10●33●61 edited Sep 12 '16 at 13:56 T.Todua 30.2k●12●132●131 8 Answers order by up vote 602 down vote accepted The code below demonstrates on how to do this. var http = new XMLHttpRequest(); var url = 'get_data.php'; var params = 'orem=ipsum&name=binny'; http.open('POST', url, true); //Send the proper header information along with the request http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); http.onreadystatechange = function() {//Call a function when the state changes. if(http.readyState == 4 && http.status == 200) { alert(http.responseText); } } http.send(params); share improve this answer answered Mar 15 '12 at 2:12 Ed Heal 47.8k●13●65●105 edited May 25 '18 at 6:34 36 Is it possible to send an object in params instead of a string like in jQuery? – Vadorequest Sep 7 '14 at 11:27 4 No, but @Vadorequest's comment mentioned jQuery - he asked if it were possible to pass data "like jQuery". I mentioned how I think jQuery does it and thus, how you could achieve this. – Dan Pantry Apr 16 '15 at 14:33 10 @EdHeal, Connection and Content-Length headers cannot be set. It'll say "Refused to set unsafe header "content-length"" . See stackoverflow.com/a/2624167/632951 – Pacerier Jun 27 '15 at 10:55 50 Note: setRequestHeader() after open(). Took me an hour, let's hope this comment saves someone an hour ;) – Kevin Sep 26 '16 at 8:30 4 is it possible to send an application/json request? – Dev Dec 6 '16 at 3:03 show 9 more comments up vote 221 down vote var xhr = new XMLHttpRequest(); xhr.open('POST', 'somewhere', true); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.onload = function () { // do something to response console.log(this.responseText); }; xhr.send('user=person&pwd=password&organization=place&requiredkey=key'); Or if you can count on browser support you could use FormData: var data = new FormData(); data.append('user', 'person'); data.append('pwd', 'password'); data.append('organization', 'place'); data.append('requiredkey', 'key'); var xhr = new XMLHttpRequest(); xhr.open('POST', 'somewhere', true); xhr.onload = function () { // do something to response console.log(this.responseText); }; xhr.send(data); share improve this answer answered Mar 9 '13 at 16:21 uKolka 16.1k●4●25●40 edited Jun 24 '13 at 13:43 1 FormData takes the form element as its constructor argument, no need to add values indivually – Juan Mendes Jun 22 '13 at 5:51 4 Yes, but question was to write JavaScript equivalent of provided form not submit the form using JavaScript. – uKolka Jun 22 '13 at 17:07 3 The answer that has few votes but got marked correct uses two extra headers: http.setRequestHeader("Content-length", params.length); and http.setRequestHeader("Connection", "close");. Are they needed? Are they perhaps only needed on certain browsers? (There is a comment on that other page saying setting the Content-Length header was "exactly what was needed") – Darren Cook Oct 17 '13 at 0:19 @Darren Cook Implementation dependent. From my experience major browsers set 'Content-length' (it is required) automatically from the data you supply. 'Connection' header defaults to 'keep-alive' in most cases, which keeps connection open for a while so subsequent requests don't have to reestablish connection again as in case of 'close'. You can try those snippets in the console, using current page URL and inspect request headers using browser's tools or wireshark. – uKolka Oct 18 '13 at 0:46 2 @uKolka it should be noted on the reply than with your second solution the request Content-Type changes automatically to multipart/form-data. This has serious implications on the server side and how the information is accessed there. – AxeEffect Jul 10 '17 at 9:29 show 2 more comments up vote 38 down vote Use modern JavaScript! I'd suggest looking into fetch. It is the ES5 equivalent and uses Promises. It is much more readable and easily customizable. const url = "http://example.com"; fetch(url, { method : "POST", body: new FormData(document.getElementById("inputform")), // -- or -- // body : JSON.stringify({ // user : document.getElementById('user').value, // ... // }) }).then( response => response.text() // .json(), etc. // same as function(response) {return response.text();} ).then( html => console.log(html) ); More Info: Mozilla Documentation Can I Use (88% Mar 2018) Matt Walsh Tutorial share improve this answer answered Aug 6 '17 at 7:14 Gibolt 5,242●2●47●40 edited Apr 21 '18 at 23:35 1 You should avoid using Promises and fat arrows for things this critical to webpage functionality, as many devices do not have browsers that support these features. – Dmitry Sep 2 '17 at 13:30 5 Promises are 90% covered. I added function() examples in case you don't prefer =>. You should absolutely be using modern JS to ease the developer experience. Worrying about a small percentage of people stuck on IE isn't worth it unless you are a huge enterprise – Gibolt Sep 2 '17 at 20:06 4 Fat arrow also doesn't work with this keyword. I like to mention that, but I also secretly hate people that use this, and inheritance architecture instead of function factories. Forgive me, I am node. – agm1984 Sep 8 '17 at 9:17 2 I avoid this like the plague as well, and so should anyone reading this. – Gibolt Oct 20 '17 at 17:28 1 If worried about compatibility...Google es6 transpiler... stackoverflow.com/questions/40205547/…. Write it simple. Deploy it compatible. +1 avoid this. – TamusJRoyce Dec 27 '17 at 17:25 show 2 more comments up vote 31 down vote Minimal use of FormData to submit an AJAX request
Remarks This does not fully answer the OP question because it requires the user to click in order to submit the request. But this may be useful to people searching for this kind of simple solution. This example is very simple and does not support the GET method. If you are interesting by more sophisticated examples, please have a look at the excellent MDN documentation. See also similar answer about XMLHttpRequest to Post HTML Form. Limitation of this solution: As pointed out by Justin Blank and Thomas Munk (see their comments), FormData is not supported by IE9 and lower, and default browser on Android 2.3. share improve this answer answered Nov 7 '13 at 14:17 olibre 26.7k●16●113●150 edited Jan 5 '18 at 5:54 rogerdpack 34k●15●129●252 1 The only thing about this is that I think FormData is not available in IE 9, so it's not going to be usable for a lot of people without a polyfill. developer.mozilla.org/en-US/docs/Web/API/FormData – Justin Blank Jul 9 '14 at 14:19 1 Correct with IE9: caniuse.com/#search=FormData – Thomas Munk Oct 23 '14 at 19:08 2 Elegant solution, but you should specify onsubmit="return submitForm(this);" otherwise the user gets redirected to the URL in the request. – Vic Feb 9 '15 at 13:28 1 I'm not that experienced with web-development. I've figured out that the POST request is indeed sent when you return false. If true is returned, the original (unwanted) POST request will be send! Your answer is correct, sorry for the confusion. – Markus L Jun 21 '17 at 7:06 1 works somewhat in IE11 apparently, FWIW... – rogerdpack Jan 5 '18 at 5:57 show 4 more comments up vote 22 down vote NO PLUGINS NEEDED! Just drag any link (i.e. THIS LINK) in BOOKMARK BAR (if you dont see it, enable from Browser Settings), then EDIT that link : enter image description here and insert javascript code: javascript:var my_params = prompt("Enter your parameters", "var1=aaaa&var2=bbbbb"); var Target_LINK = prompt("Enter destination", location.href); function post(path, params) { var xForm = document.createElement("form"); xForm.setAttribute("method", "post"); xForm.setAttribute("action", path); for (var key in params) { if (params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); xForm.appendChild(hiddenField); } } var xhr = new XMLHttpRequest(); xhr.onload = function () { alert(xhr.responseText); }; xhr.open(xForm.method, xForm.action, true); xhr.send(new FormData(xForm)); return false; } parsed_params = {}; my_params.split("&").forEach(function (item) { var s = item.split("="), k = s[0], v = s[1]; parsed_params[k] = v; }); post(Target_LINK, parsed_params); void(0); That's all! Now you can visit any website, and click that button in BOOKMARK BAR! NOTE: The above method sends data using XMLHttpRequest method, so, you have to be on the same domain while triggering the script. That's why I prefer sending data with a simulated FORM SUBMITTING, which can send the code to any domain - here is code for that: javascript:var my_params=prompt("Enter your parameters","var1=aaaa&var2=bbbbb"); var Target_LINK=prompt("Enter destination", location.href); function post(path, params) { var xForm= document.createElement("form"); xForm.setAttribute("method", "post"); xForm.setAttribute("action", path); xForm.setAttribute("target", "_blank"); for(var key in params) { if(params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); xForm.appendChild(hiddenField); } } document.body.appendChild(xForm); xForm.submit(); } parsed_params={}; my_params.split("&").forEach(function(item) {var s = item.split("="), k=s[0], v=s[1]; parsed_params[k] = v;}); post(Target_LINK, parsed_params); void(0); share improve this answer answered Jul 28 '16 at 17:35 T.Todua 30.2k●12●132●131 edited Nov 18 '17 at 8:28 For Mozilla, Can I do something similar to this? – user6538026 Jul 29 '16 at 5:46 I didn't and I couldn't :| I don't have 125 reps :| And if you see my profile you will see I have 136 up votes :| Even after I get the permission to downvote, I will avoid it unless it is neccessary :| – user6538026 Jul 29 '16 at 9:20 15 And your question really doesn't answer what OP has asked for. BookMarking a HTTP Request... !? I don't see any point relating XmlHttpRequest in your answer :| – user6538026 Jul 29 '16 at 9:27 @Iceman i wont start arguing with you about the profitability of my answer. however, i have updated my answer, and now there is what you wanted. – T.Todua Aug 19 '16 at 11:01 2 awesome. just wanted some relation while reviewing since it was an answer . now it is an answer plus a gr8 tip for all who drop by. i've reverted votes. cheers – Iceman Aug 19 '16 at 11:06 add a comment up vote 19 down vote Here is a complete solution with application-json: // Input values will be grabbed by ID // return stops normal action and runs login() Ensure that your Backend API can parse JSON. For example, in Express JS: import bodyParser from 'body-parser' app.use(bodyParser.json()) share improve this answer answered Sep 8 '17 at 9:11 agm1984 3,629●1●17●35 edited Apr 17 '18 at 19:10 1 Great, but don't use 'false' value for the async parameter in XMLHttpRequest.open - it's deprecated and will give a warning – johnnycardy Mar 23 '18 at 15:29 Should we put true there or just omit that parameter? I will update the answer if you can specify which is preferable. – agm1984 Apr 16 '18 at 19:56 1 It should default to true but I don't know if all browsers respect that – johnnycardy Apr 17 '18 at 8:58 Given the default of true, I am going to remove it from the example and drop this URL for research: developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open – agm1984 Apr 17 '18 at 19:09 I like that better because it's reasonable and one less detail for someone to start with. Thanks for highlighting it. – agm1984 Apr 17 '18 at 19:11 add a comment up vote 4 down vote I have faced similar problem, using the same post and and this link I have resolved my issue. var http = new XMLHttpRequest(); var url = "MY_URL.Com/login.aspx"; var params = 'eid=' +userEmailId+'&pwd='+userPwd http.open("POST", url, true); // Send the proper header information along with the request //http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //http.setRequestHeader("Content-Length", params.length);// all browser wont support Refused to set unsafe header "Content-Length" //http.setRequestHeader("Connection", "close");//Refused to set unsafe header "Connection" // Call a function when the state http.onreadystatechange = function() { if(http.readyState == 4 && http.status == 200) { alert(http.responseText); } } http.send(params); This link has completed information. share improve this answer answered Sep 26 '16 at 13:12 Laxman G 1,340●2●19●36 edited Feb 23 '18 at 10:39 up vote 2 down vote var util = { getAttribute: function (dom, attr) { if (dom.getAttribute !== undefined) { return dom.getAttribute(attr); } else if (dom[attr] !== undefined) { return dom[attr]; } else { return null; } }, addEvent: function (obj, evtName, func) { //Primero revisar attributos si existe o no. if (obj.addEventListener) { obj.addEventListener(evtName, func, false); } else if (obj.attachEvent) { obj.attachEvent(evtName, func); } else { if (this.getAttribute("on" + evtName) !== undefined) { obj["on" + evtName] = func; } else { obj[evtName] = func; } } }, removeEvent: function (obj, evtName, func) { if (obj.removeEventListener) { obj.removeEventListener(evtName, func, false); } else if (obj.detachEvent) { obj.detachEvent(evtName, func); } else { if (this.getAttribute("on" + evtName) !== undefined) { obj["on" + evtName] = null; } else { obj[evtName] = null; } } }, getAjaxObject: function () { var xhttp = null; //XDomainRequest if ("XMLHttpRequest" in window) { xhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } return xhttp; } }; //START CODE HERE. var xhr = util.getAjaxObject(); var isUpload = (xhr && ('upload' in xhr) && ('onprogress' in xhr.upload)); if (isUpload) { util.addEvent(xhr, "progress", xhrEvt.onProgress()); util.addEvent(xhr, "loadstart", xhrEvt.onLoadStart); util.addEvent(xhr, "abort", xhrEvt.onAbort); } util.addEvent(xhr, "readystatechange", xhrEvt.ajaxOnReadyState); var xhrEvt = { onProgress: function (e) { if (e.lengthComputable) { //Loaded bytes. var cLoaded = e.loaded; } }, onLoadStart: function () { }, onAbort: function () { }, onReadyState: function () { var state = xhr.readyState; var httpStatus = xhr.status; if (state === 4 && httpStatus === 200) { //Completed success. var data = xhr.responseText; } } }; //CONTINUE YOUR CODE HERE. xhr.open('POST', 'mypage.php', true); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); if ('FormData' in window) { var formData = new FormData(); formData.append("user", "aaaaa"); formData.append("pass", "bbbbb"); xhr.send(formData); } else { xhr.send("?user=aaaaa&pass=bbbbb"); } share improve this answer answered Jul 2 '16 at 1:57 toto 603●2●7●22 edited Dec 8 '16 at 16:46 1 Could you explain this code a bit ? – Hugo Nava Kopp Dec 8 '16 at 15:38 1 Hello Hugo, This code is to send data or file with progress upload if browser support it. included all possible events and compatibility browser. It try use the most new object class from browser. It help you? – toto Dec 8 '16 at 17:24 add a comment meta chat tour help blog privacy policy legal contact us full site Download the Stack Exchange Android app 2019 Stack Exchange, Inc

No comments:

Post a Comment