-2

I am a coding beginner, and I am currently learning how to code in javascript. I am stuck on a practice problem, where I must utilize AJAX in order to retrieve data from a form, convert the data into JSON and then append a message that uses the JSON data that was created. When I click the submit button, the success function doesn't seem to be working. I am also using JQUERY. My main question is, must I create a separate JSON file, or will the JSON data be produced on it's own when I submit the form.

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<div class="tour" data-daily-price="357">
  <h2>Paris, France Tour</h2>
  <p>$<span id="total">2,499</span> for <span id="nights-count">7</span> Nights</p>
  <form method="POST">
    <p>
      <label for="nights">Number of Nights</label>
    </p>
    <p>
      <input type="number" name="nights" id="nights" value="7">
    </p>
    <input type="submit" value="book">
  </form>
</div>
<script type="text/javascript" src="jquery-2.2.3.min copy 4.js"></script>
<script type="text/javascript" src="json.js"></script>
</body>
</html>

$(document).ready(function() {
  $("form").on("submit", function(event) {
    event.preventDefault();
    $.ajax("http://localhost:8888/json.html", {
      type: 'POST',
      data: $("form").serialize(),
      dataType: 'json',
      contentType: "application/json",
      success: function(data) {
        var msg = $('<p></p>');
        msg.append("Trip booked for " + data.nights+" nights.");
        $(".tour").append(msg);

      }
    });
  });
});
TomBa
  • 5
  • 5
  • Possible duplicate of [How to send a JSON object using html form data](http://stackoverflow.com/questions/22195065/how-to-send-a-json-object-using-html-form-data) – emerson.marini May 20 '16 at 15:24

2 Answers2

0

My main question is, must I create a separate JSON file

No. If you want to send JSON then you have to construct a string of JSON, but you don't need to make it a file.

or will the JSON data be produced on it's own when I submit the form.

No. You have to create the JSON yourself.


$("form").serialize() converts data into the application/x-www-form-urlencoded format. Don't use it if you want to send JSON.

There is no standard for encoding form data into JSON so you must loop over all the form controls (or the data in serializeArray) to build the data structure you want and then pass it though JSON.stringify.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks, so if I JSON.stringify the data into a variable, the i JSON.parse the variable, it returns an array of objects, with the objects containing JSON formatted data from the form I submitted. Now, how do I access that data within the objects in order to use it in my appended message in Success function? – TomBa May 20 '16 at 16:11
  • "JSON.stringify the data into a variable" — Then you get a variable containing a string. – Quentin May 20 '16 at 16:16
  • "the i JSON.parse the variable, it returns an array of objects" — You get whatever form the data was in before you converted it to JSON. If you do both of these on the client, then using JSON was pointless. It's only useful if you are going to use Ajax to send the string of JSON to the server and parse it there. – Quentin May 20 '16 at 16:17
  • "with the objects containing JSON formatted data from the form" — It isn't JSON formatted (unless you converted the data to JSON before putting it into objects before putting them into the array you mentioned … which would be complex and probably pointless). – Quentin May 20 '16 at 16:18
  • "how do I access that data within the objects in order to use it in my appended message in Success function" — If you want to use your original data, then you just access the variable that you stored it in when you read it from the form in the first place. At that point I'd question why you were using Ajax at all. If you wanted to do something with the data on the server and then return some data … you'd use the `data` variable you defined here: `success: function(data) {` which would contain the result of parsing the JSON that the server side code (that you haven't provided) responded with. – Quentin May 20 '16 at 16:19
0

Expanding on what Quentin said, you'll need to parse the fields and values out of the form yourself and put them in a JSON object. I've been using the following function (found on another stack overflow answer but I don't have the reference) which will iterate the form looking for named fields and then put that into a JSON object.

(function ($) {
    $.fn.serializeFormJSON = function () {

        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };
})(jQuery);

This function is added to the JQuery operator $ so can be called like

var data = $(this).serializeFormJSON();

And you can then use that directly in the AJAX call or stringify it first if necessary.

EDIT; meant to add that you should only call this inside of a form.submit callback as it will use the form as the this parameter.

Dillanm
  • 876
  • 12
  • 28