Sunday, March 3, 2019

llamas with hats full script 1-¹²

Paul : Carl, there is a dead human in our house.
Carl : Oh, hey, how did he get here?
Paul : Carrrllll, what did you do?
2) Carl : I don't kill people. That is-that is my least favorite thing to do.
3)
Paul : Tell me, Carl. Exactly what you were doing before I got home.
Carl : Alright, well I was upstairs.
Paul : Okay.
Carl : I was, I was sitting in my room.
Paul : Yes.
Carl : Reading a book.
Paul : Go on.
Carl : And uh, well this guy walked in.
Paul : Okay.
Carl : So I went up to him.
Paul : Yes.
Carl : And I, uh stabbed him 37 times in the chest.
Paul : Carrrlll, that kills people!
Carl : Oh, oh, well I-I-I didn't know that.
Paul : How could you not know that?
Carl : Yeah, I'm in the wrong here. I suck.
4)
Paul : What happened to his hands?
Carl : What's that?
Paul : His hands. Why-Why are they missing?
Carl : Well, I uh, I kind of cooked them up and ate them.
Paul : *silence* Carrl.
5) Carl : Well I uh, I was hungry and, well you know, when you crave hands...
6)
Carl : My stomach was making the rumblies-
Paul : Carl-
Carl : That only HANDS would satisfy.
7)
Paul : What is wrong with you, Carl!?
Carl : Well, I kill people and I eat hands, that's two things.
Llama-Ugh Carl, what on earth was that  Carl- Um, I’m not sure what you’re referring to  Llama-You sunk an entire cruise ship Carl  Carl- are you sure that was me? I would think I would remember something like that  Llama-Carl, I watched you fire a harpoon into the captains face  Carl- That sounds dangerous  Llama-you were head butting children off the side of the ship  Carl-That, that must have been horrifying to watch  Llama-Then you started making out with the ice sculpture  Carl- Well thank god the children weren’t on board to see it  Llama-Aww Carl, why is the lifeboat all red and sticky?  Carl-well I guess you could say it’s all red and sticky  Llama-Carl, what are we standing in?  Carl-would you believe its strawberry milkshake?  Llama-No I would not believe that  Carl-Melted gumdrops  Llama-No  Carl-boat nectar  Llama-No  Carl-some of gods tears  Llama-Tell me the truth Carl  Carl-Fine, it’s the lovely elderly couple from 2B  Llama-Carl!!!!!  Carl- Well they were a, they were taking all the crescent rolls  Llama-I can’t believe what I’m hearing  Carl- I will not apologize for art  Llama-where are the other life boats?  Carl- whoa, you won the prize. I didn’t even notice that  Llama-where are the other life boats Carl?  Carl- Looking at the trajectory of the moon and the sun, probably at the bottom of the ocean. I bit lots of holes in them  Llama-Carl!!!!!!  Carl- I have a problem, I have a serious problem  Llama-You are just terrible today  Carl- shhhh, do you hear that? That’s the sound of forgiveness  Llama-that’s the sound of people drowning Carl  Carl-That is what forgiveness sounds like, screaming and then silence  El Fin!! P:CARL! We're supposed to be on vacation!  C:I Don't know about you, but I am having a wonderful time here.  P:You toppled a south american government, Carl.  C:The people have spoken, VIVA LA RESISTANCE.  P:You pushed the resistance leader into a giant fan.  C:He was a traitor and a scoundrel.  P:He was trying to stop you from pushing other people into a giant fan.  C:Oh, that was a foot. I appear to have swallowed an entire person.  P:That would be the hotel bartender.  C:Well, that explains why my mohito is taking so long.  P:It was horrifying. Your mouth unhinged like a snake.  C:Wow, that sounds pretty awesome.  P:I can't go anywhere with you, carl.  C:That hurt my feelings. Now we're both in the wrong.  P:I wanna go home. We're leaving.  C:In that case, I should probably mention that I filled our luggage with orphan meat.  P:What.  C:Well, I'm building a meat dragon, and not just any meat will do.  P:You know what, forget it. I'm not even shocked anymore.  C:Aw, that's no fun.  P:This has become the norm for you carl.  C:I'll have to try harder next time.  P:Please don't.  C:I feel like I've been issued a challenge.  P:CAARl.  C:It's too late now... You.  P:You?  C:I totally Don't remember your name.  P:We've known eachother for 3 years carl.  C:And what an impression you've made.  P:My name is Paul.  C:What.  P:I said my name is Paul.  C:Oh. I thought you were a woman.  P:Why would you think that?  C:Mostly the Hat. Are you sure?  P:Of course I'm sure.  C:Well, If you'll excuse me, I've got some pictures I need to delete from my computer. 1 Carl, you've tracked mud all over the carpet!  2 Now that right there is a mess...  1 I just had it cleaned yesterday, Carl.  2 I'm not responsible for this - I've been jamming on the saxophone all morning.  1 They're clearly your hoofprints, Carl.  2 Then there is an imposter on the loose! 1 They lead directly to you!  2 Clue number one: The imposter is a phantom.  1 Carl, stop avoid- *BOOM!*  1 CARL!  2 Happy birthday!  1 It's not - please tell me you had nothing to do with this.  2 Why don't you blow out your candle?  1 You've gone too far this time, Carl.  2 What? It's hard to hear you over the sound of melting city.  1 How did you even do this?  2 A dollop of fairy dust.  1 Carl-  2 I ripped the tag off a mattress.  1 This isn't funny.  2 Who's laughing? Clearly not all the people who just exploded.  1 I'm leaving. I've had enough of this.  2 But think of all the perfectly roasted face we'll get to munch on now.  1 What? Why?  2 Because we're friends. And friend ship is two pals munching on a well roasted face together.  1 That isn't friendship, Carl. That's sick.  2 Well, then you're probably not going to like your birthday decoration.  1 It's not even my - Oh my God.  2 Surprise!  1 Oh... oh no. Aww...  2 I'm sorry, I thought you liked faces. Obviously there's a mis communitcation. 1 This is awful, Carl.  2 You're right. It's not nearly as tasteful as I pictured it in my head.  1 I think I'm gonna throw - oh, one just touched me.  2 This was clearly not the way to go.  1 Ya think, Carl?  2 What can I say? I expected them to be cooked more. Raw face is just gross.  1 But that isn't the problem, Carl! Why would you think any of this was a good idea?  2 Probably because I'm a dangerous sociopath with a long history of violence. 1 oh.  2 I don't understand how you keep forgetting that. Paul- Carl! I know you've done something

