I have a page which generates a chart. I have a button which generates a pdf report for it. I wanted to create an image of this chart and insert it into the pdf. To create the image, I use html2canvas and get the dataurl which I store in the localstorage.
chart.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#download').click(function() {
$.ajax({
type: "POST",
url: "pdfGen.php",
data: 'hello',
success: function(data) {
alert("hi");
}
});
});
}); //END $(document).ready()
</script>
<script>
//<![CDATA[
(function() {
window.onload = function(){
html2canvas(document.getElementById('chart'), {
"onrendered": function(canvas) {
var img = new Image();
img.onload = function() {
img.onload = null;
console.log(canvas.toDataURL("image/png"));
window.localStorage.setItem("imgURL", canvas.toDataURL("image/png"));
};
img.onerror = function() {
img.onerror = null;
if(window.console.log) {
window.console.log("Not loaded image from canvas.toDataURL");
} else {
//alert("Not loaded image from canvas.toDataURL");
}
};
img.src = canvas.toDataURL("image/png");
}
});
};
})();
//]]>
</script>
<body>
Report
..more code to generate the chart
</body>
The download button calls the pdfGen.php script which uses fpdf to generate a report.
pdfGen.php
<?php
echo $_POST['data']; //gives error
/*$pdf = new FPDF();
$pdf->AddPage();
//over here I want to add the image from the chart.php page whose data url is now in the localstorage.
..more code to generate report
$pdf->output();*/
?>
How do I get the image inside the php script? I try to make the ajax call but I get undefined index data in pdfGen.php script. I got the alert HI but could not get the data on the server.
It does not seem to work.
Your ajax call is wrong.
Your call should be like this to get value hello in data variable/key
$('#download').click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "pdfGen.php",
data: 'data=hello',
success: function(data) {
alert("hi");
}
});
});
To learn more about the jQuery Ajax refer this link.
Here is an example passing localstorage from js to php session, assume using jQuery as ajax requester.
Handle
In root, add file: retrieve.php (This will RETRIEVE AND SYNC localstorage from js with session from php)
<?php
session_start();
$key = 'my-car'; // Your localstorage key
$client = (isset($_GET[$key]) && $_GET[$key] !== 'null') ? $_GET[$key] : null;
$server = isset($_SESSION[$key]) ? $_SESSION[$key] : null;
$_SESSION[$key] = $client; // Now stored in php´s session variable $_SESSION['my-car']
echo $client === $server ? 'true' : 'false'; // Tells js to reload if data was not synced
Set
In your index.html / index.php add this script: (This will PASS localstorage to php and reload if not synced after php´s session data is set)
<?php
session_start(); // Dont forget this line
$key = 'my-car';
if (isset($_SESSION[$key]) && $_SESSION[$key] !== null) {
$car = json_decode($_SESSION[$key], true);
echo $car['name']; // Will print 'Tesla'
}
?>
<script>
// Set in JS
var key = '<?php echo $key; ?>';
window.localStorage.setItem(key, JSON.stringify({
name: 'Tesla'
})); // Set to whatever you want
var data = {};
data[key] = window.localStorage.getItem(key);
// Passes to PHP using GET
jQuery.get(
location.protocol + '//' + location.host + '/retrieve.php',
data
).done(function (synced) {
if (synced !== 'true') {
// If not synced, reload
location.reload();
// Caution! If it doesnt sync correctly, infinite loop may occure
}
});
</script>
Use
And last, passing session from PHP to localstorage in js ->
In ANY php file:
<?php
start_session();
$key = 'my-car';
if (isset($_SESSION[$key]) && $_SESSION[$key] !== null) {
// Print old value
$car = json_decode($_SESSION[$key], true);
echo $car['name']; // 'Tesla'
// Update object
$car['name'] = 'Honda';
$_SESSION[$key] = json_encode($car);
// Pass to js:
echo "<script>window.localStorage.setItem('" . $key . "', '" . $_SESSION[$key] . "');</script>";
// Prints the updated object with name 'Honda'
echo "<script>console.log(window.localStorage.getItem('" . $key . "'))";
}
Note: 'my-car' can be replaced with your own keys.
Related
i have a function that shows me if a file exists, if so he will return me the file path if it doesnt exist he will still give me the path so he can create the file:
function getnamechats($user1,$user2){
$filename1="chats/chat".$user1."&".$user2.".json";
$filename2="chats/chat".$user2."&".$user1.".json";
if (file_exists($filename1)) {
return $filename1;
}
else if (file_exists($filename2)) {
return $filename2;
}
else{ return $filename1;}
}
it works fine on creating/opening the file to write on it,ive tested a lot of times and my json file gets updated everytime:
function send_chat($nick,$chat){
global $userid;global $chatparse;
$heasda=getnamechats($userid,$chatparse);
$ok=$heasda;
// read/write
$filename = "$heasda";
$fopen = fopen($filename,"r");
$fgets = fgets($fopen);
fclose($fopen);
$decode = json_decode($fgets,true);
// limit 10
end($decode);
if(key($decode) >= 10){
array_shift($decode);
$new_key =10;
}
else{
$new_key = key($decode);
$new_key++;}
$format = array($nick,$chat);
$decode[$new_key] = $format;
$encode = json_encode($decode);
// write
$fopen_w = fopen($filename,"w");
fwrite($fopen_w,$encode);
fclose($fopen_w);
}
but in the function that opens/create it to read i get the following error the first variable is right(1) but the second one (suppost to be after the &) just doesnt work, and the error HTMLParagraphElement appears,example:
chats/chat1&[object HTMLParagraphElement].json
i then called again the getnamechats() function as soon as a new msg is triggered just to check if the file still exists, if it does, it will send me the variable $heasda to show_chat($heasda) and basically it will do the same as send_chat, but instead writing on it, it will read it:
function show_chat($heasda){
print_r($heasda);
$filename = $heasda;
$fopen = fopen($filename,"r");
$fgets = fgets($fopen);
fclose($fopen);
$decode = json_decode($fgets,true);
$val .= "<table id='table' class=\"table table-condensed\">";
foreach($decode as $post){
$val .= "<tr><td><b style=\"color:#{$post[0]}\">{$post[0]}</b>: {$post[1]}</td></tr>";}
$val .= "</table>";
return $val;
}
if(isset($_POST["chat"]) && $_POST["chat"] != ""){
$nick = $_SESSION['iduser'];
$chat = $_POST["chat"];
send_chat($nick,$chat);
}
if(isset($_GET["chat"]) && $_GET["chat"] != ""){
global $userid;global $chatparse;
$heasda=getnamechats($userid,$chatparse);
echo show_chat($heasda);
exit;
}
?>
As someone said it can be JavaScript heres the code too, ive read about it but i still dont understand properly:
function autoloadpage() {
$.ajax({
url: "?chat=1&chat-pars="+secnum,
type: "POST",
success: function(data) {
$("div#chat").html(data);
}
});
}
secnum is a DOM element, not the text inside it. You need to get the text.
You should also call encodeURIComponent in case it contains characters that have special meaning in a URL.
function autoloadpage() {
$.ajax({
url: "?chat=1&chat-pars="+encodeURIComponent(secnum.innerText),
type: "POST",
success: function(data) {
$("div#chat").html(data);
}
});
}
I am working on Tokbox video calling process. Now I am using the sample kit of Tokbox which is working properly but it is showing me all active user video.
but I need one user can video calling to another user.
I mean I need one to one video calling process. Is It possible in Tokbox. So please help to solve out it.
This is My code
use Slim\Slim;
use Gregwar\Cache\Cache;
use OpenTok\OpenTok;
if(!empty($userid))
{
$autoloader = __DIR__.'/../../../component/tokbox/vendor/autoload.php';
if (!file_exists($autoloader)) {
die('You must run `composer install` in the sample app directory');
}
require($autoloader);
// PHP CLI webserver compatibility, serving static files
$filename = __DIR__.preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']);
if (php_sapi_name() === 'cli-server' && is_file($filename)) {
return false;
}
// Initialize Slim application
$app = new Slim(array(
'templates.path' => __DIR__
));
// Intialize a cache, store it in the app container
$app->container->singleton('cache', function() {
return new Cache;
});
// Initialize OpenTok instance, store it in the app contianer
$app->container->singleton('opentok', function () {
return new OpenTok('***', '****');
});
// Store the API Key in the app container
$app->apiKey = '45833942';
$id=$this->uri->segment('3');
$urlname=$this->uri->segment('4');
// Configure routes
$app->get('/home/livechat/'.$id.'/'.$urlname.'/', function () use ($app) {
// If a sessionId has already been created, retrieve it from the cache
$sessionId = $app->cache->getOrCreate('sessionId', array(), function() use ($app) {
// If the sessionId hasn't been created, create it now and store it
$session = $app->opentok->createSession();
return $session->getSessionId();
});
// Generate a fresh token for this client
$token = $app->opentok->generateToken($sessionId);
/*$this->db->select('activemember');
$this->db->from('pshy_videocat');
$psychics=$this->db->get();
$totaluseractive= $psychics->row();
$totalactivevideouser=$totaluseractive->activemember;*/
?>
<input type="hidden" id="connectionCountField" value="0"></input>
<!--button onclick="myFunction()">Toggle Video</button-->
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://static.opentok.com/v2/js/opentok.js" charset="utf-8"></script>
<script charset="utf-8">
var publisher;
var connectionCount = 0;
var apiKey = '<?php echo '45833942'; ?>';
var sessionId = '<?php echo $sessionId; ?>';
var token = '<?php echo $token; ?>';
var subscribeoptions = {width: 664, height: 421, insertMode: 'append'}
var session = OT.initSession(apiKey, sessionId)
.on('streamCreated', function(event) {
session.subscribe(event.stream,'myPublisherDiv', subscribeoptions);
})
.connect(token, function(error) {
var publisherOptions = {
insertMode: 'append',
width: 150,
height: 150,
publishAudio:true,
publishVideo:true,
name: "You"
};
publisher = OT.initPublisher('mycam', publisherOptions);
session.publish(publisher);
});
session.on("connectionCreated", function(event) {
connectionCount++;
displayConnectionCount();
});
session.on("connectionDestroyed", function(event) {
connectionCount--;
displayConnectionCount();
});
function displayConnectionCount() {
document.getElementById("connectionCountField").value = connectionCount.toString();
/*var newdata=connectionCount.toString();
$.ajax({
url:$('#baseUrl').val()+"home/updateactiveuser",
type:'post',
data: {newdata:newdata}
})*/
}
var enableVideo=true;
function myFunction() {
if(enableVideo)
{
publisher.publishVideo(false);
enableVideo=false;
} else
{
publisher.publishVideo(true);
enableVideo=true;
}
}
</script>
<?php
});
$app->run();
}
?>
Thanks
Here is a sample code. I've not used SLIM for this. But this can be done with Slim also. I've executed the script 5 times & each time I got a unique Session-Id.
Session Id Received -
Session Id Got : 1_MX40NTgzMzk0Mn5-MTQ5NDMyMzQ0NzU0NH5KNk9Gcy9FSktPSlUwdldUbURwazJ0Umd-QX4
Session Id Got : 2_MX40NTgzMzk0Mn5-MTQ5NDMyMzQ3ODMzM35rWWU5NDV1ZjZPMGhLc3pCS3pRSERJY0h-QX4
Session Id Got : 1_MX40NTgzMzk0Mn5-MTQ5NDMyMzQ5NTcwOX5kc0Q3NDBjQSthOWJaMEk1eUllU3dCY0t-QX4
Session Id Got : 2_MX40NTgzMzk0Mn5-MTQ5NDMyMzUwNzExOH5NMEZuZWRyejBZYnZRVk1zSEczNldocmV-QX4
Session Id Got : 1_MX40NTgzMzk0Mn5-MTQ5NDMyMzUxNzE3NH5Yc0hyMUlacmFqK25pVzhXNDI5NTV6eDB-QX4
Vanilla PHP Script -
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require 'vendor/autoload.php';
use OpenTok\OpenTok;
$apiKey = '45833942';
$apiSecret = '9727d4ae20e8695a8f787bc58c0b4a9ebf6aae6e';
$opentok = new OpenTok($apiKey, $apiSecret);
use OpenTok\MediaMode;
use OpenTok\ArchiveMode;
// An automatically archived session:
$sessionOptions = array(
'archiveMode' => ArchiveMode::ALWAYS,
'mediaMode' => MediaMode::ROUTED
);
$session = $opentok->createSession($sessionOptions);
// Store this sessionId in the database for later use
$sessionId = $session->getSessionId();
echo "Session Id Got : $sessionId";
SLIM Version -
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use OpenTok\OpenTok;
use OpenTok\MediaMode;
use OpenTok\ArchiveMode;
require 'vendor/autoload.php';
$app = new \Slim\App;
$container = $app->getContainer();
$container['opentok'] = function ($c) {
$apiKey = '45833942';
$apiSecret = '9727d4ae20e8695a8f787bc58c0b4a9ebf6aae6e';
$opentok = new OpenTok($apiKey, $apiSecret);
return $opentok;
};
$app->get('/', function (Request $request, Response $response) {
// An automatically archived session:
$sessionOptions = array(
'archiveMode' => ArchiveMode::ALWAYS,
'mediaMode' => MediaMode::ROUTED
);
$session = $this->opentok->createSession($sessionOptions);
// Store this sessionId in the database for later use
$sessionId = $session->getSessionId();
$response->getBody()->write("Session Id Got : $sessionId");
return $response;
});
$app->run();
Hope, it'll help you.
Ref : https://tokbox.com/developer/sdks/php/
Looks like you have based your code on the OpenTok Hello World PHP sample. This sample is written to support a single session only, for demonstration purposes. Your issue here is that you are retrieving the same key (sessionId) from cache every time, which is what the sample does.
You are close. The simplest way to extend this sample to multiple sessions is to store your new session IDs in the cache as different keys. You need to change your code to use different key for storing and retrieving session ID. So, you can change the cache retrieval logic from:
<?php
$sessionId = $app->cache->getOrCreate('sessionId', array(), function() use ($app) {
# ...
}
?>
to something like:
<?php
# Here we add `$id` from the URI segment to create a unique key
# Notice the change in the key name to `'session' . $id'`
$sessionId = $app->cache->getOrCreate('session' . $id, array(), function() use ($app) {
# ...
}
?>
At the simplest, your code needs to map your application's live chat ID to an OpenTok session internally. Everytime you request for a new livechat ID, it will create a new OpenTok session and store the new OpenTok session ID internally for that livechat ID.
So, you should have two different sessions if you request:
/home/livechat/foo/bar
/home/livechat/baz/bar
Bonus
A quick tip on creating OpenTok sessions: This is all you need to create a new session using OpenTok PHP SDK:
<?php
use OpenTok\OpenTok;
$apiObj = new OpenTok($API_KEY, $API_SECRET);
# This function creates an OpenTok session and returns a new session ID
function createOTSession() {
$session = $apiObj->createSession(array('mediaMode' => MediaMode::ROUTED));
return $session->getSessionId();
}
?>
Everytime you call $apiObj->createSession(), it creates a new session and you can access the session id by calling getSessionId() on the returned object. If you have a function like createOTSession() above, you can call that function from a route that needs to creates new sessions.
See: Creating OpenTok sessions in PHP
I want to display a form with a script I adapted from this question. The script is in a file I wrote called queries.js, and its purpose is to print the content of a php form called "dbMinAlert.php" in a div like this <div id="recentExits" name="recentExits"></div> located in my project's index, I tried invoking getNewData(); in my index.php file using this tag <body onLoad="getNewData()"> but it doesn't seem to do anything at all.
var data_array = ''; // this is a global variable
function getNewData() {
$.ajax({
url: "dbMinAlert.php",
})
.done(function(res) {
data_array = res; // the global variable is updated here and accessible elsewhere
getNewDataSuccess();
})
.fail(function() {
// handle errors here
})
.always(function() {
// we've completed the call and updated the global variable, so set a timeout to make the call again
setTimeout(getNewData, 2000);
});
}
function getNewDataSuccess() {
//console.log(data_array);
document.getElementById("recentExits").innerHTML=data_array;
}
getNewData();`
---This php code works and it actually does what I expect it to do. The real problem is the javascript, for all I care the next php form could print a "Hello world" message, but I want it displayed inside the div I placed in my index, without having to post a thing to dbMinAlert.php.
define("HOST", "localhost");
define("DBUSER", "root");
define("PASS", "password");
define("DB", "mydb");
// Database Error - User Message
define("DB_MSG_ERROR", 'Could not connect!<br />Please contact the site\'s administrator.');
$conn = mysql_connect(HOST, DBUSER, PASS) or die(DB_MSG_ERROR);
$db = mysql_select_db(DB) or die(DB_MSG_ERROR);
$query = mysql_query("
SELECT *
FROM outputs, products
WHERE products.idProduct=outputs.idProduct
ORDER BY Date DESC, Time DESC limit 5
");
echo '<ul class="news">';
while ($data = mysql_fetch_array($query)) {
$date = date_create($data['Date']);
$time = date_create($data['Time']);
echo '<li><figure><strong>'.date_format($date,'d').'</strong>'.date_format($date,'M').date_format($date,'Y').'</figure>'.$data["idProduct"]." ".$data['prodName'].'</li>';
}
echo '</ul>';
You have to execute the function for the first time.
getNewData();
It could be the way you are returning the result from php. Instead of doing multiple echo, could you first assign your result in single php variable and finally do single echo.
$result = '<ul class="news">';
while ($data = mysql_fetch_array($query)) {
$date = date_create($data['Date']);
$time = date_create($data['Time']);
$result = $result + '<li><figure><strong>'.date_format($date,'d').'</strong>'.date_format($date,'M').date_format($date,'Y').'</figure>'.$data["idProduct"]." ".$data['prodName'].'</li>';}
$result = $result + '</ul>';
echo $result;
I found a solution in this question and my code ended up Like this.
I just had to invoke the function in my index by typing <body onload="return getOutput();">
JavaScript
//Min-Max Alerts
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'dbMinAlert.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('recentExits');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('recentExits');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
I am trying to use the JavaScript/jQuery Ajax File Uploader by Jordan Feldstein available at https://github.com/jfeldstein/jQuery.AjaxFileUpload.js
It is an older library but still very popular due to it's simplicity and for being so lightweight (around 100 lines) and you can attach it to a single form input filed and it simply works! You select a file as normal with the form inut filed and on selection it instantly uploads using AJAX and returns the uploaded file URL.
This makes the library good for my use where I am uploading a file inside a modal window which is also generate with AJAX and I have used this library in many similar projects.
My backend is using PHP and Laravel and that is where my issue seems to be.
My test script works but when I implement it into my Laravel app it returns this error....
ERROR: Failed to write data to 1439150550.jpg, check permissions
This error is set in my controller below when this code is not retuning a value...
$result = file_put_contents( $folder . '/' .$filename, file_get_contents('php://input') );
So perhaps this part file_get_contents('php://input') does not contain my file data?
It does create the proper directory structure and even a file which is /uploads/backing/2015/08/1439150550.jpg
The 1439150550.jpg is a timestamp of when the upload took place. It create this file in the proper location however the file created has no content and is 0 bytes!
Below is my Laravel Controller action which handles the back-end upload and below that the JavaScript....
PHP Laravel Controller Method:
public function uploadBackingStageOneFile(){
// Only accept files with these extensions
$whitelist = array('ai', 'psd', 'svg', 'jpg', 'jpeg', 'png', 'gif');
$name = null;
$error = 'No file uploaded.';
$destination = '';
//DIRECTORY_SEPARATOR
$utc_str = gmdate("M d Y H:i:s", time());
$utc = strtotime($utc_str);
$filename = $utc . '.jpg';
$folder = 'uploads/backing/'.date('Y') .'/'.date('m');
//if Directory does not exist, create it
if(! File::isDirectory($folder)){
File::makeDirectory($folder, 0777, true);
}
// Save Image to folder
$result = file_put_contents( $folder . '/' .$filename, file_get_contents('php://input') );
if (!$result) {
Log::info("ERROR: Failed to write data to $filename, check permissions");
return "ERROR: Failed to write data to $filename, check permissions\n";
}
$url = $folder . '/' . $filename;
return Response::json(array(
'name' => $name,
'error' => $error,
'destination' => $url
));
}
JavaScript AJAX FIle Upload LIbrary
/*
// jQuery Ajax File Uploader
//
// #author: Jordan Feldstein <jfeldstein.com>
// https://github.com/jfeldstein/jQuery.AjaxFileUpload.js
// - Ajaxifies an individual <input type="file">
// - Files are sandboxed. Doesn't matter how many, or where they are, on the page.
// - Allows for extra parameters to be included with the file
// - onStart callback can cancel the upload by returning false
Demo HTML upload input
<input id="new-backing-stage-1-file" type="file">
Demo JavaScript to setup/init this lbrary on the upload field
$('#new-backing-stage-1-file').ajaxfileupload({
'action': '/upload.php',
'params': {
'extra': 'info'
},
'onComplete': function(response) {
console.log('custom handler for file:');
alert(JSON.stringify(response));
},
'onStart': function() {
if(weWantedTo) return false; // cancels upload
},
'onCancel': function() {
console.log('no file selected');
}
});
*/
(function($) {
$.fn.ajaxfileupload = function(options) {
var settings = {
params: {},
action: '',
onStart: function() { },
onComplete: function(response) { },
onCancel: function() { },
validate_extensions : true,
valid_extensions : ['gif','png','jpg','jpeg'],
submit_button : null
};
var uploading_file = false;
if ( options ) {
$.extend( settings, options );
}
// 'this' is a jQuery collection of one or more (hopefully)
// file elements, but doesn't check for this yet
return this.each(function() {
var $element = $(this);
// Skip elements that are already setup. May replace this
// with uninit() later, to allow updating that settings
if($element.data('ajaxUploader-setup') === true) return;
$element.change(function()
{
// since a new image was selected, reset the marker
uploading_file = false;
// only update the file from here if we haven't assigned a submit button
if (settings.submit_button == null)
{
upload_file();
}
});
if (settings.submit_button == null)
{
// do nothing
} else
{
settings.submit_button.click(function(e)
{
// Prevent non-AJAXy submit
e.preventDefault();
// only attempt to upload file if we're not uploading
if (!uploading_file)
{
upload_file();
}
});
}
var upload_file = function()
{
if($element.val() == '') return settings.onCancel.apply($element, [settings.params]);
// make sure extension is valid
var ext = $element.val().split('.').pop().toLowerCase();
if(true === settings.validate_extensions && $.inArray(ext, settings.valid_extensions) == -1)
{
// Pass back to the user
settings.onComplete.apply($element, [{status: false, message: 'The select file type is invalid. File must be ' + settings.valid_extensions.join(', ') + '.'}, settings.params]);
} else
{
uploading_file = true;
// Creates the form, extra inputs and iframe used to
// submit / upload the file
wrapElement($element);
// Call user-supplied (or default) onStart(), setting
// it's this context to the file DOM element
var ret = settings.onStart.apply($element, [settings.params]);
// let onStart have the option to cancel the upload
if(ret !== false)
{
$element.parent('form').submit(function(e) { e.stopPropagation(); }).submit();
}
}
};
// Mark this element as setup
$element.data('ajaxUploader-setup', true);
/*
// Internal handler that tries to parse the response
// and clean up after ourselves.
*/
var handleResponse = function(loadedFrame, element) {
var response, responseStr = $(loadedFrame).contents().text();
try {
//response = $.parseJSON($.trim(responseStr));
response = JSON.parse(responseStr);
} catch(e) {
response = responseStr;
}
// Tear-down the wrapper form
element.siblings().remove();
element.unwrap();
uploading_file = false;
// Pass back to the user
settings.onComplete.apply(element, [response, settings.params]);
};
/*
// Wraps element in a <form> tag, and inserts hidden inputs for each
// key:value pair in settings.params so they can be sent along with
// the upload. Then, creates an iframe that the whole thing is
// uploaded through.
*/
var wrapElement = function(element) {
// Create an iframe to submit through, using a semi-unique ID
var frame_id = 'ajaxUploader-iframe-' + Math.round(new Date().getTime() / 1000)
$('body').after('<iframe width="0" height="0" style="display:none;" name="'+frame_id+'" id="'+frame_id+'"/>');
$('#'+frame_id).get(0).onload = function() {
handleResponse(this, element);
};
// Wrap it in a form
element.wrap(function() {
return '<form action="' + settings.action + '" method="POST" enctype="multipart/form-data" target="'+frame_id+'" />'
})
// Insert <input type='hidden'>'s for each param
.before(function() {
var key, html = '';
for(key in settings.params) {
var paramVal = settings.params[key];
if (typeof paramVal === 'function') {
paramVal = paramVal();
}
html += '<input type="hidden" name="' + key + '" value="' + paramVal + '" />';
}
return html;
});
}
});
}
})( jQuery );
My JavaScript usage of the above library:
// When Modal is shown, init the AJAX uploader library
$("#orderModal").on('shown.bs.modal', function () {
// upload new backing file
$('#new-backing-stage-1-file').ajaxfileupload({
action: 'http://timeclock.hgjghjg.com/orders/orderboards/order/uploadbackingimage',
params: {
extra: 'info'
},
onComplete: function(response) {
console.log('custom handler for file:');
console.log('got response: ');
console.log(response);
console.log(this);
//alert(JSON.stringify(response));
},
onStart: function() {
//if(weWantedTo) return false; // cancels upload
console.log('starting upload');
console.log(this);
},
onCancel: function() {
console.log('no file selected');
console.log('cancelling: ');
console.log(this);
}
});
});
The problem is like you said, file_get_contents('php://input') does not contain your file data.
jQuery.AjaxFileUpload plugin wrap file input element with a form element that contains enctype="multipart/form-data" attribute. 1
From php documentation: 2
php://input is not available with enctype="multipart/form-data".
This is an example of the PHP script I want to get the output from within my javascript file:
data.php
<?php
$input = file_get_contents('data.txt');
echo $input."\n";
?>
script.js
$(document).ready(function(){
var data;
// get output from data.php
console.log( data );
});
I just want a way to test to see if the data from within the data.txt file that is being stored in a php variable can be passed into the javascript file and then printed within the javascript console on the html page.
I want to do this so that I can store a variable in the text file and then reference it as it dynamically is updated from multiple users at the same time.
I've seen ways to do this, but it involves the javascript being in the same file as the html, which is not the case here. I'm also using jquery so I don't know if that makes a difference. I've never used php before and am new to javascript, so any help would be appreciated.
You can put you php code in the javascript file if you change the extension to "php". As "php" extensions will get delivered as Html per default, you have to state that it is Javascript in the code.
script.js.php
<?php header('Content-Type: application/javascript');
?>console.log("<?php
$input = file_get_contents('data.txt');
echo $input."\n";
?>");
$(document).ready(function(){
$("#imgTag, #img2").on("click", process);
var size = 0;
function getTarget(evt)
{
evt = evt || window.event;
return evt.target || evt.scrElement;
}
var temp;
console.log("before get");
console.log("post get");
console.log(size);
function changeSize(myName, myOther)
{
var name = myName;
var other = myOther;
if($("#" + name).height() < 400)
{
$("#" + name).height($("#" + name).height() + 5);
$("#" + name).width($("#" + name).width() + 5);
$("#" + other).height($("#" + other).height() - 5);
$("#" + other).width($("#" + other).width() - 5);
}
}
function process(event)
{
var name = getTarget(event).id;
var other;
if(name == "imgTag")
{
other = "img2";
}
else
other = "imgTag";
console.log($("#" + name));
console.log("Changing size!!!");
console.log( $("#" + name).height());
changeSize(name, other);
}
});
You can read that text file directly with jquery like this:
$.ajax({
url : "data.txt",
dataType: "text",
success : function (data) {
// Display the data in console
console.log(data);
// Or append it to body
$('body').append(data);
}
});
The same way you can read output from your php file, in which case you should change the url to point to your php file. Another thing you should read about is different options of communicating server-client side like json data structure etc.
Documentation: https://api.jquery.com/jQuery.ajax/