Reputation: 463
I have a html form which I can append using JavaScript, I use PHP to save the data to a JSON file. However, when I click the submit button while there is no form (not appended yet) it still saves data to the JSON file:
[{"language":null,"time_in_words":null,"time_hours":null,"time_mins":null,"audio":null}]
Is there a way to check if the form (or a div wrapped around the form) actually exists? (using PHP)
Edit: Here's my PHP for submitting the form and sending it to the JSON file
if(isset($_POST["submit"])){
$_POST = array_filter($_POST);
if(file_exists('data.json')){
$current_data = file_get_contents('data.json');
$array_data = json_decode($current_data, true);
$extra = array(
'language' => $_POST["language"],
'time_in_words' => $_POST['time_in_words'],
'time_hours' => $_POST["time_hours"],
'time_mins' => $_POST["time_mins"],
'audio' => $_POST["audio"],
);
$array_data[] = $extra;
$final_data = json_encode($array_data);
if(file_put_contents('data.json', $final_data)) {
$message = "Successfully saved";
echo "<script type='text/javascript'>alert('$message');</script>";
}
}
else
{
$error = "data.json does not exist";
echo "<script type='text/javascript'>alert('$error');</script>";
}
}
Upvotes: 0
Views: 1824
Reputation: 463
Thanks to ParantapParashar for helping me figure this out. =)
if(isset($_POST["language"])){
// *submit the form to the json file*
}
else {
// *tell the user to add an input field*
}
This checks if <input type="text" name="language" required>
has any value. If it doesn't exist, it has no value, so the outcome would be false.
If it does exist, it would still have no value, but since i gave the input element the "required" attribute it wouldn't let the user submit before the user gives it a value (by filling in the input field).
So when the user fills in the input field, the outcome would be true.
Upvotes: 1