I made an HTML form that sends the data to JSON, but I experienced a problem with code I took from a tutorial. It makes a new JSON file every time I submit a new form. How to make it so it adds the data to it, not rewrite it?
This is the PHP code I'm using
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
function get_data() {
$datae = array();
$datae[] = array(
'Name' => $_POST['name'],
'Strategy' => $_POST['strategy'],
'Teams' => $_POST['team'],
);
return json_encode($datae);
}
$name = "strategies";
$file_name = $name . '.json';
if(file_put_contents(
"$file_name", get_data())) {
echo $file_name .' file created';
}
else {
echo 'There is some error';
}
}
?>
Related
I have an HTML page which, after being filled up, needs to collect whatever data the user imputs and place it into a template document, which then needs to be converted into a pdf file and sent to the user to be printed. Does anyone have a tutorial for something similar to this? I have tried to find my way around with php and json files but i keep getting stuck at a certain point and i can't figure out an answer.
Edit: this is an example i've tried, to send stuff into a json file, but all it does is open a webpage with half the code on it:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
function get_data() {
$name = $_POST['name'];
$file_name='StudentsData'. '.json';
if(file_exists("$file_name")) {
$current_data=file_get_contents("$file_name");
$array_data=json_decode($current_data, true);
$extra=array(
'Name' => $_POST['name'],
'Branch' => $_POST['branch'],
'Year' => $_POST['year'],
);
$array_data[]=$extra;
echo "file exist<br/>";
return json_encode($array_data);
}
else {
$datae=array();
$datae[]=array(
'Name' => $_POST['name'],
'Branch' => $_POST['branch'],
'Year' => $_POST['year'],
);
echo "file not exist<br/>";
return json_encode($datae);
}
}
$file_name='StudentsData'. '.json';
if(file_put_contents("$file_name", get_data())) {
echo 'success';
}
else {
echo 'There is some error';
}
}
?>
And for clarification, i need whatever fields are being filled, sent to a file, pasted into a template, and that template sent back to the user.
I used fpdf.org for my website. It's free.
F from FPDF stands for Free: you may use it for any kind of usage and modify it to suit your needs
i am getting issue in PUT method. But everything is fine when i'm doing method post
here is some code :
<?php
header("Content-type: multipart/form-data");
include_once '../Database/database.php';
$status = array();
if(is_uploaded_file($_FILES["ImageKTP"]["tmp_name"]))
{
$tmp_file = $_FILES["ImageKTP"]["tmp_name"];
$ImageKTP = $_FILES["ImageKTP"]["name"];
$upload_dir = "./uploads/" .$ImageKTP;
if (move_uploaded_file($tmp_file, $upload_dir)) {
$status['kode']=1;
$status['deskripsi']='upload success';
$ImageKTP = $upload_dir;
} else {
$status['kode']=0;
$status['deskripsi']='upload failed';
$ImageKTP = null;
}
}
echo json_encode($status);
?>
But when i'm doing method put using application/json, the result is failed
<?php
header("Content-type: application/json");
include_once '../Database/database.php';
include_once '../Controller/users.php';
$data = json_decode(file_get_contents('php://input'), true);
$email=$data['email'];
$idcardnumber=$data['idcardnumber'];
$placeofbirth=$data['placeofbirth'];
$dateofbirth=$data['dateofbirth'];
$Gender=$data['Gender'];
$Religion=$data['Religion'];
$ImageKTP=$data['ImageKTP'];
$ImageSelfie=$data['ImageSelfie'];
$ImageFamilyMemberCard=$data['ImageFamilyMemberCard'];
$database = new Database();
$db = $database->getConnection();
$user = new Users($db);
$stmt = $user->UpdateProfile($email, $idcardnumber, $placeofbirth, $dateofbirth, $Gender, $Religion, $ImageKTP, $ImageSelfie, $ImageFamilyMemberCard);
if($stmt->rowCount() > 0){
// create array
$profile_arr=array(
"success" => 1,
"message" => "Successfully Update Profile!"
);
}
else{
$profile_arr=array(
"success" => 0,
"message" => "Update Profile Failed!",
);
}
print_r(json_encode($profile_arr));
?>
I still didnt find out how to solve this problem cause i want to update profile using method PUT include other value
The $_FILES array only works with POST requests. If you want to use PUT there are some configurations to the web server that need to be made first, you can find a detailed guide here.
so, I am working on a JSON file that should keep on incrementing IDs.
However I get stuck at id:0 and when I insert new data the old data will be replaced by the new one (it keeps id:0).
I am not entirely sure what code is related and what not, so I will post whatever I think should be related and if someone with more knowledge related to JSON could adjust (in case it needs any) it, I would appreciate it a lot.
The include database_json.php contains the following code:
$databaseFile = file_get_contents('json_files/database.json');
$databaseJson = json_decode($databaseFile, true);
$database = $databaseJson['data'];
// below starts a new page, the page that submits the form called saveJson.php
include_once('database_json.php');
$data = $_POST;
//Setup an empty array.
$errors = array();
if (isset($data)) {
$newExerciseData = $data;
$exerciseArray = $data['main_object'];
$databaseFile = 'json_files/database.json';
$textContent = file_get_contents($databaseFile);
$database = json_decode($textContent, true);
if ($data['id'] === 'new') {
if (count($database['data']) == 0) {
$ID = 0;
} else {
$maxID = max($database['data']);
$ID = ++$maxID["id"];
}
$newJsonFile = 'jsonData_' . $ID . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData = array(
'id' => $ID,
// a lot of variables that aren't related to the problem
);
$database['data'][] = $newArrayData;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
} else {
$index = array_search((int) $_POST['id'], array_column($database['data'], 'id'));
$correctJsonFile = 'json_files/jsonData_' . $_POST['id'] . '.json';
$newJsonFile = 'jsonData_' . $_POST['id'] . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData2 = array(
'id' => (int) $_POST['id'],
// more not related to problem variables
);
$database['data'][$index] = $newArrayData2;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE));
}
echo json_encode($newExerciseData, JSON_UNESCAPED_UNICODE);
}
EDIT: someone wanted me to post how the JSON itself looked like... so this is how it looks:
The file is called: database.json
{
"data":
[
{
"id":0,
"exercisetitle":"Test300520180924",
"exerciseWord":["huiswerk"],
"syllables":["Huis","werk"],
"file":"jsonData_.json",
"audio":null,"language":null
}
]
}
(do not mind the audio and language, that's something for later on.
The best I could do was this, yes I read the stuff about making a post and how to properly format stuff etc. but I people would often say I need to include certain code etc etc. and it mostly would turn out messy as hell, so I would rather have a bit too much code (the code I think is related) then not have enough.
Cheers!
by clicking on a button I am setting a variable in php using Ajax.
submitInfo(var1);
function submitInfo(var1)
{
$.ajax({
type: "POST",
url: "js/info.php",
data: {Info:var1},
success: function (result)
{
alert(result);
}
});
}
in my php code, How can I save "var1" in a text file? I have used this to save variable in a text file but it is not saving anything there:
<?php
if (isset($_POST['var1']))
{
echo $_POST['var1'];
}
$file = fopen("js/test.txt","w");
echo fwrite($file,$var1);
fclose($file);
?>
The first issue is that in your JQuery you actually assigning the var1 variable to 'Info'
so the $_POST array will contain this rather than var1.
You then only want to manage your attempts to write to the file in order to get nicer, more user friendly error messages which will give you something nicer to send back and help you if debug any other problems.
<?php
$var1 = "";
$filename = "js/test.txt";
// Get the correct $_POST object
if (isset($_POST['Info']) {
$var1 = $_POST['Info'];
}
// If the variable is not empty try to write your file
if (!empty($var1)) {
if(!$file = fopen($filename,"w")) {
$msg = "Cannot open file");
} else if (fwrite($file,$var1) === false) {
$msg = "Cannot write to file");
} else {
$msg => 'all was good'
}
fclose($file);
$result = array(
'error' => 'false',
'msg' => $msg
);
} else {
$result = array(
'error' => 'true',
'msg' => 'Info was empty'
);
}
// Send your message back
echo "{\"result\":".json_encode{$result)."}";
PS: Not tested this so fingers crossed there are no typos.
Try this:
<?php
if (isset($_REQUEST['Info'])){
$var1 = $_REQUEST['Info'];
$file = fopen("js/test.txt","w");
echo fwrite($file,$var1);
fclose($file);
}
?>
In cake php, is there anyway to set flash message in current page without losing form values.
Here an form is submitted, then we need to set a flash message in current page without losing form values. (No ajax /no Javascript is used)
Form Submitted goto php and set a flash message
Html
<div class="videos form">
<?php echo $this->Form->create('Video');?>
<fieldset>
<legend><?php __('Add Video'); ?></legend>
<?php
echo $this->Form->input('video', array('label' => false, 'div' => false,'type' => 'file','style' =>'height:25px'));
echo $this->Form->input('title');
echo $this->Form->input('name');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit', true));?>
</div>
PHP
function add()
{
if (!empty($this->data)) {
$file = $this->data['Video']['video'];
$destination = 'files/videos/';
$max_size = 100 * 1024 * 1024; //100 MB
$allowed_types = array('mp4','flv','WebM','3GPP','avi','wmv','FLV','MP4','AVI','MOV');
$status = $this->FileUpload->uploadFile($file, $destination, $max_size, $allowed_types, $filename);
if ($status == "SUCCESS") {
$userFile = $file['name'];
$extension = pathinfo($userFile, PATHINFO_EXTENSION);
$saveData = array(
'name' => $filename . '.' . $extension,
'path' => $destination
);
return $saveData;
} else {
// If this condition enters flash message is shown, but form values are lost
return $status;
}
}
}
When you set data to file after that line set:
$this->Session->setFlash(__('your message', true));
and where you want to show write in that view file:
<?php echo $this->Session->flash(); ?>
When you perform an action that renders a View, there is no return, so you should remove these lines:
return $saveData;
return $status;
To interact with the View and send variables, you use the set method and as in this case you need the form data, you must send the variable $this->data again:
$this->set('data', $this->data);
And as already reported, to set a flash message:
$this->Session->setFlash('foobar');
More information:
Controllers
set()