Storing form data in a javascript session - php

I was wondering if it's possible to store form data such as 'title' and 'description' in a javascript session?
I'm using the uploadify script to have a flash uploader, but the script isn't passing the title and description. This is my code at the moment;
<script type="text/javascript">
jQuery(document).ready(function() {
title = $("input#title").val();
description = $("textarea#description").val();
$('#uploadImage').uploadify({
'uploader': 'flash/uploadify.swf',
'script': 'process/process_uploaded_image.php',
'folder': 'submitted/pictures',
'cancelImg': 'images/cancel.png',
'queueID' : 'fileQueueImages',
'auto' : false,
'multi' : false,
'fileExt' : '*.jpg;*.png;*.gif;*.jpeg;*.JPG',
'fileDesc': 'Images ONLY (.jpg, .png, .gif, .jpeg, .JPG)',
'buttonText' : 'BROWSE',
'scriptData': {'title':title,'description':description,'user':'<?php echo $usr["id"] ?>'},
'sizeLimit' : '2097152', //2MB
//'buttonImg' : '/components/com_mm/assets/images/button-upload-images.png',
//'width' : '218',
//'height' : '66',
onAllComplete: function() {
//$('#uploadedImage').load(location.href+" #uploadedImages>*","");
//location.reload(); //uncomment this line if youw ant to refresh the whole page instead of just the #allfiles div
location.href = "upload-pics-thanks.php";
},
//onComplete: function(a, b, c, d, e){
// if (d !== '1')
// alert(d);
//},
onError: function (a, b, c, d) {
alert("Error: "+d.type+" Info: "+d.info);
},
onSelect: function () {
}
});
});
</script>

Check out this SO answer and in case that doesn't work...
Did you see this post in the Uploadify forums? Maybe it'll point you in the right direction, and wow so much spam in those forums.
http://www.uploadify.com/forum/viewtopic.php?f=7&t=3120

JavaScript does not have sessions. Probably the best way is to send your title&description via AJAX to the server.

If you use latest version of uploadify, the data in scriptData will be passed to script as either _POST or _GET (default is now POST) variable. So in your php file, you can get the title and description using:
$_POST['title']
$_POST['description']
$_POST['user']
Just consider it same with handling form submit, only it's originated from uploadify flash. Also note, the flash is not passing the current cookies that currently exist in the browser. If your php is using session stored in the cookies, it must be tweaked to read it from $_POST instead.
I use CodeIgniter, and there are patch for that in CodeIgniter forum. If you just use build in PHP session, you can pass the PHPSESSID inside scriptData, then in side script PHP, reinitialize session using passed data. It's have been answered in other question in stackoverflow, just search it with uploadify keyword.

Related

sending data from Javascript to remote php

