Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery serialize not working

Tags:

jquery

I was dabbling with the form serialize but surprisingly its not serializing the form. Here is the code:

<div id="content">
</div>
<form  id= "myform">
    <input type="text" id="inp"value="mytext">
    <input type="button" id="btn" value="serialize"/>
</form>

Here is the jQuery code I am working with:

$("form").submit(function(e){
    e.preventDefault();
    var v= $(this).serialize();
    console.log(v);
});

Here is the fiddle

like image 936
Tassadaque Avatar asked Jan 31 '12 04:01

Tassadaque


People also ask

What is serialize in jQuery?

jQuery serialize() Method The serialize() method creates a URL encoded text string by serializing form values. You can select one or more form elements (like input and/or text area), or the form element itself. The serialized values can be used in the URL query string when making an AJAX request.

How do you serialize data in JavaScript?

In JavaScript, for example, you can serialize an object to a JSON string by calling the function JSON. stringify() . CSS values are serialized by calling the function CSSStyleDeclaration. getPropertyValue() .

How can I access serialized form data in PHP?

To get the POST values from serializeArray in PHP, use the serializeArray() method. The serializeArray( ) method serializes all forms and form elements like the . serialize() method but returns a JSON data structure for you to work with.

What will you use in jQuery if you wanted to convert the contents of a form elements into string for submission?

You can do this: var frm = $(document. myform); var data = JSON. stringify(frm.


2 Answers

You need a name attribute on your input fields. Otherwise they're ignored by jQuery's .serialize().

Here's a quote from the docs:

Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.

Here's your fiddle with a name attribute: http://jsfiddle.net/6fgUg/28/

like image 182
Joseph Silber Avatar answered Oct 21 '22 03:10

Joseph Silber


You have to give a name to the input HTML element, for example:

<form id="myform"> 
    <input type="text" id="inp" name="inp" value="mytext">
    <input type="button" id="btn" name="btn" value="serialize"/>
</form>
like image 30
Yanny Avatar answered Oct 21 '22 01:10

Yanny