Carl- Whatever do you mean?

Paul- You've always done something. It's a lovely day out, we're having a good time. What have you done?

Carl- You mistake me for some sort of scoundrel.

Paul- Carl! 

Carl- I am a respected member of the community… to even insinuate__

Paul- Okay Carl, so what did you do today?

Carl- Well let's see, I washed the car.

Paul- Uhuh

Carl- I made a donation to the local girl scout troop

Paul- Sure

Carl- I returned an overdue movie at Blockbuster

Paul- What else?

Carl- Hmmm, I stepped on a ladybug by accident.

Paul- Go on.

Carl- And… I baked some banana bread for our neighbor Pat. I believe that's it. Done.

Paul- That's it…

Carl- That's all I did today… (a crack in space time happens) Ohhhhhh....

Paul- Carl! What is that?

Carl- I may have forgot to mention one of my activities.

Paul- Carl!

Carl- I apologize, that was wrong.

Paul- Explain Carl!

Carl- Well from here it looks like a weather balloon.

Paul- I'm not in the mood for this.

Carl- I think it's just a lens flare and some dust.

Paul- Just tell me Carl.

Carl- Fine, I may have created a crack in space time. Through which to collect millions of baby hands.

Paul- Huh.

Carl- What do you mean huh?

Paul- I think I was expecting worse.

Carl- Worse? But this is totally fugged bro.

Paul- I know but after last time with the nuke and the faces, it's just…

Carl- Come on, look at this. How did I even do this?

Paul- I don't understand how or why you do anything.

Carl- Do you know what it feels like to be Carl right now? It hurts. Not as much as the babies but it hurts.

Paul- Uh, Carl.

Carl- What?

Paul- Why are there only hands from white babies?

Carl- Well, you know, whities gotta pay.

Paul- Ah

Carl- And the payment is baby hands. Carl: aren't you going to say it?

