I used jQuery to read from a json file, but when I try to write it to the same file, it won't work.
Here's the code:
$.getJSON(src,function(data){
var about= data.abouttext;
var mail= data.mail;
var phone = data.phone;
$("#about_ta").val(about);
$("#mail_ta").val(e);
$("#phone_ta").val(mp);
$("#wizard_tabs_edit").show();
$("#mask_edit").show();
$("#edit_save").on("click",function() {
data.abouttext = $("#about_ta").val();
data.mail = $("#mail_ta").val();
data.phone = $("#phone_ta").val();
$.ajax({
url: src,
type: "POST",
data: data,
contentType: "application/json",
success: function(response){
alert("aaa");
}
});
$("#wizard_tabs_edit").hide();
$("#mask_edit").hide();
});
});
src is the path to the file (working at the $.getJSON), and it's giving me the alert "aaa" when AJAX succeeds.
But still, the JSON file remains the same.
The only way is to use php or any other backend coding language that can handle the file manipulation for you. Below is an example if you use php5 so you can have a clue:
<?php
// Specify filename
$filename = 'myJsonFile.json';
// Read data transforming them to an array
$data = json_decode(file_get_contents($filename), true);
// Push to the array a new pair
array_push($data, ['key' => 'value']);
// Open file for writing
$file = fopen($filename, 'w');
// Write data as json
fwrite($file, json_encode($data));
// Close file
fclose($file);
?>
Related
I'm trying to provide data to my MYSQL Database using Ajax, however, for some reason my PHP file is not reading the JSON array that I post to the file. Within the array I also have a file to store an image on my server as well as my database.
Javascript file
$(document).ready(function(){
// Give Data to PHP
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
//formData.append('tax_file', $('input[type=file]')[0].files[0]
var img = $('input[name=img]').prop('files')[0];
var name = img.name,
tmp = img.tmp_name,
size = img.size,
form = $('input[name=form-submit]').val(),
myName = $('input[name=my-name]').val(),
desc = $('input[name=description]').val();
// document.write(name + tmp + size);
var formData = {
'form-submit' : form,
'my-name' : myName,
'description' : desc,
'img' : name,
'tmp_name' : tmp,
'size' : size
};
// document.write(JSON.stringify(formData));
console.log(formData);
// process the form
$.ajax({
url : 'insert-bio.php', // the url where we want to POST
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
data : formData, // our data object
processData : false,
contentType : false,
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
My PHP file
include('../db.php');
$conn = new Database();
echo explode(",", $_POST['data']);
if(isset($_POST['form-submit'])){
// text data
$name = strip_tags($_POST['my-name']);
$desc = strip_tags($_POST['description']);
// picture stuff
$file = rand(1000,100000)."-".$_FILES['img']['name'];
$file_loc = $_FILES['img']['tmp_name'];
$file_size = $_FILES['img']['size'];
$file_type = $_FILES['img']['type'];
// folder for profile pic
$folder = "bio-pic/";
// new file size in KB
$new_size = $file_size/1024;
// make file name in lower case
$new_file_name = strtolower($file);
// final pic file
$final_file=str_replace(' ','-',$new_file_name);
// mysql query for form data
if(move_uploaded_file($file_loc,$folder.$final_file)){
$sql="INSERT INTO bio(img, name, description) VALUES('$final_file', '$name', '$desc')";
$conn->query($sql);
}
} else {
echo "Need data";
}
$query = $conn->query("SELECT * FROM bio");
$results=$query->fetchAll(PDO::FETCH_ASSOC);
$parse_bio_json = json_encode($results);
file_put_contents('bio-DATA.json', $parse_bio_json);
echo $parse_bio_json;
The console shows that I have made contact with my PHP file, but it simply has not read any data.
The error on the PHP file:
Notice: Undefined index: data in /Applications/XAMPP/xamppfiles/htdocs/WEBSITE/BIO/insert-bio.php on line 8
Notice: Array to string conversion in /Applications/XAMPP/xamppfiles/htdocs/WEBSITE/BIO/insert-bio.php on line 8 ArrayNeed data[]
I had the same issue back in the day. After doing lots of research I found out that JSON cannot have a property that holds a file value. However, you can follow this example. It worked great for me. Hope it helps :)
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
PHP
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
Credit goes to -> jQuery AJAX file upload PHP
When I want to printout the output of jQuery AJAX, which has been recived from server. It doesn't show the right charset. What I want exactly is to get š instead I am getting ? or without using utf8_decode() when sending data from server, I get ĹĄ. All files script.js and server php proceed.php are saved in UTF-8 and set in UTF-8. Database is set to UTF-8 as well. All other request from database give the right charset. I've tried most of the things.
In .js file for AJAX:
$.ajaxSetup({
url: "proceed.php", //file to procces data
ContentType : 'charset=UTF-8', // tried here
global: false,
type: "POST",
dataType: "html" // change to text/html, application/text doesnt work at all
});
In .php file:
mysql_query("SET NAMES utf8");
$output = utf8_decode($sql_result);
All possible combinations.
CODE:
PHP
if(!empty($_POST['select_had'])){
$zem = $_POST['select_had'];
$vysledek = mysql_query("SELECT typ_hadanky, jazyk FROM hlavolam RIGHT JOIN hadanka ON hlavolam.id_hlavolamu=hadanka.id_hlavolamu WHERE zeme_puvodu='$zem'");
$out = "";
while ($zaznam = mysql_fetch_array($vysledek)) {
$zaz = $zaznam['jazyk'];
$out .= "<option>".$zaz."</option>";
}
$vys = utf8_decode($out);
echo $vys;
}
jQuery:
$("#sel_had_zem").change(function(){
var select_had = $("#sel_had_zem option:selected").text();
$.ajax({
data:{'select_had':select_had},
success: function(data){
$("#sel_had_jaz option").nextAll().remove();
$("#sel_had_jaz").append(data);
},
error: function(){
alert('No server response');
}
});
});
I am trying to save a json string from a javascript file to a local file on the server using PHP, however, my json file is not being modified at all.
Here is my Javascript:
function saveToFile(data){
jsonString = JSON.stringify(data);
$.ajax({
url: 'php/save.php',
data : jsonString,
type: 'POST'
});
}
Note that jsonString is a valid variable, and i can log it correctly into the console.
Here is my PHP:
<?php
$data = $_POST['jsonString'];
$f = fopen("../website-contents.json", "w") or die("fopen failed");
fwrite($f, $data) or die("fwrite failed");
fclose($f);
?>
Note that even tests trying to save "Hello World" to "test.txt" don't work, or through errors.
Finally, here is my folder structure:
Here is your solution.
Js code
function saveToFile(data){
jsonString = JSON.stringify(data);
$.ajax({
url: 'php/save.php',
data : {'jsonString':jsonString},
type: 'POST'
});
}
php code.
$data = $_POST['jsonString'];
//set mode of file to writable.
chmod("../website-contents.json",0777);
$f = fopen("../website-contents.json", "w+") or die("fopen failed");
fwrite($f, $data);
fclose($f);
I agree with the comments pointing out you must have a permission problem. However, it will not work after you have corrected this problem either. You have
$data = $_POST['jsonString'];
but where do you set a key called jsonString? Use
function saveToFile(data){
var jsonString = JSON.stringify(data);
$.post("php/save.php", {
jsonString: jsonString
})
}
instead.
I'm using pdfmake to create my pdf and while it allows the user to open the pdf directly or download it to their computer, I'm not sure how I would go about generating the pdf and saving it to my server's file system.
From what I understand, there are plenty of security measures not allowing javascript to save data to file(s), so would sending it to my php backend be the only choice ? and how would i go about doing that ?
Thanks !
(untested)
PHP:
<?
// pull the raw binary data from the POST array
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
// decode it
$decodedData = base64_decode($data);
// print out the raw data,
echo ($decodedData);
$filename = "test.pdf";
// write the data out to the file
$fp = fopen($filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>
JS:
var docDefinition = {
content: 'This is an sample PDF printed with pdfMake'
};
pdfMake.createPdf(docDefinition).getBuffer(function(buffer) {
var blob = new Blob([buffer]);
var reader = new FileReader();
// this function is triggered once a call to readAsDataURL returns
reader.onload = function(event) {
var fd = new FormData();
fd.append('fname', 'test.pdf');
fd.append('data', event.target.result);
$.ajax({
type: 'POST',
url: 'upload.php', // Change to PHP filename
data: fd,
processData: false,
contentType: false
}).done(function(data) {
// print the output from the upload.php script
console.log(data);
});
};
// trigger the read from the reader...
reader.readAsDataURL(blob);
});
Upload and receive code from How can javascript upload a blob?.
I'm using an audio recorder from this place
http://webaudiodemos.appspot.com/AudioRecorder/index.html,
but I instead of saving the file locally I would like to upload it back to the server. My best shot was to try to modify the Recorder.setupDownload function in recording.js script to pass the blob it creates to a simple upload PHP script I found here:
<?php
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['recording']['name'];
$file_size =$_FILES['recording']['size'];
$file_tmp =$_FILES['recording']['tmp_name'];
$file_type=$_FILES['recording']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$extensions = array("wav");
if(in_array($file_ext,$extensions )=== false){
$errors[]="extension not allowed, please choose wav file."
}
if($file_size > 2097152){
$errors[]='File size under 20MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
?>
And I'm tring it using a jquery call,
$.ajax({
type: "POST",
url: "../scripts/Single-File-Upload-With-PHP.php",
data: blob
});
But I'm obviously doing something wrong. The original PHP script has a form in it
used for input, which I commented out trying to call the php code directly.
So my questions would be;
how to modify the Recorder.setupDownload to upload the file to a
designated folder?
how to report back when something goes wrong?
Or alternatively, is there a more elegant solution?
Edit: Regarding what's in the blob
This is how the blob is being defined in recorder.js:
worker.onmessage = function(e){
var blob = e.data;
currCallback(blob);
}
As to my understanding it is created with methods listed in recorderWorker.js (link in comments), and it should contain simply a wav file.
I dont think you should create the blob in the worker, but I had a similar setup (actually based on the same example) where I retrieved the samplebuffers from the worker and save them into the m_data fields of an AudioMixer class that did some stuff to the recording, then:
//! create a wav file as blob
WTS.AudioMixer.prototype.createAudioBlob = function( compress ){
// the m_data fields are simple arrays with the sampledata
var dataview = WTS.AudioMixer.createDataView( this.m_data[ 0 ], this.m_data[ 1 ], this.m_sampleRate );
return( new Blob( [ dataview ], { type:'audio/wav' } ) );
}
WTS.AudioMixer.createDataView = function( buffer1, buffer2, sampleRate ){
var interleaved = WTS.AudioMixer.interleave( buffer1, buffer2 );
// here I create a Wav from the samplebuffers and return a dataview on it
// the encodeWAV is not provided..
return( WTS.AudioMixer.encodeWAV( interleaved, false, sampleRate ) );
}
then to send it to the server
var blob = this.m_projectView.getAudioEditView().getAudioMixer().createAudioBlob();
if( blob ){
//! create formdata (as we don't have an input in a DOM form)
var fd = new FormData();
fd.append( 'data', blob );
//! and post the whole thing #TODO open progress bar
$.ajax({
type: 'POST',
url: WTS.getBaseURI() + 'mixMovie',
data: fd,
processData: false,
contentType: false
} );
}
and I had a node server running where the blob was sent to and could be picked up directly as a wav file, using the express node module:
var express = require( 'express' );
// we use express as app framework
var app = express();
/** mixMovie expects a post with the following parameters:
* #param 'data' the wav file to mux together with the movie
*/
app.post( '/mixMovie', function( request, response ){
var audioFile = request.files.data.path;
....
} );
hope this helps..
Jonathan
In the end this worked nicely for me:
recorder.js:
$.ajax(
{
url: "./scripts/upload.php?id=" + Math.random(),
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(data){
alert('Your message has been saved. \n Thank you :-)');
}
});
And the upload script itself:
<?php
if(isset($_FILES['data']))
{
echo $_FILES['data']["size"];
echo $_FILES['data']["type"];
echo $_FILES['data']["tmp_name"];
$name = date(YmdHis) . '.wav';
move_uploaded_file($_FILES['data']["tmp_name"],"../DEST_FOLDER/" . $name);
}
?>