Save data from modal form using AJAX - php

I would like to be able to save the data I entered on a modal form to a file and return the data into an alert after submission.
This is the current AJAX I have.
$("#submit").click(function(){
$.ajax({
type: "POST",
url: "save.php",
data: $('#form1').serialize(),
success: function(r){
alert (r);
return false;
},
dataType: "html"
});
$('.modal').modal('show');
});
If you need to see save.php, here it is:
<?php
// check if a form was submitted
if( !empty( $_POST ) ){
// convert form data to json format
$data = array(
"name" => $_POST['name1'],
"branch_address" => $_POST['bAddress1'],
"officer_in_charge" => $_POST['officer1'],
"contact_number" => $_POST['contactN1']
); //processes the fields on the form
$json = json_encode( $data );
$file = 'entries.json';
// write to file
file_put_contents( $file, $json, FILE_APPEND);
?>

You just need to echo the json data from the PHP file, like this:
$json = json_encode( $data );
$file = 'entries.json';
// write to file
file_put_contents( $file, $json, FILE_APPEND);
echo $json;
This is how data is returned via ajax - you simply echo it out, then it should be captured by the script as the variable r in this case.

File save.php
<?php
// check if a form was submitted
if( !empty( $_POST ) ){
// convert form data to json format
$data = array(
"name" => $_POST['name1'],
"branch_address" => $_POST['bAddress1'],
"officer_in_charge" => $_POST['officer1'],
"contact_number" => $_POST['contactN1']
); //processes the fields on the form
$json = json_encode( $data );
$file = 'entries.json';
// write to file
file_put_contents( $file, $json, FILE_APPEND);
echo $json;
?>

Use echo $json; after the line file_put_contents( $file, $json, FILE_APPEND);

Related

PHP writes null to JSON file

I've seen similar posts to this question but I can't seem to figure it out. I have a small PHP script that reads and writes form input to a JSON file, like this –
$file = 'data.json';
$arr_data = array();
$formdata = array(
'name' => strip_tags( trim($_POST['formName']) ),
'email' => $email,
'phone' => strip_tags( trim($_POST['formPhone']) ),
'message' => strip_tags( trim($_POST['formMessage']) )
// also tested this just using reg strings
);
$jsondata = file_get_contents($file);
//var_dump($jsondata); returns whatever string content is in the file, so seems to work
$arr_data = json_decode($jsondata, true);
array_push($arr_data, $formdata);
//var_dump($arr_data); returns NULL, not sure what happens here
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents($file, $jsondata);
Any ideas? Using PHP 5.5.9, checked that files are writeable. Both files have UTF8 encoding.
json_decode() will return NULL if the input is blank. Try this to ensure your $arr_data is an array...
$arr_data = json_decode($jsondata, true);
if ($arr_data === null) {
$arr_data = [];
}
maybe you want this code
<?php
$file = 'data.json';
$email='your mail info';
$arr_data = array();
$formdata = array(
'name' => strip_tags( trim($_POST['formName']) ),
'email' => $email,
'phone' => strip_tags( trim($_POST['formPhone']) ),
'message' => strip_tags( trim($_POST['formMessage']) )
// also tested this just using reg strings
);
$jsondata = file_get_contents($file);
//var_dump($jsondata); returns whatever string content is in the file, so seems to work
$arr_data = json_decode($jsondata, true);
// I added for if data.json is null to empty array
$arr_data = is_null($arr_data)?array():$arr_data;
array_push($arr_data, $formdata);
//var_dump($arr_data); returns NULL, not sure what happens here
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents($file, $jsondata);
?>
others
you should change your code to keep post data not null or default values and pay attention to file_get_contents method about file length

Accessing POST parameter with file upload in PHP

Trying to access the POST parameter passed with image uploading. When I print $_POST, the output is as follows:
array (
'%entity' => 'org.apache.http.client.entity.UrlEncodedFormEntity#532d2d84',
)
The PHP code is as follows:
$data = file_get_contents($_FILES['source']['tmp_name']);
$image = imagecreatefromstring( $data );
$ifp = fopen( '1.png', "wb" );
fwrite( $ifp, $data);
fclose( $ifp );
echo '<pre>';
print_r($POST);
User id is sent along with the file in POST request.
How to access the USERID which is passed with the file?
In your output you have listed key => value. You have to use the key part on $_POST array.
Just try with:
$_POST['%entity']

functions.php script breaks when variable isn't hard coded

I have written a jQuery script that takes a JSON encoded list produced with this function is run in my theme's functions.php and creates a playlist for my jPlayer. However, the script only works when the $file variable is hard coded (for example, OH0400). But I need it to pick up the $file variable based on the page being loaded. But when I switch to this method (using URL), the script says the JSON is null.
I've run the script in multiple ways and the output between the hard coded $file and the variable based $file appear to be the same. Why do I get null when I make the switch?
Here's the PHP in my theme functions.php.
function MyjPlayerList(){
$url = explode( '/', $_SERVER['REQUEST_URI'] );
$file = strtoupper($url[2]);
//$file = 'OH0400';
$filename = '/dir/oralhistory/mp3files/'.$file.'*.mp3';
$FILES = glob( $filename );
foreach( $FILES as $key => $mp3 ) {
$mp3 = str_replace( '/dir/oralhistory/mp3files/', '',$mp3);
$FILE_LIST[ $key ][ 'title' ] = $mp3;
$FILE_LIST[ $key ][ 'mp3' ] = 'http://websiteurl.org/mp3files/'.$mp3;
}
$myjplayerdata = json_encode( $FILE_LIST );
header ( 'Content-type: application/json' );
echo $myjplayerdata;
exit;
die();
};
Here is my javascript:
ajax_player = function() {
jQuery('div#player').load('/js/player.html' , function() {
var cssSelector= {
jPlayer: "#jquery_jplayer_1",
cssSelectorAncestor: "#jp_container_1"
};
var playlist = [];
var options = {
swfPath: "/js/Jplayer.swf",
supplied: "mp3",
smoothPlayBar: true,
keyEnabled: true
};
var myPlaylist = new jPlayerPlaylist(cssSelector, playlist, options);
jQuery.ajax({
url: "/wp-admin/admin-ajax.php" ,
type: "POST",
dataType: "text json",
data: { action: "MyjPlayerList"},
success:(function(data) {
jQuery.each(data, function(index, value){
myPlaylist.add(value); // add each element in data in myPlaylist
console.log(data);
})
})//function (data) close
})//ajax close
})//jquery.load
}//ajax_player
Yes, check the character encoding you're using. That could be the problem.
thanks to the debugging of Marc,turns out that what I get when i run the script in page & what i get when I call the script w/ javascript are different. it's trying to glob admin-ajax.php instead of the URL.

Trying to save base64 (image) file to server, it's empty

I'm trying to save a canvas image to a folder in my server however the file is empty upon inspection. I'm using AJAX to pass the encoded data to my php script, and then the php script is saving it to the server, empty.
This is the code I have:
JS/AJAX:
function convertCanvasToImage(thecanvas) {
var ajax = new XMLHttpRequest();
ajax.open("POST",'testSave.php',false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(canvasData);
}
PHP (testSave.php):
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
$filteredData=substr($imageData, strpos($imageData, ",")+1);
$unencodedData= base64_decode($filteredData);
//echo "unencodedData".$unencodedData;
$fp = fopen( 'test.png', 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
Thanks for any help in advance!
You're missing a line in your function to convert the <canvas> to data using the .toDataURL() function.
function convertCanvasToImage( thecanvas ) {
var canvasData = thecanvas.toDataURL( 'image/png' ), //add this
ajax = new XMLHttpRequest();
ajax.open( 'POST', 'testSave.php', false );
ajax.setRequestHeader( 'Content-Type', 'application/upload' );
ajax.send( canvasData );
};
var thecanvas = document.getElementById( 'canvasId' );
convertCanvasToImage( thecanvas );

Writing JSON object to .json file on server

I'm trying to write my JSON object to a .json file on the server. The way I'm doing this now is:
JavaScript:
function createJsonFile() {
var jsonObject = {
"metros" : [],
"routes" : []
};
// write cities to JSON Object
for ( var index = 0; index < graph.getVerticies().length; index++) {
jsonObject.metros[index] = JSON.stringify(graph.getVertex(index).getData());
}
// write routes to JSON Object
for ( var index = 0; index < graph.getEdges().length; index++) {
jsonObject.routes[index] = JSON.stringify(graph.getEdge(index));
}
// some jQuery to write to file
$.ajax({
type : "POST",
url : "json.php",
dataType : 'json',
data : {
json : jsonObject
}
});
};
PHP:
<?php
$json = $_POST['json'];
$info = json_encode($json);
$file = fopen('new_map_data.json','w+');
fwrite($file, $info);
fclose($file);
?>
It is writing fine and the information seems to be correct, but it is not rendering properly. It is coming out as:
{"metros":["{\\\"code\\\":\\\"SCL\\\",\\\"name\\\":\\\"Santiago\\\",\\\"country\\\":\\\"CL\\\",\\\"continent\\\":\\\"South America\\\",\\\"timezone\\\":-4,\\\"coordinates\\\":{\\\"S\\\":33,\\\"W\\\":71},\\\"population\\\":6000000,\\\"region\\\":1}",
... but I'm expecting this:
"metros" : [
{
"code" : "SCL" ,
"name" : "Santiago" ,
"country" : "CL" ,
"continent" : "South America" ,
"timezone" : -4 ,
"coordinates" : {"S" : 33, "W" : 71} ,
"population" : 6000000 ,
"region" : 1
} ,
Why am I getting all of these slashes and why it is all on one line?
You are double-encoding. There is no need to encode in JS and PHP, just do it on one side, and just do it once.
// step 1: build data structure
var data = {
metros: graph.getVerticies(),
routes: graph.getEdges()
}
// step 2: convert data structure to JSON
$.ajax({
type : "POST",
url : "json.php",
data : {
json : JSON.stringify(data)
}
});
Note that the dataType parameter denotes the expected response type, not the the type you send the data as. Post requests will be sent as application/x-www-form-urlencoded by default.
I don't think you need that parameter at all. You could trim that down to:
$.post("json.php", {json : JSON.stringify(data)});
Then (in PHP) do:
<?php
$json = $_POST['json'];
/* sanity check */
if (json_decode($json) != null)
{
$file = fopen('new_map_data.json','w+');
fwrite($file, $json);
fclose($file);
}
else
{
// user has posted invalid JSON, handle the error
}
?>
Don't JSON.stringify. You get a double JSON encoding by doing that.
You first convert your array elements to a JSON string, then you add them to your full object, and then you encode your big object, but when encoding the elements already encoded are treated as simple strings so all the special chars are escaped. You need to have one big object and encode it just once. The encoder will take care of the children.
For the on row problem try sending a JSON data type header: Content-type: text/json I think (didn't google for it). But rendering will depend only on your browser. Also it may be possible to encode with indentation.
Probably too late to answer the question. But I encountered the same issue. I resolved it by using "JSON_PRETTY_PRINT"
Following is my code:
<?php
if(isset($_POST['object'])) {
$json = json_encode($_POST['object'],JSON_PRETTY_PRINT);
$fp = fopen('results.json', 'w');
fwrite($fp, $json);
fclose($fp);
} else {
echo "Object Not Received";
}
?>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js" ></script>
</head>
<body>
<?php
$str = file_get_contents('data.json');//get contents of your json file and store it in a string
$arr = json_decode($str, true);//decode it
$arrne['name'] = "sadaadad";
$arrne['password'] = "sadaadad";
$arrne['nickname'] = "sadaadad";
array_push( $arr['employees'], $arrne);//push contents to ur decoded array i.e $arr
$str = json_encode($arr);
//now send evrything to ur data.json file using folowing code
if (json_decode($str) != null)
{
$file = fopen('data.json','w');
fwrite($file, $str);
fclose($file);
}
else
{
// invalid JSON, handle the error
}
?>
<form method=>
</body>
data.json
{
"employees":[
{
"email":"11BD1A05G9",
"password":"INTRODUCTION TO ANALYTICS",
"nickname":4
},
{
"email":"Betty",
"password":"Layers",
"nickname":4
},
{
"email":"Carl",
"password":"Louis",
"nickname":4
},
{
"name":"sadaadad",
"password":"sadaadad",
"nickname":"sadaadad"
},
{
"name":"sadaadad",
"password":"sadaadad",
"nickname":"sadaadad"
},
{
"name":"sadaadad",
"password":"sadaadad",
"nickname":"sadaadad"
}
]
}

Categories