Paul: say what Carl? 

Carl: THAT! My name! All offended and annoyed!

Paul: I'm leaving Carl. 

Carl: What?

Paul: I'm moving out.

Carl: it's the meat conveyor isn't it... You never were a fan of modern home design.

Paul: it's a lot of things Carl!

Carl: just let me explain! (Beat) efficiency, industry, never before has so many dead bodies been so manageable.

Paul: Carl!

Carl: I'm the Henry Ford of human meat.

Paul: I've already packed, I'm not coming back.

Carl: awe, come on! We haven't even gotten to the big surprise yet

Paul: I'm sure it's very upsetting.

Carl: well, now I don't even want to show you...

Paul: good! I don't want to see it

Carl: and your being a huge b hole right now.

Paul: I'm not the one shoving people into a meat grinder!

Carl: it's not a meat grinder, it's an orphan stomper!

Paul: gross!

Carl: do you know what's gross, your attitude.

Paul: are you serious?

Carl: what have I done to deserve all this b hole coming out of your mouth!

Paul: it's everything Carl! It's everything you've done! Ever!

Carl: everything? Even the time I helped Mrs. Bixby with her garden?

Paul: you buried her there!! 

Carl: it's what she would have wanted.

Paul: you buried her alive!

Carl: she wasn't keeping up with the weeding! As president of the homeowners association, I had to take immediate action!

Paul: all you do is kill people Carl!

Carl: that's like saying all Mozart did was write songs.

Paul: you are completely insane!

Carl: oh, weird! That's what all these orphans said!

(Big rumble and the room shakes. A roar is then heard)

Paul: is that the surprise...?

Carl: (angry and holds out words) no...

Paul: that looks like a meat dragon, did you finish your meat dragon, Carl? 

Carl: (holds out words and is still looks away mad) maybe...

Paul: (beats then sighs) it's horrifying Carl...

Carl: (a bit flattered and loosens up) thank you. Sheep: (wearing a Paul mask) mmmmrrraaaaahhh!!!!

Carl: who me?

Sheep: mrah mrah mrah mrah mrah!

Carl: what ever could you be referring to?

Sheep: mrah mrah mrah mrah mrah mrah mrah!

Carl: oh the hand chair. I've recently taken up carpentry.

Sheep: mrah mrah mrah mrah mrah mrah mrah!

Carl: oh, how would you feel if I called YOUR work a  monstrosity.

Sheep: mrah mrah mrah!

Carl: of course I had to use faces! Anything else would be disrespecting the art!

Sheep: mrah mrah raw mrah rawr raw raaaw!!

Carl: it's called modernism, only I've made it more modern by using face parts of city council members!

Sheep: mrrrraaaaah-mrah!

Carl:  I disagree with the election results

Sheep: mrah!!

Carl: someone had to take a stand! I'm patriot, and a hero!

Sheep: mrah mrah mrah mrah mrah!

Carl: fine! If your going to whine about it, I can sew them back on.

Sheep: mrah mrah mrah mrah mrah! 

Carl: I think their bodies are still in the blood canal...

Sheep: mrah mrah mrah mrah mrah!!

Carl: yes, I'm the crazy one, but not the people who elected those buffoons!

Sheep: mrah mrah mrah mrah mraaaaahh!!

Carl: if you paid any attention to our city charter meetings, you would see it wasn't an over reaction.

Sheep: (sits down) mrrraaaah!

Carl: (beats) what are you doing?

Sheep: mraaaah!

Carl: (beat and gets angry) you're sitting...

Sheep: mrah mrah mrah mrah mrah!

Carl: you never sit

Sheep: mrah mrah mrah mrah mrah!

Carl: you're always standing Paul! You're not supposed to sit.

Sheep: (lays down) mrah!

Carl: I find this very upsetting. 

Sheep: mrah mrah mrah raw raw raw!

Carl: you don't even care, do you? About MY feelings!

Sheep: mrah mrah mrah mrah!

Carl: will you please stand up, paul

Sheep: (does a handstand)   mraaah???!

Carl: I don't even know who you are anymore...

Sheep: mrah raw mraw mraw!

