mardi 20 octobre 2020

Saving JSON data to JSON file using AJAX and PHP

I need your help to save the inputted data to JSON File. When I refresh the browser the inputted data is gone because it is still not added to the JSON File.

My JSON File looks like this (todo.json):

[
        {
               "task": "get milk",
               "who": "Scott",
               "dueDate": "today",
               "done": false
        },

        {
               "task": "get broccoli",
               "who": "Elisabeth",
               "dueDate": "today",
               "done": false
        }
]

My PHP File (save.php):

<?php 
if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
    function strip_slashes($input)
    {
        if (!is_array($input))
        {
            return stripslashes($input);
        }
        else
        {
            return array_map('strip_slashes', $input);
        }
    }
    $_GET = strip_slashes($_GET);
    $_POST = strip_slashes($_POST);
    $_COOKIE = strip_slashes($_COOKIE);
    $_REQUEST = strip_slashes($_REQUEST);
}
function customError($errno, $errstr)
{
    echo "<b>Error:</b> [$errno] $errstr<br>";
    echo "Ending Script";
    die("Ending Script");
}
set_error_handler("customError");
$myData = $_GET["data"];
$myFile = "todo.json";
$fileHandle = fopen($myFile, "w");
fwrite($fileHandle, $myData);
fclose($fileHandle); 
?>

I Use AJAX to save the data.

My JavaScript File (todo.js):

function getFormData() {
    var task = document.getElementById("task").value;
    if (checkInputText(task, "Please enter a task")) return;
    var who = document.getElementById("who").value;
    if (checkInputText(who, "Please enter a person to do the task")) return;
    var date = document.getElementById("dueDate").value;
    if (checkInputText(date, "Please enter a due date")) return;
    console.log("New task: " + task + ", for: " + who + ", by: " + date);
    var todoItem = new Todo(task, who, date);
    todos.push(todoItem);
    addTodoToPage(todoItem);
    saveTodoData();
}

function saveTodoData() {
    var todoJSON = JSON.stringify(todos);
    var request = new XMLHttpRequest();
    var URL = "save.php?data=" + encodeURI(todoJSON);
    request.open("GET", URL);
    request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    request.send();
}

Here is the output on the browser:

enter image description here

1 commentaire: