Most votes on ajax questions 3

Most votes on ajax questions 3. #21 In MVC, how do I return a string result? #22 Are the PUT, DELETE, HEAD, etc methods available in most web browsers? #23 How do I send a cross-domain POST request via JavaScript? #24 Sending multipart/formdata with jQuery.ajax #25 Send POST data using XMLHttpRequest #26 On - window.location.hash - Change? #27 Response to preflight request doesn't pass access control check #28 How can I post data as form data instead of a request payload? #29 How to send FormData objects with Ajax-requests in jQuery? #30 jQuery get textarea text

Read all the top votes questions and answers in a single page.

#21: In MVC, how do I return a string result? (Score: 664)

Created: 2009-02-16 Last updated: 2016-10-03

Tags:, ajax, actionresult

In my AJAX call, I want to return a string value back to the calling page.

Should I use ActionResult or just return a string?

#21 Best answer 1 of In MVC, how do I return a string result? (Score: 1125)

Created: 2009-02-16 Last updated: 2016-03-29

You can just use the ContentResult to return a plain string:

public ActionResult Temp() {
    return Content("Hi there!");

ContentResult by default returns a text/plain as its contentType. This is overloadable so you can also do:

return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");

#21 Best answer 2 of In MVC, how do I return a string result?(Score: 113)

Created: 2009-02-16

You can also just return string if you know that’s the only thing the method will ever return. For example:

public string MyActionName() {
  return "Hi there!";

See also original question in stackoverflow

#22: Are the PUT, DELETE, HEAD, etc methods available in most web browsers? (Score: 621)

Created: 2008-10-03 Last updated: 2017-05-23

Tags: http, cross-browser, browser, ajax

I’ve seen a couple questions around here like How to debug RESTful services, which mentions:

Unfortunately that same browser won’t allow me to test HTTP PUT, DELETE, and to a certain degree even HTTP POST.

I’ve also heard that browsers support only GET and POST, from some other sources like:

However, a few quick tests in Firefox show that sending PUT and DELETE requests works as expected – the XMLHttpRequest completes successfully, and the request shows up in the server logs with the right method. Is there some aspect to this I’m missing, such as cross-browser compatibility or non-obvious limitations?

#22 Best answer 1 of Are the PUT, DELETE, HEAD, etc methods available in most web browsers? (Score: 467)

Created: 2008-10-03 Last updated: 2019-03-26

No. The HTML 5 spec mentions:

The method and formmethod content attributes are enumerated attributes with the following keywords and states:

The keyword get, mapping to the state GET, indicating the HTTP GET method. The GET method should only request and retrieve data and should have no other effect.

The keyword post, mapping to the state POST, indicating the HTTP POST method. The POST method requests that the server accept the submitted form’s data to be processed, which may result in an item being added to a database, the creation of a new web page resource, the updating of the existing page, or all of the mentioned outcomes.

The keyword dialog, mapping to the state dialog, indicating that submitting the form is intended to close the dialog box in which the form finds itself, if any, and otherwise not submit.

The invalid value default for these attributes is the GET state

I.e. HTML forms only support GET and POST as HTTP request methods. A workaround for this is to tunnel other methods through POST by using a hidden form field which is read by the server and the request dispatched accordingly.

However, GET, POST, PUT and DELETE are supported by the implementations of XMLHttpRequest (i.e. AJAX calls) in all the major web browsers (IE, Firefox, Safari, Chrome, Opera).

#22 Best answer 2 of Are the PUT, DELETE, HEAD, etc methods available in most web browsers?(Score: 81)

Created: 2008-10-05 Last updated: 2021-03-06

HTML forms support GET and POST. (HTML5 at one point added PUT/DELETE, but those were dropped.)

XMLHttpRequest supports every method, including CHICKEN, though some method names are matched against case-insensitively (methods are case-sensitive per HTTP) and some method names are not supported at all for security reasons (e.g. CONNECT).

Fetch API also supports any method except for CONNECT, TRACE, and TRACK, which are forbidden for security reasons.

Browsers are slowly converging on the rules specified by XMLHttpRequest, but as the other comment pointed out there are still some differences.

See also original question in stackoverflow

#23: How do I send a cross-domain POST request via JavaScript? (Score: 594)

Created: 2008-11-18 Last updated: 2018-11-29

Tags: javascript, ajax, cross-domain

How do I send a cross-domain POST request via JavaScript?

Notes - it shouldn’t refresh the page, and I need to grab and parse the response afterwards.

#23 Best answer 1 of How do I send a cross-domain POST request via JavaScript? (Score: 394)

Created: 2011-09-30 Last updated: 2013-07-16

Update: Before continuing everyone should read and understand the html5rocks tutorial on CORS. It is easy to understand and very clear.

If you control the server being POSTed, simply leverage the “Cross-Origin Resource Sharing standard” by setting response headers on the server. This answer is discussed in other answers in this thread, but not very clearly in my opinion.

In short here is how you accomplish the cross domain POST from to (using PHP as an example). Note: you only need to set Access-Control-Allow-Origin for NON OPTIONS requests - this example always sets all headers for a smaller code snippet.

  1. In postHere.php setup the following:

    switch ($_SERVER['HTTP_ORIGIN']) {
        case '': case '':
        header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
        header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
        header('Access-Control-Max-Age: 1000');
        header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

    This allows your script to make cross domain POST, GET and OPTIONS. This will become clear as you continue to read…

  2. Setup your cross domain POST from JS (jQuery example):

    $.ajax({ type: ‘POST’, url: ‘', crossDomain: true, data: ‘{“some”:“json”}’, dataType: ‘json’, success: function(responseData, textStatus, jqXHR) { var value = responseData.someKey; }, error: function (responseData, textStatus, errorThrown) { alert(‘POST failed.'); } });

When you do the POST in step 2, your browser will send a “OPTIONS” method to the server. This is a “sniff” by the browser to see if the server is cool with you POSTing to it. The server responds with an “Access-Control-Allow-Origin” telling the browser its OK to POST|GET|ORIGIN if request originated from “” or “”. Since the server is OK with it, the browser will make a 2nd request (this time a POST). It is good practice to have your client set the content type it is sending - so you’ll need to allow that as well.

MDN has a great write-up about HTTP access control, that goes into detail of how the entire flow works. According to their docs, it should “work in browsers that support cross-site XMLHttpRequest”. This is a bit misleading however, as I THINK only modern browsers allow cross domain POST. I have only verified this works with safari,chrome,FF 3.6.

Keep in mind the following if you do this:

  1. Your server will have to handle 2 requests per operation
  2. You will have to think about the security implications. Be careful before doing something like ‘Access-Control-Allow-Origin: *’
  3. This wont work on mobile browsers. In my experience they do not allow cross domain POST at all. I’ve tested android, iPad, iPhone
  4. There is a pretty big bug in FF < 3.6 where if the server returns a non 400 response code AND there is a response body (validation errors for example), FF 3.6 wont get the response body. This is a huge pain in the ass, since you cant use good REST practices. See bug here (its filed under jQuery, but my guess is its a FF bug - seems to be fixed in FF4).
  5. Always return the headers above, not just on OPTION requests. FF needs it in the response from the POST.

#23 Best answer 2 of How do I send a cross-domain POST request via JavaScript?(Score: 124)

Created: 2011-05-29 Last updated: 2017-05-23

If you control the remote server, you should probably use CORS, as described in this answer; it’s supported in IE8 and up, and all recent versions of FF, GC, and Safari. (But in IE8 and 9, CORS won’t allow you to send cookies in the request.)

So, if you don’t control the remote server, or if you have to support IE7, or if you need cookies and you have to support IE8/9, you’ll probably want to use an iframe technique.

  1. Create an iframe with a unique name. (iframes use a global namespace for the entire browser, so pick a name that no other website will use.)
  2. Construct a form with hidden inputs, targeting the iframe.
  3. Submit the form.

Here’s sample code; I tested it on IE6, IE7, IE8, IE9, FF4, GC11, S5.

function crossDomainPost() {
  // Add the iframe with a unique name
  var iframe = document.createElement("iframe");
  document.body.appendChild(iframe); = "none"; = uniqueString;

  // construct a form with hidden inputs, targeting the iframe
  var form = document.createElement("form"); = uniqueString;
  form.action = "http://INSERT_YOUR_URL_HERE";
  form.method = "POST";

  // repeat for each parameter
  var input = document.createElement("input");
  input.type = "hidden"; = "INSERT_YOUR_PARAMETER_NAME_HERE";


Beware! You won’t be able to directly read the response of the POST, since the iframe exists on a separate domain. Frames aren’t allowed to communicate with each other from different domains; this is the same-origin policy.

If you control the remote server but you can’t use CORS (e.g. because you’re on IE8/IE9 and you need to use cookies), there are ways to work around the same-origin policy, for example by using window.postMessage and/or one of a number of libraries allowing you to send cross-domain cross-frame messages in older browsers:

If you don’t control the remote server, then you can’t read the response of the POST, period. It would cause security problems otherwise.

See also original question in stackoverflow

#24: Sending multipart/formdata with jQuery.ajax (Score: 588)

Created: 2011-03-22 Last updated: 2016-12-13

Tags: jquery, ajax, file-upload, multipartform-data, form-data

I’ve got a problem sending a file to a serverside PHP-script using jQuery’s ajax-function. It’s possible to get the File-List with $('#fileinput').attr('files') but how is it possible to send this Data to the server? The resulting array ($_POST) on the serverside php-script is 0 (NULL) when using the file-input.

I know it is possible (though I didn’t find any jQuery solutions until now, only Prototye code (

This seems to be relatively new, so please do not mention file upload would be impossible via XHR/Ajax, because it’s definitely working.

I need the functionality in Safari 5, FF and Chrome would be nice but are not essential.

My code for now is:

    url: 'php/upload.php',
    data: $('#file').attr('files'),
    cache: false,
    contentType: 'multipart/form-data',
    processData: false,
    type: 'POST',
    success: function(data){

#24 Best answer 1 of Sending multipart/formdata with jQuery.ajax (Score: 905)

Created: 2011-05-12 Last updated: 2017-10-05

Starting with Safari 5/Firefox 4, it’s easiest to use the FormData class:

var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
    data.append('file-'+i, file);

So now you have a FormData object, ready to be sent along with the XMLHttpRequest.

    url: 'php/upload.php',
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    method: 'POST',
    type: 'POST', // For jQuery < 1.9
    success: function(data){

It’s imperative that you set the contentType option to false, forcing jQuery not to add a Content-Type header for you, otherwise, the boundary string will be missing from it. Also, you must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.

You may now retrieve the file in PHP using:


(There is only one file, file-0, unless you specified the multiple attribute on your file input, in which case, the numbers will increment with each file.)

Using the FormData emulation for older browsers

var opts = {
    url: 'php/upload.php',
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    method: 'POST',
    type: 'POST', // For jQuery < 1.9
    success: function(data){
if(data.fake) {
    // Make sure no text encoding stuff is done by xhr
    opts.xhr = function() { var xhr = jQuery.ajaxSettings.xhr(); xhr.send = xhr.sendAsBinary; return xhr; }
    opts.contentType = "multipart/form-data; boundary="+data.boundary; = data.toString();

Create FormData from an existing form

Instead of manually iterating the files, the FormData object can also be created with the contents of an existing form object:

var data = new FormData(jQuery('form')[0]);

Use a PHP native array instead of a counter

Just name your file elements the same and end the name in brackets:

jQuery.each(jQuery('#file')[0].files, function(i, file) {
    data.append('file[]', file);

$_FILES['file'] will then be an array containing the file upload fields for every file uploaded. I actually recommend this over my initial solution as it’s simpler to iterate over.

#24 Best answer 2 of Sending multipart/formdata with jQuery.ajax(Score: 55)

Created: 2014-08-30 Last updated: 2014-11-04

Look at my code, it does the job for me

$( '#formId' )
  .submit( function( e ) {
    $.ajax( {
      url: 'FormSubmitUrl',
      type: 'POST',
      data: new FormData( this ),
      processData: false,
      contentType: false
    } );
  } );

See also original question in stackoverflow

#25: Send POST data using XMLHttpRequest (Score: 576)

Created: 2012-03-15 Last updated: 2020-07-21

Tags: javascript, ajax, forms, 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">

How can I write the equivalent using an XMLHttpRequest in JavaScript?

#25 Best answer 1 of Send POST data using XMLHttpRequest (Score: 819)

Created: 2012-03-15 Last updated: 2020-10-06

The code below demonstrates on how to do this.

var http = new XMLHttpRequest();
var url = 'get_data.php';
var params = 'orem=ipsum&name=binny';'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) {

In case you have/create an object you can turn it into params using the following code, i.e:

var params = new Object();
params.myparam1 = myval1;
params.myparam2 = myval2;

// Turn the data object into an array of URL-encoded key/value pairs.
let urlEncodedData = "", urlEncodedDataPairs = [], name;
for( name in params ) {

#25 Best answer 2 of Send POST data using XMLHttpRequest(Score: 290)

Created: 2013-03-09 Last updated: 2013-06-24

var xhr = new XMLHttpRequest();'POST', 'somewhere', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
    // do something to response

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();'POST', 'somewhere', true);
xhr.onload = function () {
    // do something to response

See also original question in stackoverflow

#26: On - window.location.hash - Change? (Score: 568)

Created: 2009-03-25 Last updated: 2020-03-14

Tags: javascript, ajax, dom-events, fragment-identifier, hashchange

I am using Ajax and hash for navigation.

Is there a way to check if the window.location.hash changed like this?**#123** to**#456**

It works if I check it when the document loads.

But if I have #hash based navigation it doesn’t work when I press the back button on the browser (so I jump from blah#456 to blah#123).

It shows inside the address box, but I can’t catch it with JavaScript.

#26 Best answer 1 of On - window.location.hash - Change? (Score: 621)

Created: 2009-03-25 Last updated: 2014-10-03

The only way to really do this (and is how the ‘reallysimplehistory’ does this), is by setting an interval that keeps checking the current hash, and comparing it against what it was before, we do this and let subscribers subscribe to a changed event that we fire if the hash changes.. its not perfect but browsers really don’t support this event natively.

Update to keep this answer fresh:

If you are using jQuery (which today should be somewhat foundational for most) then a nice solution is to use the abstraction that jQuery gives you by using its events system to listen to hashchange events on the window object.

$(window).on('hashchange', function() {
  //.. work ..

The nice thing here is you can write code that doesn’t need to even worry about hashchange support, however you DO need to do some magic, in form of a somewhat lesser known jQuery feature jQuery special events.

With this feature you essentially get to run some setup code for any event, the first time somebody attempts to use the event in any way (such as binding to the event).

In this setup code you can check for native browser support and if the browser doesn’t natively implement this, you can setup a single timer to poll for changes, and trigger the jQuery event.

This completely unbinds your code from needing to understand this support problem, the implementation of a special event of this kind is trivial (to get a simple 98% working version), but why do that when somebody else has already.

#26 Best answer 2 of On - window.location.hash - Change?(Score: 295)

Created: 2009-03-25 Last updated: 2012-06-15

HTML5 specifies a hashchange event. This event is now supported by all modern browsers. Support was added in the following browser versions:

  • Internet Explorer 8
  • Firefox 3.6
  • Chrome 5
  • Safari 5
  • Opera 10.6

See also original question in stackoverflow

#27: Response to preflight request doesn't pass access control check (Score: 546)

Created: 2016-02-23 Last updated: 2020-12-18

Tags: javascript, ajax, http, cors, http-status-code-405

I’m getting this error using ngResource to call a REST API on Amazon Web Services:

XMLHttpRequest cannot load Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost’ is therefore not allowed access. Error 405


socialMarkt.factory('loginService', ['$resource', function ($resource) {
    var apiAddress = "";
    return $resource(apiAddress, {
        login: "facebook",
        access_token: "@access_token",
        facebook_id: "@facebook_id"
    }, {
        getUser: {
            method: 'POST'


    function (data) {
    function (result) {
        console.error('Error', result.status);

I’m using Chrome, and I dont know what else to do in order to fix this problem. I’ve even configured the server to accept headers from origin localhost.

#27 Best answer 1 of Response to preflight request doesn't pass access control check (Score: 282)

Created: 2016-02-23 Last updated: 2021-01-27

You are running into CORS issues.

There are several ways to fix/workaround this.

  1. Turn off CORS. For example: how to turn off cors in chrome
  2. Use a plugin for your browser
  3. Use a proxy such as nginx. example of how to set up
  4. Go through the necessary setup for your server. This is more a factor of the web server you have loaded on your EC2 instance (presuming this is what you mean by “Amazon web service”). For your specific server you can refer to the enable CORS website.

More verbosely, you are trying to access from localhost. This is the exact definition of cross domain request.

By either turning it off just to get your work done (OK, but poor security for you if you visit other sites and just kicks the can down the road) you can use a proxy which makes your browser think all requests come from local host when really you have local server that then calls the remote server.

so might become localhost:8000/api and your local nginx or other proxy will send to the correct destination.

Now by popular demand, 100% more CORS info….same great taste!

Bypassing CORS is exactly what is shown for those simply learning the front end.

#27 Best answer 2 of Response to preflight request doesn't pass access control check(Score: 186)

Created: 2016-04-06 Last updated: 2016-06-21

My “API Server” is an PHP Application so to solve this problem I found the below solution to work:

Place the lines in index.php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');

See also original question in stackoverflow

#28: How can I post data as form data instead of a request payload? (Score: 531)

Created: 2012-07-11 Last updated: 2015-08-15

Tags: ajax, angularjs, post, angular-http

In the code below, the AngularJS $http method calls the URL, and submits the xsrf object as a “Request Payload” (as described in the Chrome debugger network tab). The jQuery $.ajax method does the same call, but submits xsrf as “Form Data”.

How can I make AngularJS submit xsrf as form data instead of a request payload?

var url = '';
var xsrf = {fkey: 'xsrf key'};

    method: 'POST',
    url: url,
    data: xsrf
}).success(function () {});

    type: 'POST',
    url: url,
    data: xsrf,
    dataType: 'json',
    success: function() {}

#28 Best answer 1 of How can I post data as form data instead of a request payload? (Score: 621)

Created: 2012-07-11 Last updated: 2020-06-20

The following line needs to be added to the $http object that is passed:

headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}

And the data passed should be converted to a URL-encoded string:

> $.param({fkey: "key"})

So you have something like:

    method: 'POST',
    url: url,
    data: $.param({fkey: "key"}),
    headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}



To use new services added with AngularJS V1.4, see

#28 Best answer 2 of How can I post data as form data instead of a request payload?(Score: 194)

Created: 2013-02-14 Last updated: 2017-05-23

If you do not want to use jQuery in the solution you could try this. Solution nabbed from here

	method: 'POST',
	url: url,
	headers: {'Content-Type': 'application/x-www-form-urlencoded'},
	transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
	data: xsrf
}).success(function () {});

See also original question in stackoverflow

#29: How to send FormData objects with Ajax-requests in jQuery? (Score: 522)

Created: 2011-08-07 Last updated: 2017-05-23

Tags: javascript, jquery, ajax, html, multipartform-data

The XMLHttpRequest Level 2 standard (still a working draft) defines the FormData interface. This interface enables appending File objects to XHR-requests (Ajax-requests).

Btw, this is a new feature - in the past, the “hidden-iframe-trick” was used (read about that in my other question).

This is how it works (example):

var xhr = new XMLHttpRequest(),
    fd = new FormData();

fd.append( 'file', input.files[0] ); 'POST', '', true );
xhr.onreadystatechange = handler;
xhr.send( fd );

where input is a <input type="file"> field, and handler is the success-handler for the Ajax-request.

This works beautifully in all browsers (again, except IE).

Now, I would like to make this functionality work with jQuery. I tried this:

var fd = new FormData();    
fd.append( 'file', input.files[0] );

$.post( '', fd, handler );

Unfortunately, that won’t work (an “Illegal invocation” error is thrown - screenshot is here). I assume jQuery expects a simple key-value object representing form-field-names / values, and the FormData instance that I’m passing in is apparently incompatible.

Now, since it is possible to pass a FormData instance into xhr.send(), I hope that it is also possible to make it work with jQuery.


I’ve created a “feature ticket” over at jQuery’s Bug Tracker. It’s here:

I was suggested to use an “Ajax prefilter”…


First, let me give a demo demonstrating what behavior I would like to achieve.


    <input type="file" id="file" name="file">
    <input type="submit">


$( 'form' ).submit(function ( e ) {
    var data, xhr;
    data = new FormData();
    data.append( 'file', $( '#file' )[0].files[0] );
    xhr = new XMLHttpRequest(); 'POST', '', true );
    xhr.onreadystatechange = function ( response ) {};
    xhr.send( data );

The above code results in this HTTP-request:


This is what I need - I want that “multipart/form-data” content-type!

The proposed solution would be like so:

$( 'form' ).submit(function ( e ) {
    var data;
    data = new FormData();
    data.append( 'file', $( '#file' )[0].files[0] );
        url: '',
        data: data,
        processData: false,
        type: 'POST',
        success: function ( data ) {
            alert( data );

However, this results in:


As you can see, the content type is wrong…

#29 Best answer 1 of How to send FormData objects with Ajax-requests in jQuery? (Score: 926)

Created: 2011-11-23 Last updated: 2020-04-18

I believe you could do it like this :

var fd = new FormData();    
fd.append( 'file', input.files[0] );

  url: '',
  data: fd,
  processData: false,
  contentType: false,
  type: 'POST',
  success: function(data){


  • Setting processData to false lets you prevent jQuery from automatically transforming the data into a query string. See the docs for more info.

  • Setting the contentType to false is imperative, since otherwise jQuery will set it incorrectly.

#29 Best answer 2 of How to send FormData objects with Ajax-requests in jQuery?(Score: 30)

Created: 2011-11-30

There are a few yet to be mentioned techniques available for you. Start with setting the contentType property in your ajax params.

Building on pradeek’s example:

$('form').submit(function (e) {
    var data;

    data = new FormData();
    data.append('file', $('#file')[0].files[0]);

        url: '',
        data: data,
        processData: false,
        type: 'POST',

        // This will override the content type header, 
        // regardless of whether content is actually sent.
        // Defaults to 'application/x-www-form-urlencoded'
        contentType: 'multipart/form-data', 
        //Before 1.5.1 you had to do this:
        beforeSend: function (x) {
            if (x && x.overrideMimeType) {
        // Now you should be able to do this:
        mimeType: 'multipart/form-data',    //Property added in 1.5.1

        success: function (data) {


In some cases when forcing jQuery ajax to do non-expected things, the beforeSend event is a great place to do it. For a while people were using beforeSend to override the mimeType before that was added into jQuery in 1.5.1. You should be able to modify just about anything on the jqXHR object in the before send event.

See also original question in stackoverflow

#30: jQuery get textarea text (Score: 506)

Created: 2008-09-28 Last updated: 2011-05-31

Tags: javascript, jquery, ajax

Recently I have started playing with jQuery, and have been following a couple of tutorials. Now I feel slightly competent with using it (it’s pretty easy), and I thought it would be cool if I were able to make a ‘console’ on my webpage (as in, you press the ` key like you do in FPS games, etc.), and then have it Ajax itself back to the server in-order to do stuff.

I originally thought the best way would be to just get the text inside the textarea, and then split it, or should I use the keyup event, convert the keycode returned to an ASCII character, append the character to a string and send the string to the server (then empty the string).

I couldn’t find any information on getting text from a textarea, all I got was keyup information. Also, how can I convert the keycode returned to an ASCII character?

#30 Best answer 1 of jQuery get textarea text (Score: 737)

Created: 2008-09-28

Why would you want to convert key strokes to text? Add a button that sends the text inside the textarea to the server when clicked. You can get the text using the value attribute as the poster before has pointed out, or using jQuery’s API:

$('input#mybutton').click(function() {
    var text = $('textarea#mytextarea').val();
    //send to server and process response

#30 Best answer 2 of jQuery get textarea text(Score: 41)

Created: 2014-06-13

Where it is often the text function you use (e.g. in divs etc) then for text area it is val




$('#myTextBox').val('new value');

See also original question in stackoverflow

  1. This page use API to get the relevant data from stackoverflow community.
  2. Content license on this page is CC BY-SA 3.0.
  3. score = up votes - down votes.