Carl: no you cannot take off the mask, it has to look right when throw you into the meat canal. Carl: (has Paul mask around his neck) Paul, you home? Ding dong! (Guy accent) Landlord! (Accent of sloppy teenage boy) pizza delivery! (Hero voice) fire department! (Annoying voice) bank manager! You have an appointment!

Paul: what do you want Carl? 

Carl: I want to be treated like a friend Paul.

Paul: we're not friends anymore!

Carl: didn't you get my apology piano?

Paul: pianos aren't supposed to bleed and scream!!

Carl: I guess it less a piano and more a statement on pianos.

Paul: why don't you go horrify someone else Carl?

Carl: I miss your grumpy face. And the mask I made hasn't worked. It's just not grump enough.

Paul:... You made a mask of my face...? 

Carl: yes and speaking of which, you might want to avoid being seen by federal investigators...

Paul: Carl!!!

Carl: to some you are now known as Nikolai Sponigouph. Leader of the Russian Obion Cardell! 

Paul: Go home Carl, I'm calling the police

Carl: bad idea Nikolai! And you know there isn’t a prison I can’t nibble my way out of.

Paul: I’m dialing.

Carl: oh, come on! I have nowhere to go! I burned my house down once it had enough swans inside! Then I used the rest of my savings buying the swans!

Paul: And whose fault is that?!

Carl: society! Society and the swans!

Paul: (whines) Carl? Please! I gave you every chance I could, I- I just can’t do it anymore!

Carl: what if I got you… ten million dollars cash.

Paul: you don’t have ten million dollars, Carl!

Carl: I buried a large chest of double-loons once. I could go dig that up.

Paul: no, Carl.

Carl: It was either that or my zoobooks. Either way, a lot of something in buried in a hole somewhere.

Paul: I’m putting on music Carl, I can’t listen anymore.

Carl: rude...

Paul Mask: I am sorry, flesh-me is so ungrateful Carl.

Carl: And after all we’ve been through, it’s scandalous I must say.

Paul Mask: You do wonderful things and deserve appreciation.

Carl: It’s okay… he’ll come around. As soon as the swan piano arrives.

Paul: (honking is heard, a crash, and piano keys) CCAAAARRRRRRRLL!!

Carl: you’re welcome! Paul Mask: Caarl, I can't believe you. 

Carl: uh-oh, what I have I done this time? 

Paul Mask: you killed someone and chopped them up and they are right here on the floor, Carl.

Carl: I didn't do that. Why would you- Why would you think I would you did such a thing?! 

Paul Mask: Caaarl!! All the blood and the- the pieces.. Y-You murderer! 

Carl: I-I think I would of remembered uh-uh, dismembering someone and putting all their bits on the ground right here, that is not the sort of thing I would usually forget about.

Paul Mask: CAAARL! I hate chu Carl, I HATE CHU! 

Carl: Oh, watch it, now who is being hurtful, you Paul, YOU. 

Paul Mask: (says in a robotic voice, sounding like the dead Paul) Caaaaaaarrl... 

Carl: Who said that? 

(The Paul mask begins to float off the tree and the pupils of the mask begin to go to a glowing red) It is me, Caaarl. 

Carl: Paul?? 

Paul Mask: Yes, Carl. 

Carl: Y-you came back... 

Paul Mask: You must finish your work, Carl. 

Carl: My work? 

Paul Mask: There is so much to do, we mustn't dawdle... 

Carl: You said you weren't coming back.. 

Paul Mask: Caaaaaarrl.. 

Carl: Yeah? 

Paul Mask: Caaaaaaaarrrll... 

Carl: I don't know what I am suppose to say.. 

Paul Mask: (Says angrily, beginning to yell very loudly) CAAAAAAAAAAARRRL!

Carl: (Angrily says with a bit of a harsh tone, kind of yelling) What?! 

Paul Mask: (says calmly and with now a soft voice) What are you planning, Carl? 

Carl: I am kinda just free styling it these days, taking things as they come. 

Paul Mask: You are better than that Carl, your better... 

Carl: (says with confidence) I am, aren't I? 

Paul Mask: You're Carl..

Carl: I am Carl! 

Paul Mask: Caaaaarl... 

Carl: That's me!

Paul Mask: CAAAAAAARRRRRL!!

