Sunday, February 14, 2016

PHP SQLite Form Send JSON Data


.
PHP SQLite Form Send JSON Data

This tutorial demonstrates the concept of form data serialization.
In order to process the submitted data, the server should be able to recognize the JSON Format and decode it.

0) Starting Up

This tutorial extends from the previous tutorial, http://php-steps.blogspot.my/2016/02/php-and-sqlite-form-validate-submit-and.html .
We will clone the script file submitbuddy.php into submitjsonbuddy.php.
We will use addbuddy.pphp as the target script for JSON data processing since it has been programmed to process JSON data format. (refer tutorial http://php-steps.blogspot.my/2016/02/php-sqlite-json-decode-encode-http.html )

1) Write the script logic

File: submitjsonbuddy.php

<html>
<body>
<form action="addbuddy.php" method="post">
    <!-- when name field changes(onchange) call setJsonData() -->
    <!-- when email field changes(onchange) call setJsonData() -->
    <!-- when name file ischanged(onchange) call previewFile() -->
    <!-- hide photo text field using CSS "style='display:none'"-->
    <!-- hide jsondata text field using attribute "hidden" -->
</form>
<script>
//function to update the image preview
function previewFile() {
    <!-- update the image src with dataurl -->
    <!-- call setJsonData() -->
}
function setJsonData(){
        <!-- call formToJson() -->
    <!-- update hidden field 'jsondata' -->
}
function formToJson(form) {
    <!-- convert all field values (except hidden field) into JSON format -->
    return jsonformat
};
</script>
</body>
</html>

2) Write PHP codes


The form data values are transformed into JSON format and stored in a hidden field “jsondata”.
The image is encoded as base 64 string and stored in a field “photo”. Since the hidden attribute is already used for storing JSON format, the field uses CSS to hide from users ie the users do not have to see the 64 string format.
File: submitjsonbuddy.php

<html>
<body>
<form action="addbuddy.php" method="post">
<p>Name: <input type="text" name="name" required
        onchange="setJsonData()"></p>
<p>E-mail: <input type="email" name="email"
        required placeholder="Enter a valid email address"
        onchange="setJsonData()"></p>
<p>Photo: <input type="text" name="photo" style="display:none;">
<input type="file" onchange="previewFile()">
<p><img src="" height="100" alt="Image preview..."></p>
<input type="hidden" name="jsondata" value="0">
<p><input type="submit" value='Submit' name="submit"></p>
</form>
<script>
//function to update the image preview
function previewFile() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
   reader.addEventListener("load", function () {
     preview.src = reader.result;
    var file = document.querySelector('input[type=file]').files[0];
    document.getElementsByName("photo")[0].value = preview.src;    
    setJsonData();
   }, false);
  if (file) {
    reader.readAsDataURL(file);
  }
}
function setJsonData(){
        var jsondata= formToJson(document.forms[0]);
        document.getElementsByName("jsondata")[0].value = jsondata;
        
}
function formToJson(form) {
    if (!form || form.nodeName !== "FORM") {
        return
    }
    var i, j, q = [];
   
    for (i = form.elements.length - 1; i >= 0; i = i - 1) {
        if (form.elements[i].name === "") {
            continue
        }
        switch (form.elements[i].nodeName) {
            case "INPUT":
                switch (form.elements[i].type) {
                        case "hidden": break;
                    case "text":
                    case "email":
                    case "password":
                    case "button":
                    case "reset":
                    case "submit":
                    q.push('"' + form.elements[i].name + '":"' + (form.elements[i].value) + '"');
                        break;
                    case "checkbox":
                    case "radio":
                        if (form.elements[i].checked) {
                          q.push('"' + form.elements[i].name + '":"' + (form.elements[i].value) + '"')
                        }
                        break;
                    case "file":
                        break
                }
                break;
            case "TEXTAREA":
            q.push('"' + form.elements[i].name + '":"' + (form.elements[i].value) + '"');
                break;
            case "SELECT":
                switch (form.elements[i].type) {
                    case "select-one":
                    q.push('"' + form.elements[i].name + '":"' + (form.elements[i].value) + '"');
                        break;
                    case "select-multiple":
                        for (j = form.elements[i].options.length - 1; j >= 0; j = j - 1) {
                            if (form.elements[i].options[j].selected) {
                              q.push('"' + form.elements[i].name + '":"' + (form.elements[i].options[j].value) + '"')
                            }
                        }
                        break
                }
                break;
            case "BUTTON":
                switch (form.elements[i].type) {
                    case "reset":
                    case "submit":
                    case "button":
                    q.push('"' + form.elements[i].name + '":"' + (form.elements[i].value) + '"');
                        break
                }
                break
        }
    }
    var jsonformat = "{" + q.toString() + "}";
    return jsonformat
};
</script>
</body>
</html>
OUTCOME.

REFERENCES

The codes for function previewFile() were modified from the original script published at https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL 
The codes for function formToJson() were modified from the original script published at http://www.bulgaria-web-developers.com/projects/javascript/serialize/ 

.

No comments:

Post a Comment

Labels