PeakGen
PeakGen

Reputation: 23035

How to store form data in an ajax variable?

I have a form with one text field. This form is submitted using ajax. While submitting, I want to save the data in the textfield in one of ajax variables too. Below is my code.

<script>
 $(function() {
//twitter bootstrap script
 $("button#submit").click(function(){
         $.ajax({

     type: "POST",
 url: "PastSurgicalCustomItem",
 data: $('form.form-horizontal').serialize(),
         success: function(msg){

        var $data = $('form.form-horizontal').serialize();

         var $firstDiv = $('<div></div>');
         $firstDiv.attr("class","col-md-3");


         var $secondDiv = $('<div></div>');
         $secondDiv.attr("class","checkbox history_checkbox_div");
         $secondDiv.appendTo($firstDiv);

         var $label = $('<label></label>');
         $label.appendTo($secondDiv);

         var $checkBox = $('<input></input>');
         $checkBox.attr("type","checkbox");
         $checkBox.attr("class","history_checkbox");
         $checkBox.attr("id",msg);
         $checkBox.appendTo($label);

         var $span = $('<span></span>');
         $span.text($data);
         $span.appendTo($label);

         $firstDiv.appendTo($('#customDiv'));


         },
 error: function(){
 alert("failure");
 }
       });
 });
});
</script>

But that didn't work well. If I insert the data "test7", then the $data variable will contain the below

textinput=&textarea=&customName=test7

How can I correctly get the data inside the textbox to an ajax variable? For more information, my application is designed using bootstrap.

Upvotes: 2

Views: 786

Answers (3)

user3989103
user3989103

Reputation:

Then you can store in variable something like this

var variable_name= $(this).find('textarea[name="your_textarea_name"]').text();

Upvotes: 3

Jeremy Thille
Jeremy Thille

Reputation: 26390

Use serializeArray() instead of serialize().

serialize() outputs a key/value string textinput=&textarea=&customName=test7

serializeArray() outputs a JSON :

[
  {
    name: "a",
    value: "1"
  },
  {
    name: "b",
    value: "2"
  },
  {
    name: "c",
    value: "3"
  },
  {
    name: "d",
    value: "4"
  },
  {
    name: "e",
    value: "5"
  }
]

Upvotes: 1

7ochem
7ochem

Reputation: 2350

Here's how you can get values of individual fields inside your form:

$('form.form-horizontal').find(':input[name="customName"]').val();

Upvotes: 1

Related Questions