Carl: (says with his usual voice) You sure like your yelling..... (Echo of Paul's voice)
CAAAAAARRRLLL.
CAAAAAARRRLLL.
Paul: You need to get out Carl you are in grave danger.
Carl: Where are we?
Paul: I'll find a light Carl.
Carl: Okay...
Carl: Oh it's my gore pit.
Paul: You had a terrible fall Carl.
Carl: I..I think my legs are broken.
Paul: You're in danger you need to get out. 
Carl: How long have I been down here, it feel like a long time.
Paul: Your work isn't finished Carl you have so much more to do.
Carl: I don't know if I can move Paul.
Paul: You must act quickly something is down here with us.
Carl: That's probably the basilisk he won't bother us the stupid thing only eats chipotle!
Paul: It grows closer.
Carl: Are you always this creepy Paul?
Paul: I'll go find some rope.
Carl: And some neosporin too.
Paul: CAARRLL!
Carl: I know it's all laughs with Carl.
(Some strange noises occur in the gore pit)
Carl: Paul...was that you?
Carl: Maybe it's my stomach making the rumblies.
Carl: Hungry for hands remember that Paul?
Carl: Paul?
Paul: CAAAARRRLLL.
Carl: Couldn't find the rope?
Paul: I'm sorry Carl you'll need to do this yourself.
Carl: Well that's a bummer.
Paul: CAAAAAAARRRRRRLLLL.
Carl: That's not gonna work I'm in a too bad of a mood.
Paul: CAAAARRRRRRRRLLL.
Carl: Alright...oh hey how did all these bodies get down here? 
Paul: You killed these people Carl.
Carl: Collecting piles of human is my least favorite thing to do.
Paul: CAAAARRRRLLL.
Carl: I am a rascal just a no good trouble maker and that's me. Paul mask: CAAAAAARRRRLLLL.
Carl: I guess I'm done.
Paul mask: You must complete your work Carl.
Carl: There is nothing left to complete it's all gone.
Paul mask: CAAARL.
Carl: I'm done Paul!
Paul mask: CAARRRRRRL.
Carl: Why are you still yelling at me!?
Paul mask: You must complete your work Carl.
Carl: All the hands are eaten, all the meat creatures are made,unleashes and also eaten.
Paul mask: CAARRRRRRL!!!!!!!
Carl: Yes it was very upsetting.
Paul mask: I can't believe you Carl.
Carl: Do you remember the blood vortex in Paris?
Paul mask: CAARRRRRRL!!!!!!
Carl: Yea...that one was my favorite.
Paul mask: CAARRRRRRL.
Carl: You know what I don't even think your Paul.
Paul mask: Of course I am Carl.
Carl: I think your a liar and a cheat.
Paul: You must finish your work Carl.
Carl: I'm gonna find the real Paul.
Paul mask: CARRRRRRRL!!!!!!
Carl: I don't think he is gonna be very pleased about all this stuff I've done.
Paul mask: It's almost time.
Carl: Remember the orb thing with all the nerves it would shock people beneath their skin?
Paul mask: Yes Carl.
Carl: Paul is going to be really upset to learn that I made that.
Paul mask: Your almost done Carl.
Carl: When I find the real Paul I bet he's going to be the most mad at you.
Paul mask: CAAARRRRL!!!!!
Carl: Identity theft, that's a felony.
Paul mask: CAAARRRL!!!!!
Carl: Yelling also a felony.
Paul mask: CAAAAAAARRRRRRRRLLLLLLL!!!!!!!!
Carl: PAAAAUUULLLL!
Paul mask: (angrily) CAARRRRRRLLLLLLLL!!!!!!
Carl: (angrily) PAUUUULLLLL!!!!!!
Paul mask: (Angrily) CAARRRRLLLL!!!! Carl is seen at Paul's destroyed apartment

Carl: Paaaaul! Paul, are you home? Paaaaaul? 

Paul Mask: I'm right here, Carl. 

Carl: No, you're not. You're not Paul, you're an imposter!

Paul Mask: Caaaaaaaaaarl!

Carl: STOP IT!

Paul Mask: You must finish your work, Carl.

Carl: Paaaaaul! Paaaaaaaaaul!

Paul Mask: You're almost done, Carl.

Carl: I'm coming in, Paul! I'm sorry if this violates your restraining order, but it's important!

Carl is walking in the apartment

Carl: Paaaul? Paaaul?

Carl sees Paul's dead body - nothing but a mere skeleton with a hat.

The mask has gone inactive.

Carl: (Says very sadly) Oh...I-I guess you're gone.

A slideshow begins of the destruction Carl has caused - buildings are destroyed, homes are wrecked, and the blood vortex Carl has mentioned earlier is hovering over the Eiffel Tower.

Carl is at the top of a destroyed bridge, standing at the edge.

Carl begins speaking to himself in both his and Paul's accents while sobbing.

Carl: Caaaaaaaaarl!

Carl: Oh, heeey!

Carl: Caaaaaarl!

Carl: I didn't do that!

Carl: Caaaaaarl! CAAAAAAAARL!

Carl jumps off the bridge and drowns.

Carl's hat starts to float in the water and then very slowly starts to go very deep into the ocean

Saturday, February 2, 2019

lets try again

Javascript Chat Bot Demo
Play sample conversation!
What can I say?
 

#HaatBootz

Javascript Chat Bot Demo
Play sample conversation!
What can I say?
 

Tuesday, January 29, 2019

thank you for the vrarrings

:

Select numbers:
Enter Url:   

30 ¿¿¿ ¿¿¿***

#NaNTrafficExchange

:

Select numbers:
Enter Url:   

30 ¿¿¿ ¿¿¿***

timer?

:

Select numbers:
Enter Url:   

30 ¿¿¿ ¿¿¿***

Monday, January 28, 2019

barback.gif

#wait10seconds
#tsext

==UserScript== // @name Quizlet micromatch bot // @namespace Danielv123 // @version 3.1 // @description Win micromatch in < 100 seconds! // @author You // @match https://quizlet.com/*/micro* // @grant none // ==/UserScript== // this script died when microscatter turned into micromatch, but it still works albeit badly. // edit: Version 2.0 fixed everything and its now able to get sub 0.5 second times! // @grant GM_addStyle // @grant unsafeWindow // ==/UserScript==

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

CookiePad

h – coffeemakr 15 'mm

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
423
down vote
favorite
Send POST data using XMLHttpRequest
javascript ajax post xmlhttprequest
I'd like to send some data using an XMLHttpRequest in JavaScript.

Say I have the following form in HTML:

<form name="inputform" action="somewhere" method="post">
    <input type="hidden" value="person" name="user">
    <input type="hidden" value="password" name="pwd">
    <input type="hidden" value="place" name="organization">
    <input type="hidden" value="key" name="requiredkey">
</form>
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
49
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,212●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

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge, chrome=1"/>
<script>
"use strict";
function submitForm(oFormElement)
{
  var xhr = new XMLHttpRequest();
  xhr.onload = function(){ alert (xhr.responseText); } // success case
  xhr.onerror = function(){ alert (xhr.responseText); } // failure case
  xhr.open (oFormElement.method, oFormElement.action, true);
  xhr.send (new FormData (oFormElement));
  return false;
}
</script>
</head>

<body>
<form method="post" action="somewhere" onsubmit="return submitForm(this);">
  <input type="hidden" value="person"   name="user" />
  <input type="hidden" value="password" name="pwd" />
  <input type="hidden" value="place"    name="organization" />
  <input type="hidden" value="key"      name="requiredkey" />
  <input type="submit" value="post request"/>
</form>
</body>
</html>
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
<input id="loginEmail" type="text" name="email" placeholder="Email">
<input id="loginPassword" type="password" name="password" placeholder="Password">

// return stops normal action and runs login()
<button onclick="return login()">Submit</button>

<script>
    function login() {
        // Form fields, see IDs above
        const params = {
            email: document.querySelector('#loginEmail').value,
            password: document.querySelector('#loginPassword').value
        }

        const http = new XMLHttpRequest()
        http.open('POST', '/login')
        http.setRequestHeader('Content-type', 'application/json')
        http.send(JSON.stringify(params)) // Make sure to stringify
        http.onload = function() {
            // Do whatever with response
            alert(http.responseText)
        }
    }
</script>
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,619●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+'&amp;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