Skip to content Skip to sidebar Skip to footer

Storing Form Data To Json

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. <

Solution 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

varstring = JSON.stringify(containerName);

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

Solution 2:

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.

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

    foreach($dataas$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 : ''?><formmethod="post"><labelfor="name">Name</label><inputtype="name"name="name"id="name"placeholder="e.g. John Doe"required><labelfor="email">Email address</label><inputtype="email"name="email"id="email"placeholder="e.g. john.doe@example.com"required><labelfor="password">Password</label><inputtype="password"name="password"id="password"placeholder="e.g. S3cR3t"required><labelfor="password">Confirm Password</label><inputtype="password"name="cpassword"id="cpassword"placeholder="e.g. S3cR3t"required><inputtype="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.

Post a Comment for "Storing Form Data To Json"