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

fuzzybabybunny

Moderator<br>Digital & Video Cameras
Moderator
Jan 2, 2006
10,455
35
91
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?

Code:
     <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>
 

purbeast0

No Lifer
Sep 13, 2001
53,543
6,368
126
before the $.ajax call, use the jquery selector to get all of the values in the form field and build a json with those values.
 

Ken g6

Programming Moderator, Elite Member
Moderator
Dec 11, 1999
16,616
4,532
75
Also, be sure to consider error conditions and messages, both on the client side and the server side.

And are you sure you want to use type: "PATCH"? This looks like a simple POST to me. :confused:
 

KB

Diamond Member
Nov 8, 1999
5,406
389
126
You have to build the pin object before you send it:

Code:
var pin;

pin.title = $('#pin[title]').value();
pin.lat = $('#pin[lat]').value();

...............


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

I do have some convention questions for you.
Why do you have [] brackets in the names of your controls. I don't recommended it as it confusing. It looks liek javascript code. Is it apart of some javascript framework you are using? Second why are you using the name attribute of the fields and not the id attribute? To use the $('#pin[title]') selector in jquery, the identity attribute on the control needs to be in the id, not the name.
 

Crusty

Lifer
Sep 30, 2001
12,684
2
81
You have to build the pin object before you send it:

Code:
var pin;

pin.title = $('#pin[title]').value();
pin.lat = $('#pin[lat]').value();

...............


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

I do have some convention questions for you.
Why do you have [] brackets in the names of your controls. I don't recommended it as it confusing. It looks liek javascript code. Is it apart of some javascript framework you are using? Second why are you using the name attribute of the fields and not the id attribute? To use the $('#pin[title]') selector in jquery, the identity attribute on the control needs to be in the id, not the name.

I believe he's using Ruby on Rails, so those control names are supposed to hook into rails jquery adapter.
https://github.com/rails/jquery-ujs
 

fuzzybabybunny

Moderator<br>Digital & Video Cameras
Moderator
Jan 2, 2006
10,455
35
91
Yeah, RoR. What I ended up doing is this:

Code:
$.ajax({
         type: "PATCH",
         url: "api/pins/{{pin/id}}",
         contentType: 'application/json',
         dataType: 'json',
         data: $('#editUserPinForm').serializeJSON()
     }).success(function(){
        alert("Pin edited!");
        getAllCurrentUserPins(); //response from server.
     });

Voila. Done. serializeJSON I got from GitHub and it works like a dream.

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

Others recommended this:

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

But the problem with this is that it converts the data into an array which you then convert into a JSON, but the array adds a "Name" and "Value" that makes the resultant JSON really hard to use.

serializeJSON outputs a perfect JSON file. No massaging of data necessary.
 

fuzzybabybunny

Moderator<br>Digital & Video Cameras
Moderator
Jan 2, 2006
10,455
35
91
Also, be sure to consider error conditions and messages, both on the client side and the server side.

And are you sure you want to use type: "PATCH"? This looks like a simple POST to me. :confused:

Eh. I was told it's best to use PATCH if we're updating just parts of something.
 

Crusty

Lifer
Sep 30, 2001
12,684
2
81
Eh. I was told it's best to use PATCH if we're updating just parts of something.

Assuming you're using the standard resource based routes then the PATCH will map to the 'update' action in your controller and POST will match to the 'create' action in your controller.
 

fuzzybabybunny

Moderator<br>Digital & Video Cameras
Moderator
Jan 2, 2006
10,455
35
91
Assuming you're using the standard resource based routes then the PATCH will map to the 'update' action in your controller and POST will match to the 'create' action in your controller.

Ah, yes, true. I used resources BUT even if I didn't I would still be using Patch and pointing it to update. Just like to keep things RESTful.