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);
}
?>
Related
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';
}
}
?>
I m trying to upload a file and a thumb of that file (using the cropper v2.3.0).
This code work on all other browser but in safari it gives an error.
The problem describe as follow:
on safari browser on desktop when upload the file then the below error occurred and used other then safari browser there is no error and get success message.
I test both ways that first upload only the cropped image that is in base64
encode or also in blob as file with appending into formData but on both ways that error not resolved.
I also tried to upload the image only then error occurred sometimes or sometimes not.
if use cropper adjust then the error occurred (this is my assumption)
My js Code to submit the form
function addFile() {
$("#result").html("");
var myForm = $('#mainForm');
var formData = new FormData(myForm[0]);
$.ajax({
url: "action.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: formData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
dataType: "json",
success: function (data) // A function to be called if request succeeds
{
$("#result").html(data.response + " : " + data.message);
},
error: function (res) {
$("#result").html(res.responseText);
}
});
return false;
}
my action php code
<?php
$uploadThumbnailPath = "dir";
$thumbImgData = $_POST['thumbImg'];
$numberOfImages = 1;
$isImageUploaded = 0;
if ($thumbImgData != "") {
//thumbnail image uploading code
list($type, $thumbImgData) = explode(';', $thumbImgData);
list(, $thumbImgData) = explode(',', $thumbImgData);
$thumbImgData = base64_decode($thumbImgData);
$myTimeStamp = "thumbImg_" . time() . uniqid();
$displayImageName = $myTimeStamp . ".png";
$dir = $uploadThumbnailPath;
if (file_put_contents("$dir/$displayImageName", $thumbImgData)) {
$jpgFormatImageName = $myTimeStamp . ".jpg";
convertPNGtoJPG("$dir/$displayImageName", "$dir/$jpgFormatImageName", 238, 238, 238, 1);
if (file_exists("$dir/$displayImageName")) {
unlink("$dir/$displayImageName");
}
$isImageUploaded = 1;
}
} else {
$arrayResponse = array("response" => "thumbImg_BLANK", "message" => 'thumbImg_BLANK');
echo json_encode($arrayResponse);
exit;
}
for ($i = 1; $i <= $numberOfImages; $i++) {
if (isset($_POST["imgName$i"])) {
$itemImagesName = "";
} else {
$itemImagesName = $_FILES["imgName$i"]['name'];
}
if ($itemImagesName != "") {
$extension = pathinfo($itemImagesName, PATHINFO_EXTENSION);
$uploadNewFileNameWithoutExt = "image_" . md5($i . time());
$uploadDirPath = "dir/p/";
$uploadNewFileName[$i] = $uploadNewFileNameWithoutExt . '.' . $extension;
$uploadNewFileWithPathName = $uploadDirPath . $uploadNewFileName[$i];
$mesUpload = uploadImageFileOnServer("imgName$i", $allowedExts, $maxFileSize, $uploadNewFileWithPathName);
}
}
$itemImages = implode("#:#", $uploadNewFileName);
$thumbnailImageName = "default_thumbnail.png";
if ($isImageUploaded == 1) {
$thumbnailImageName = $jpgFormatImageName;
}
if ($mesUpload == "FILE_UPLOADED") {
$arrayResponse = array("response" => "OK", "message" => "OK UPLOAD SUCCESS");
echo json_encode($arrayResponse);
exit;
} else {
/* $mesUpload */
$arrayResponse = array("response" => "FILE_FAILED", "message" => "FAIL TO UPLOAD");
echo json_encode($arrayResponse);
exit;
}
?>
Here the screen shots of the error of that
this is image where the
screen shot 1
screen shot 2
Please help me to solving this issue. i am puzzled for this error and i have not getting any idea to resolved this problem.
If any one want to use i upload a sample code on the web click on below link
https://tamapev.000webhostapp.com/upload-img/
The issue is probbaly you sending the form data to the wrong page, first determine whether action.php is in the root directory or if it is in a directory called "upload-img". Then send the request to that given page.
Next for the error that says "An error occurred trying to load resource", to see what the actual error is, in your first screenshot there is a little button in the panel that says "Response", Click on it and change it to "JSON"
If "action.php" is in "upload-img" then you need to change
url: "action.php", to url: "/upload-img/action.php",
I am doing an ajax update. I just want a response of success or failure so I know how to handle some things in the front end. Problem is it isn't working. Brand new to all of this.
$('.delete-template-popup .confirm').on('click', function() {
var templateName = $('.loaded-template-name').html();
var templateArray = {};
templateArray.templateName = templateName;
var JSONObject = [templateArray];
var templateJson = JSON.stringify(JSONObject);
$.ajax({
url: 'http://localhost/ds-layouts/public/delete-template.php',
type: 'post',
data: {"templatePHP" : templateJson},
success: function(data) {
console.log(data)
if (data.status == "success") {
console.log(1)
}
// if (data.status == "success") {
// closePopup($('.delete-template-popup'));
// window.location.replace("http:////localhost/ds-layouts/public/manage-layouts.php");
// } else {
// $('.delete-template-popup .error').show().html('An error occurred processing your request. Please try again. If this error persists contact blah.');
// }
}
});
});
and the php
if ($flag) {
//mysqli_commit($connection);
if ($debug) {
echo "pass";
echo "\r\n";
}
//$_SESSION["message"] = "Template delete was successful.";
//header('Content-Type: application/json');
header('Content-Type: application/json; charset=UTF8');
echo json_encode(array('status' => 'success'));
} else {
if ($debug) {
echo "fail";
echo "\r\n";
}
//mysqli_rollback($connection);
// header('Content-Type: application/json');
// echo json_encode(array('status' => 'failure'));
}
So the deal is I am getting into the if block of the php statment fine. If I have the header part of the block I get all of my echo statements passed properly and I can read them in Chromes developer console. The moment I uncomment the header statement nothing works. This is for either one of $flag cases true or false.
I have this same type of script in another area and it works absolutely fine. Don't mind the comments. I was just commenting things out as a way to figure out where things were breaking. That is how I determened the header was causing it.
Maybe adding the dataType: "json", to your AJAX request object will help?
try this php
header('Content-Type: application/json'); //must be FIRST output.
if ($flag) {
//mysqli_commit($connection);
if ($debug) {
echo json_encode(array('debug' => 'pass'));
}
else
{
echo json_encode(array('status' => 'success'));
}
} else {
if ($debug) {
echo json_encode(array('debug' => 'fail'));
}
else
{
//mysqli_rollback($connection);
echo json_encode(array('status' => 'failure'));
}
}
I've changed the debug blocks to return json, since turning on debug will break the ajax anyway.
As the answer was posted as a comment I can't mark the answer as fixed. I am going to mark this answer as the what fixed the issue:
"The header must be before echo – user4035"
Thank you user4035 for letting me know about the header being before any echos aka before any printed form of html from the server...I should have known that.
I am trying to set up an AJAX file upload script with jQuery and JSON.
I have some experience with AJAX and jQuery, but have never used JSON in my life.
While going through this tutorial, I found that their method of retrieving uploaded files was to get all the files from the database.
This does not suit my current needs. This will be part of a form for writing articles to the database, so the script needs to work only with attachments associated with the article being created.
I basically had to create a DB table for attachment sessions which I use to determine the attachments that are currently being worked with.
This is fine, however, I now need a way to pass an extra variable for the session id to the jQuery script.
I have encoded the JSON data in my PHP script, but now how do I access the certain variable in the jQuery script? In the code below, I will indicate where I encoded the JSON data, and also where I would like to add that data in the jQuery script.
PS: This is in CodeIgniter.
This is the PHP script
function upload_file()
{
$status = '';
$msg = '';
$config = array(
'upload_path' => FCPATH.'attachments',
'allowed_types' => 'jpg|gif|png',
'min_height' => ($this->session->flashdata('img_min_height')) ? $this->session->flashdata('img_min_height') : 0,
'min_width' => ($this->session->flashdata('img_min_width')) ? $this->session->flashdata('img_min_width') : 0,
'max_height' => ($this->session->flashdata('img_max_height')) ? $this->session->flashdata('img_max_height') : 0,
'max_width' => ($this->session->flashdata('img_max_width')) ? $this->session->flashdata('img_max_width') : 0,
'max_size' => 300,
'encrypt_name' => TRUE
);
$this->load->library('upload', $config);
if(!$this->upload->do_upload('user_files')){
$status = 'error';
$msg = $this->upload->display_errors('', '');
} else {
$data = $this->upload->data();
$this->attachment->create($data);
if($this->attachment->error == NULL){
$status = "success";
$msg = "File uploaded.";
$session_id = $this->attachment->_session_id;
} else {
unlink($data['full_path']);
$status = "error";
$msg = $this->attachment->error;
$session_id = '';
}
}
#unlink($_FILES['user_files']);
echo json_encode(array('status' => $status, 'msg' => $msg, 'session_id' => $session_id )); **//I added the session id variable here.**
}
This is the jQuery script that gets the uploaded files:
function refresh_files()
{
$.get('./upload/files/') //The session ID should go at the end of this URL...
.success(function (data){
$('#files').html(data);
});
}
You simply add an extra parameter next to the url.
Reference: http://api.jquery.com/jquery.get/
$.get('./upload/files/', required_data_here)
.success(function (data){
$('#files').html(data);
});
Then in your server-side script:
<?php
var sess_id = $_GET['your_variable_here'];
?>
Here's an example from the reference:
$.get( "test.php", { name: "John", time: "2pm" } );
I am using Zend Framework, and to illustrate what is working I added the saveAction() to this post and it works flawlessly. It will animate and change the class as I want. The function upload instead only change the text and ignore the javascript. I can do alerts that works, however jquery is not possible. I get error saying that $ is undefined. How could it be undefined in 1 case and not the other?
I am catching the upload form with ajax and just throw it into the #savecontainer.
Hope there's a solution, it seems to be a tiny issue somewhere, but I can't find it on my own. Thank you.
it looks like this:
$(document).ready(function() {
$('#newsForm').ajaxForm({
target: '#savecontainer'
});
$('#uploadForm').ajaxForm({
target: '#savecontainer'
});
$("#btn_save").click(function () {
$('#newsForm').submit();
});
$("#btn_upload").click(function () {
$('#uploadForm').submit();
});
});
public function saveAction()
{
$this->_helper->layout->disableLayout();
$db = new Admin_Model_DbAccess();
if(isset($_POST['active']))
$_POST['active'] = 1;
else
$_POST['active'] = 0;
if($_POST['id'] == 0){
// If it is a new post
$data = array(
'header' => $_POST['header'],
'message' => $_POST['message'],
'date' => time(),
'user' => Zend_Auth::getInstance()->getStorage()->read()->id,
'image' => $_POST['image'],
'active' => $_POST['active'],
'category' => $_POST['category']
);
if($db->addNews($data)){
// set the css variables to saved
echo "<script type='text/javascript'>
$('#savecontainer').fadeOut(200).attr('class', 'savecontainer_success').fadeIn(400);
$('#news_id').attr('value', '".$db->lastInsertId()."');
$('#upload_box').show('slide', {direction: 'up'}, 500);
$('#news_id_upload').attr('value', '".$db->lastInsertId()."');
</script>";
echo "Status: Added.";
}else{
// set the css variables to failed
echo "<script type='text/javascript'>
$('#savecontainer').fadeOut(200).attr('class', 'savecontainer_fail').fadeIn(400);
</script>";
echo "Status: Error.";
}
}else{
$data = array(
'header' => $_POST['header'],
'message' => $_POST['message'],
'image' => $_POST['image'],
'active' => $_POST['active'],
'category' => $_POST['category']
);
$db = new Admin_Model_DbAccess();
if($db->updateNews($_POST['id'], $data)){
// set the css variables to saved
echo "<script type='text/javascript'>
$('#savecontainer').fadeOut(200).attr('class', 'savecontainer_success').fadeIn(400);
</script>";
echo "Status: Updated.";
}else{
// set the css variables to failed
echo "<script type='text/javascript'>
$('#savecontainer').fadeOut(200).attr('class', 'savecontainer_fail').fadeIn(400);
</script>";
echo "Status: Error.";
}
}
}
public function uploadAction(){
$this->_helper->layout->disableLayout();
if ($this->_request->isPost()) {
//Startup the adapter to upload
$adapter = new Zend_File_Transfer_Adapter_Http();
//Define the upload path
define('UPLOAD_NEWS_IMAGE_PATH', APPLICATION_PUBLIC_PATH. "/img/news/");
// Fixa upload path
$adapter->addValidator('Extension', false, array('jpg', 'jpeg' , 'gif' , 'png'))
->addValidator('Count', false , array( 'min' => 0, 'max' => 0));
$file = $adapter->getFileInfo();
$adapter->receive();
$messages = $adapter->getMessages();
if(isset($messages['fileCountTooMany']) && !isset($messages['fileExtensionFalse'])){
//If the file does exists (Everything went fine);
$fileinfo['ext'] = end(explode(".", $file['upload_0_']['name']));
$uploaded_filename = $_POST['id'].".".$fileinfo['ext'];
// Change name to id.jpg for example
move_uploaded_file($file['upload_0_']['tmp_name'], UPLOAD_NEWS_IMAGE_PATH.$uploaded_filename);
// resize to
$full_thumb = Butikadmin_Model_PhpThumbFactory::create(UPLOAD_NEWS_IMAGE_PATH.$uploaded_filename);
$full_thumb->resize(960, 500);
$id = $_GET['id'];
if($full_thumb->save(UPLOAD_NEWS_IMAGE_PATH.$uploaded_filename)){
// set the css variables to saved
echo "<script type='text/javascript'>
$('#savecontainer').fadeOut(200).attr('class', 'savecontainer_success').fadeIn(400);
$('#upload_box').fadeOut(500);
</script>";
echo "Status: Uploaded.";
}
}else{
// If the file is not right format
// set the css variables to saved
echo "<script type='text/javascript'>
$('#savecontainer').fadeOut(200).attr('class', 'savecontainer_fail').fadeIn(400);
</script>";
echo "Status: Error.";
}
}
}
why not using an ajax call instead of .submit?
and in the php code, remove the js record and return data (array or ojbect) from the function and handle it back in the js script with a callback function which return that data