0

i am trying to get form values in json format on button click the code is..

$('#submit').click(function() {
    var form = $("#user_info");
    var data =form.serialize();
    console.log(data)

but i am getting values like

userfnmae=xyz&userlname=xyz&[email protected]&useremail= xyz&usercity=zzz&userlocation=abc&userproduct=xyz&usercomment=xyz

but i want data in json format.

2 Answers 2

3

Use serializeArray => Encode a set of form elements as an array of names and values

Try this:

$('#g').click(function(e) {
  e.preventDefault();
  var data = $('#user_info').serializeArray();
  alert(JSON.stringify(data));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id='user_info'>
  <div>
    <input type="text" name="a" value="1" id="a">
  </div>
  <div>
    <input type="text" name="b" value="2" id="b">
  </div>
  <div>
    <input type="hidden" name="c" value="3" id="c">
  </div>
  <div>
    <textarea name="d" rows="8" cols="40">4</textarea>
  </div>
  <div>
    <select name="e">
      <option value="5" selected="selected">5</option>
      <option value="6">6</option>
      <option value="7">7</option>
    </select>
  </div>
  <div>
    <input type="checkbox" name="f" value="8" id="f">
  </div>
  <div>
    <input type="submit" name="g" value="Submit" id="g">
  </div>
</form>

Sign up to request clarification or add additional context in comments.

Comments

1

Use this coding ...

$('#submit').click(function() {
    var result= {};
     $("#user_info").serializeArray().map(function(item) {
        if ( result[item.name] ) {
            if ( typeof(result[item.name]) === "string" ) {
                result[item.name] = [config[item.name]];
            }
            result[item.name].push(item.value);
        } else {
            result[item.name] = item.value;
        }
    });
 console.log(result);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.