I am modifying a script to make up a firefox extension for my website. The original script ( chrome extension) stores data into a local websql database. I want it rather to send the three variable to a php file using this format
http://mysite.com/receiver.php?id=href&&title=hostname&&article=article&&article=title
The part of Js that is normally sending the data is the following
// post credentials to background
chrome.extension.sendRequest({
action: 'queryDatabase',
crud: 'create',
record: [
window.location.href,
window.location.hostname,
title,
article
]
});
I would be glad if any one can lead me through the modification of this code
You can use jQuery's ajax() method to accomplish this:
// post credentials to http://mysite.com/receiver.php
jQuery.ajax({
url: "http://mysite.com/receiver.php",
type: 'GET',
data: {
id: "href",
title: "hostname",
article: "article"
}
}).success(function ( data ) {
alert("completed successfully");
}).error(function ( data ) {
alert("there was an error");
});
http://api.jquery.com/jQuery.ajax/
example of the image/PHP solution. The jQuery Ajax solution listed is good if you need to know what was returned (I use it on things like http://jsErrLog.appspot.com and it's a great solution), the image is good if you just want to throw something over the fence and move on. Both as non-blocking
in the HTML page the Javascript would need to trigger a call that requests an image:
<script>
databaseImage = new Image();
databaseImage.src = "http://mysite.com/receiver.php?id=href&&title=hostname&&article=article&&article=title";
</script>
and the PHP page that it calls would, after storing the data, would need to return an image (cleaner than sending back something inappropriate) -
<?
$im = file_get_contents('{path to your 1px .gif}');
header('content-type: image/gif');
echo $im;
?>

How to get Uploadify working with Codeigniter + CSRF?

I'm trying to get Uploadify 2.1.4 to work with Codeigniter 2.1.0 and CSRF and I'm not having much luck. I have a very basic upload controller & the following code for uploadify:
$(function() {
var cct = $.cookie('csrf_cookie_name');
$('#uploadifyMe').uploadify({
'uploader' : '<?php echo site_url(); ?>js/uploadify/uploadify.swf',
'script' : '<?php echo site_url(); ?>upload/',
'cancelImg' : '<?php echo site_url(); ?>js/uploadify/cancel.png',
'multi' : true,
'auto' : false,
'fileExt' : '*.jpg;*.jpeg',
'fileDesc' : 'Image Files (JPG, JPEG)',
'fileDataName' : 'imgData',
'queueID' : 'fileQueue',
'simUploadLimit' : 1,
'sizeLimit' : 7340032,
'removeCompleted': false,
'scriptData' : { 'csrf_token_name' : cct, 'upload' : 'true' },
'onSelectOnce' : function(event, data) {
$('.uploadifyProgress').addClass('progress');
$('.uploadifyProgressBar').addClass('bar');
},
'onComplete' : function(e, i, f, r, d) {
console.log(r);
},
'onError' : function(e, i, f, eO) {
console.log(eO);
if(eO.info == 500) {
$('#status').prop('class', 'alert alert-error').html('<a class="close" data-dismiss="alert">×</a><h4>Hmmm. Something gone wrong it has.</h4> Yoda has discovered that your security token has expired. This is because you have been here for longer than two hours. we cannot refresh your key automatically, please refresh the page and try again.');
}
}
});
});
The problem is when I upload an image I get a HTTP 500 thrown back at me. I now know it's due to CSRF being turned on since if I turn it off it works fine.
I've tried a load of solutions to the problem. The one you can see in my code, and a one from here that clones your session data and sends it across with the CSRF key, but nothing works. I always end up with a 500 HTTP unless I turn off CSRF.
If anyone can help it would be really appreciated. I realize this question seems to get asked a lot, and it's driving me nutty. On a side note passing the CSRF along with standard AJAX requests works fine, just not with uploadify.
Use this code, it enables you to define an array of controller methods that are not subject to CSRF: https://github.com/EllisLab/CodeIgniter/pull/236.
The issue is that Uploadify uses a Flash object, which is like a completely different browser, with different session, so the CSRF won't match your session if you POST the cookie data.
You would need to override the original CSRF function with a MY_Security.php file and make so you can get around it by, in example, sending your entire session cookie via POST and make so the CSRF can read it, so you can be matched.
You might as well try HTML5 uploaders like https://github.com/blueimp/jQuery-File-Upload that at least gives you a better chance at not having to do such overrides.

Need advice on Ajax fileupload

I am trying get use of Ajax file uploader
http://valums.com/ajax-upload/
The doc says:
var uploader = new qq.FileUploader({
// pass the dom node (ex. $(selector)[0] for jQuery users)
element: document.getElementById('file-uploader'),
// path to server-side upload script
action: '/server/upload'
// WHAT IS action:?
});
The element property means what element ID is used as Upload button.
What is action? It must be some sort of handler for uploaded files?
How I can handle uploaded files and where are located?
The doc says
// events
// you can return false to abort submit
onSubmit: function(id, fileName){},
onProgress: function(id, fileName, loaded, total){},
onComplete: function(id, fileName, responseJSON){},
onCancel: function(id, fileName){},
I want when upload complete display a list of files somewhere, say in div with ID=list
The short snippet will be highly appreciated and awarded.
I've used File Uploader quite a lot and I think it is the best file uploader out there.
The action is the method (URL) which receives the call from your Ajax client script.
You have to define a DIV in your HTML:
<div id="uploaderFile"></div>
I've used a javascript function to build my uploader around the DIV:
function CreateImageUploader() {
var uploader = new qq.FileUploader({
element: $('#uploaderFile')[0],
template: '<div class="qq-uploader">' +
'<div class="qq-upload-drop-area"><span>Drop files here to upload</span></div>' +
'<div class="qq-upload-button ui-button ui-widget ui-corner-all ui-button-text-only ui-state-default">Seleziona il Listino Excel</div>' +
'<ul class="qq-upload-list"></ul>' +
'</div>',
hoverClass: 'ui-state-hover',
focusClass: 'ui-state-focus',
action: 'Home/UploadImage',
allowedExtensions: ['jpg', 'gif'],
params: { },
onSubmit: function(file, ext) {
},
onComplete: function(id, fileName, responseJSON) {
$("#PopupImageUploader").dialog('close');
}
}
});
}
What happens here is you're creating an uploader around this element element: $('#uploaderFile')[0]. I've used the standard template but you can change the appearance.
When you've done that everything is pretty much setup on the client-side.
On the server side (it depends what you're using) you have to intercept and read the file and persist it.
I use ASP.NET MVC. You can find my action here and here
Your server-side code will manage to persist the file where you want and will return infos to the client script.
Personally I return json data which I manage with the event onComplete to: close a dialog (like in the example); show a message etc etc etc.
If you want to pass parameters back to the client on the server side you can return a JSON object. I would do something like this:
return ("{success:true, newfilename: '" + newFileName + "'}");
I reckon that in PHP could be something like this:
echo {success:true, newfilename: '" + newFileName + "'}";
Forgive me if there are mistakes in that but I've never written a single PHP line in my whole life ;-)
the client side now can check the JSON object like this:
onComplete: function(id, fileName, responseJSON) {
alert(responseJSON.newfilename);
}
As you can see I pass back the result of the action: success:true or success:false so I can show a warning to the user:
onComplete: function(id, fileName, responseJSON) {
if (responseJSON.success)
{
alert(responseJSON.newfilename);
}
else {
alert("something wrong happened");
}
}
How I can handle uploaded files and where are located?
This depends on your webserver and backend language. In PHP have a look at the $_FILES array.
What is action? It must be some sort of handler for uploaded files?
The URL the form used to upload the file is submitted to.
What is action? It must be some sort of handler for uploaded files?
Yes, same as for the HTML <form> element's attribute.
How I can handle uploaded files
With a server side script written in your server side language of preference.
and where are located?
Probably as a stream to STDIN. The forms library you use with the aforementioned server side language have methods to extract it automatically.

Uploadify Hanging at random on 100%

I am using Uploadify to enable my users to upload images via my web application.
The problem I am having is that every now and then (at what appears to be random) when the progress bar reaches 100% it 'hangs' and does nothing.
I was wondering if any developers familiar with uploadify may have any idea how to solve this? I am in desperate need of some help.
Here is my front-end code:
<javascript>
jQuery(document).ready(function() {
jQuery("#uploadify").uploadify({
'uploader' : 'javascripts/uploadify.swf',
'script' : 'upload-file2.php',
'cancelImg' : 'css/images/cancel.png',
'folder' : 'uploads/personal_images/' + profileOwner,
'queueID' : 'fileQueue',
'auto' : true,
'multi' : true,
'fileDesc' : 'Image files',
'fileExt' : '*.jpg;*.jpeg;*.gif;*.png',
'sizeLimit' : '2097152',
'onComplete': function(event, queueID, fileObj, response, data)
{
processPersonalImage(fileObj.name);
arrImgNames.push(fileObj.name);
showUploadedImages(true);
document.getElementById("photos").style.backgroundImage = "url('css/images/minicam.png')";
},
'onAllComplete' : function()
{
completionMessage(arrFailedNames);
document.getElementById("displayImageButton").style.display = "inline";
document.getElementById("photos").style.backgroundImage = "url('css/images/minicam.png')";
},
'onCancel' : function()
{
arrImgNames.push(fileObj.name);
arrFailedNames.push(fileObj.name);
showUploadedImages(false);
},
'onError' : function()
{
arrImgNames.push(fileObj.name);
arrFailedNames.push(fileObj.name);
showUploadedImages(false);
}
});
});
</javascript>
And server side:
if (!empty($_FILES))
{
//Get user ID from the file path for use later..
$userID = getIdFromFilePath($_REQUEST['folder'], 3);
$row = mysql_fetch_assoc(getRecentAlbum($userID, "photo_album_personal"));
$subFolderName = $row['pk'];
//Prepare target path / file..
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/'.$subFolderName.'/';
$targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
//Move uploaded file from temp directory to new folder
move_uploaded_file($tempFile,$targetFile);
//Now add a record to DB to reflect this personal image..
if(file_exists($targetFile))
{
//add photo record to DB
$directFilePath = $_REQUEST['folder'] . '/'.$subFolderName.'/' . $_FILES['Filedata']['name'];
addPersonalPhotoRecordToDb($directFilePath, $row['pk']);
}
echo "1";
die(true);
}
thanks for any help!!
this seems like a php error.
I'd use Fiddler or a similar problem to view the php response or similar.
Check your php error logs, they might shed some light.
I had a similar problem some time ago with Uploadify (using ASP.Net MVC though) - but you will definitely find some useful info regarding the Uploadify event handling and behaviour in the answer posted! Its available here
I had the same problem.
Simply add echo "astlavista babi" to your uploadify script, this echo statement should be the last line, if you have conditional statement then echo should be placed as a last line within the conditional statement.
These are the steps I would take, in order:
1) Be 100% certain you are getting a 200 response from your server. If not, that is the problem
2) Use the latest and the greatest uplaodify and jquery
3) Check for JS errors (firebug console or browser JS debugger will work)
4) Upgrade your Flash player (if that solves it then you can require a higher version)
5) Put a debug statements in the uploadify source, specifically in the complete handler to be sure it gets called
6) If the progress is reaching 100% but the handler never gets called, I'm afraid the next step may be to dive into the actionscript and use the debugger or some trace statements to figure out where the error is. This can mean that there is a bug in calling the external interface function
7) If you make fixes, submit back to uploadify
Chreck your php.ini file for post_max_size parameter. It must be >= upload_max_filesize parameter. For more details see http://php.net/post-max-size.
For future reference: I had this problem when sending data to the upload script using "scriptData" and solved it by simply echoing "ok" in the upload script rather than sending back an empty document.
For those who are using Macs use HTTP Scoop to view the request as Firebug does not show it. More on HTTP Scoop from this blog.

