简体   繁体   中英

Submitting form with multiple fields via ajax - how to format the data into JSON?

I have a form with multiple data entries. Ajax (at the bottom) requires the data that is being passed to it to be bundled together. How do I take the un-submitted text in my form fields and bundle it into a JSON object to be sent to my Ajax?

 <div id="editUserPinForm" class="ui raised segment signin">
  <div class="cmborder">
    <div class="form_heading">Edit Your Pin</div>
    <form>
      <div class="ui form attached fluid segment">
        <div class="two fields">
          <div class="field">
            <label>Title</label>
            <input type="text" name="pin[title]" class="ui input" value="{{pin/title}}">
          </div>
          <div class="field">
            <label>Activity</label>
            <input type="text" name="pin[activity]" class="ui input" value="{{pin/activity}}">
          </div>
        </div>
        <div class="field">
          <label>Description</label>
          <textarea name="pin[description]" class="ui input">{{pin/description}}</textarea>
        </div>
        <div class="inline field">
          <input type="hidden" name="pin[guideID]" value="{{pin/guide_id}}">
        </div>
        <div class="inline field">
          <input type="hidden" name="pin[lat]" value="{{pin/lat}}">
        </div>
        <div class="inline field">
          <input type="hidden" name="pin[long]" value="{{pin/long}}">
        </div>
        <div class="inline field">
          <input type="submit" value="Submit Changes" class="ui blue submit button">
        </div>
      </div>
    </form>
  <span class='close_message' id="messageclose">&times;</span>
  </div>
</div>

<script>

  $( "#messageclose" ).on("click", function() {
      $('#editUserPinForm').fadeOut();
    });

  $("#editUserPinForm").submit(function() {
      $.ajax({
           type: "PATCH",
           url: "api/pins/{{pin/id}}",
           contentType: 'application/json',
           dataType: 'json',
           data: JSON.stringify( {pin:{description:value}})
           }).success: function(response){
               alert(response); //response from server.
           };
      });


</script>

I used jQuery Serialize instead and it worked like a charm.

https://github.com/macek/jquery-serialize-object

The problem with

JSON.stringify($(this).serializeArray());

is that it converts an array into a JSON, but the array adds a "Name" and "Value" that makes the resultant JSON really hard to use.

You could use the internal jQuery $('#domNode').serializeArray() which will return an array of all the inputs in an array of objects. It follows the W3C pattern for returning the valid inputs for successful controls, meaning it will not return disabled controls.

Ref:
https://api.jquery.com/serializeArray/
http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2

In order to send the form as a json string. You have to create an array with inputs names and values pairs, by gathering every input name and value to associate them in an array of objects containing the name and value pair :

$("#editUserPinForm").submit(function() {
jQuery("#editUserPinForm").find("input").each( function()
{

var form_data = new Array(); // The array that'll contain inputs names and values
form_data.push( { $(this).attr('name') : $(this).val() } );
var form_jsoned = JSON.stringify(form_data);

// Then here you can call ajax and send the json data
$.ajax({
       type: "PATCH",
       url: "api/pins/{{pin/id}}",
       contentType: 'application/json',
       dataType: 'json',
       data: form_jsoned
       }).success: function(response){
           alert(response); //response from server.
       };
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM