-7

I wrote this code for a sign up form. I want to add the values of email id and password to JSON file in the form of array objects.

Here is my html file.

<!DOCTYPE html>

<head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta name="robots" content="noindex, nofollow" charset="UTF-8">

</head>

<body>

  <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.3.min.js"></script>
  <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>
  <script type="text/javascript" src="jQuery-UI.js"></script>
  <script src="validate.js"></script>

  <form id="myform" enctype="application/json">
    <div class="container-form">
      <fieldset>
          <legend>Sign up</legend>

          <label for="username">User Name</label><br>
          <input type="text" name="username[]" id="username" placeholder="Your name" minlength="2" required=""><br><br>

          <label for="contact">Contact</label><br>
          <input name="contact" type="number" id="contact" placeholder="Phone Number" >
          <br><br>
          <label for="emailid">Email id</label><br>
          <input type="email" name="emailid[]" id="email" pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" placeholder="Enter email id" required=""><br><br>

          <label for="password">Password</label><br>
          <input type="password" name="password[]" id="password" placeholder="Enter password" required="" minlength="6"><br><br>

          <label for="password">Confirm Password</label><br>
          <input type="password" name="cpassword" id="cpassword" placeholder="Confirm Password"><br><br>

          <button type="submit" name="register" id="register" value="Submit">Submit</button>
          <button type="reset" value="Clear">Clear</button>
          <div id="result">
          </div>
      </fieldset>
    </div>
  </form>
</body>

my submit.js which has been converted into bundle.j since require() cannot be used directly. here is my submit.js

    (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){

var fs = require('fs');

$(function() {
    $(document).ready(function(){
        $("#myform").validate({
            rules: {
                password: "required",
                cpassword: {
                    required: true,
                    equalTo: "#password"
                }
            },

            messages: {

                cpassword: {
                    required: 'Please re-enter the password',
                    equalTo: 'Please enter the same password'
                }
            }
        });

        $("#register").on('click', function(){

      var data1 = fs.readFileSync('data.json');
      var words = JSON.parse(data1);

      function make_json(form){
            var jsonObject = {
            "name" : $("#username").val(),
            "email" : $("#email").val(),
                    "password": $("#password").val()
            };
            console.log(jsonObject);
      };
      var data2 = JSON.stringify(jsonObject, null, 2);
      fs.writeFile("./data.json", data2, finished);

      function finished(err) {
        console.log('all set.');
      }
        });
    });
});


},{"fs":2}],2:[function(require,module,exports){

},{}]},{},[1]);

Where am I going wrong? If possible send the edited code instead of link to some website. Thanks.

suchcodemuchwow
  • 848
  • 2
  • 9
  • 27
Saurabh Soman
  • 11
  • 1
  • 5
  • 8
    _“if possible send the code instead of link to some website”_ - StackOverflow is not a coding service. We are happy to help you implement what you want yourself - but that requires that you go read up on the necessary basics first. – CBroe Aug 29 '17 at 12:49
  • Possible duplicate of [How to send a JSON object using html form data](https://stackoverflow.com/questions/22195065/how-to-send-a-json-object-using-html-form-data) – T. Jung Aug 29 '17 at 12:55

2 Answers2

1

You could grep the values from your inputs, and i see you are using jQuery so here is an example for your username input field

var userName = $('#username').val(); //the # tells jQuery you are specifying an elements id, use a . (dot) tho specify a class

You can but this in a json aswell
first define a json object

var containerName = {};

Add your values to the container

containerName.userName = $('#username').val();

You can convert your object to a string with

var string = JSON.stringify(containerName);

These are some basic operations to get values from your form in some kind of structure.
Hope this helps.

Mike
  • 852
  • 9
  • 17
1

As you've tagged your question Php, I'll give you a rough gist of submitting a form, doing some server side validation. And if the validation is satisfied store the data submitted in JSON format in a file.

No Javascript included here.

<?php

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $data = [
        'name' => null,
        'password' => null,
        'cpassword' => null,
        'email' => null
    ];

    foreach($data as $k => $v) {
        if(!empty($_POST[$k]))
            $data[$k] = $_POST[$k];
    }

    $validated = true;
    if($data['password'] !== $data['cpassword'])
        $validated = false;

    if(!filter_var($data['email'], FILTER_VALIDATE_EMAIL))
        $validated = false;

    if($validated) {
        if(file_put_contents('/tmp' . '/' . uniqid('json_'), json_encode($data, JSON_PRETTY_PRINT)))
            $feedback = 'Thanks.  Submission stored.';
    }
    else {
        $error = 'Please fill in all your form fields correctly.';
    }

}

?>
<?= isset($error)    ? $error    : '' ?>
<?= isset($feedback) ? $feedback : '' ?>

<form method="post">
    <label for="name">Name</label>
    <input type="name" name="name" id="name" placeholder="e.g. John Doe" required>

    <label for="email">Email address</label>
    <input type="email" name="email" id="email" placeholder="e.g. john.doe@example.com" required>

    <label for="password">Password</label>
    <input type="password" name="password" id="password" placeholder="e.g. S3cR3t" required>

    <label for="password">Confirm Password</label>
    <input type="password" name="cpassword" id="cpassword" placeholder="e.g. S3cR3t" required>
    <input type="submit" value="Go">
</form>

Of course it could do with some usability enhancements - such as telling the user where exactly they went wrong. But you get the idea.

Progrock
  • 7,373
  • 1
  • 19
  • 25
  • Thanks bro. But what does 'if(file_put_contents('/tmp' . '/' . uniqid('json_'), json_encode($data, JSON_PRETTY_PRINT))' this mean? – Saurabh Soman Aug 30 '17 at 05:36
  • Am I supposed to give path to my json file "('/tmp' . '/' . uniqid('json_')" where the data is to be stored? – Saurabh Soman Aug 30 '17 at 05:48
  • @SaurabhSoman file_put_contents writes a string to a file. The path in the example writes this to a folder called '/tmp', and gives it a unique name with a prefix of 'json_', The json_encode function converts a Php array to JSON. The pretty print is optional. It just makes the JSON human readable. Swap '/tmp' for the directory path you'd like to store the results, and make sure it's writeable by your webserver. – Progrock Aug 30 '17 at 08:19
  • So when I replace '/tmp' with my file name e.g. data.json so i write '/data' right? – Saurabh Soman Aug 30 '17 at 09:47
  • `file_put_contents($file_path, $data)` http://php.net/manual/en/function.file-put-contents.php , you can decide on your own file path scheme. In my example you get a file called something like: `json_59a68ac096f3d` that resides in the `/tmp` directory. `uniqid` is used to avoid name based collisions. The tempory directory is just used here as an example. – Progrock Aug 30 '17 at 09:54
  • bro i think u didnt get my question. my signup.php and formData.json are in same folder. m just asking do i need to add extension like "./formData.json" or is it ok if i put "./formData". and one more thing when i hit the submit button will my formData.json file be updated? – Saurabh Soman Aug 30 '17 at 10:01
  • Your question was not clear. Call the file what you like (but it must be writable). If you give it a fixed name, every time someone submits that form the file will be clobbered with the values from the form. Not updated. – Progrock Aug 30 '17 at 10:22
  • m sry i didnt get you. if I create a file data.json is it not writebale? – Saurabh Soman Aug 30 '17 at 10:31
  • Whether a file is writable by the server/script depends upon your environment and is somewhat out of scope for this question. Try something, if you have a problem that you can't solve, come back to SO and post another question. – Progrock Aug 30 '17 at 10:52