Uploadify plugin

Has anyone used this plugin? I don't know if my setup is right, but I think so.
$(document).ready(function () {
$("#uploadify").uploadify({
'uploader': '/extra/flash/uploadify.swf',
'script': '/admin/uploads/artistsphotos',
'checkScript': '/admin/uploads/artistsphotos',
'cancelImg': '/images/cancel.png',
'folder': '/img/artists',
'queueID': 'fileQueue',
'auto': false,
'multi': true,
'onComplete': function (a, b, c, d, e) {
alert(d);
},
'onAllComplete': function (event, data) {
//something here
//alert(data);
}
});
$('.vla').click(function () {
$("#uploadify").uploadifyUpload();
return false;
});
});
If I check with firebug I receive this: http://screencast.com/t/z9PY53bi, but I can't work with the files in PHP,and I also have enctype=".. on the <form>, but when I check the $_FILES array is empty, is my plugin setup wrong?
I have used uploadify before.
Are you using the most recent version of uploadify?
also you shouldn't need a form tag, the 'script' variable is where the uploader sends the file data. Any other information that needs to be sent with it has to be placed in the 'scriptData' variable. Also, I'm not sure if you can send both the script and the checkScript to the same file that might be what is causing the problem.
The script is the file that processes the upload, the checkScript is a script that ensures that the file is not already on the server.

Categories