SWFUpload what happens after file select? - php

I'm lost here. I'm trying to set up a simple file upload, handled by SWFUpload. After file selection nothing happens. I don't see a request being sent, and there is nothing in my console. Is the swf object supposed to call my upload_url page immediately?
var swfu,jobForm;
var j = jQuery.noConflict();
j(window).load(function() {
jobForm = j('.admin-atomic-form form');
swfu = new SWFUpload({
upload_url : "URL/upload.php",
flash_url : "URL/swfupload.swf",
file_size_limit : "20 MB",
file_types : "*.doc;*.pdf;*.rtf;*docx;*.jpg;",
//file_types_description : "All Files",
file_upload_limit : "1",
button_placeholder_id : "swfuploader",
button_image_url : "URL/file-browse.png",
button_width: 100,
button_height: 30,
upload_start_handler : uploadStart,
upload_success_handler : uploadSuccess
});
//jobForm.form.submit(function(ev){ev.preventDefault()})
});
function uploadStart(){
//.submit()
console.log(this,'start');
};
function uploadSuccess(){
//form.submit()
console.log('success');
}

starting to upload a file is a two step process: 1. you select a file (which then populates a path in an input box), 2. you must submit the form to begin the actual upload.
I'm assuming you're not doing step 2, since in your code, you have commented out form.submit()
please uncomment this line: //jobForm.form.submit(function(ev){ev.preventDefault()})
then after you select a file, submit the form.

SWFUploadObj.startUpload(); needs to be fired and that's what initiated the POST request to the specified upload_url. If this method is fired by some default setting, it certainly wasn't doing it for me.
Here is an example of a few of my functions:
// Bound to file_queued_handler : sets a flag that there is a file waiting to upload
function swfuFileQueued(file){
resumeQueued = true;
$j('#browseFile').val(file.name);
}
//Bound to form submit event:
//a successful upload will submit this form again once the success response with the server-moved and renamed filename comes back from the file upload handling script
function swfuFormSubmit(ev){
if(uploadSuccess){
return true;
} else {
if(resumeQueued == true){
ev.preventDefault();
swfuUploadStart(); // see next function
} else {
return true;
}
}
}
function swfuUploadStart(){
try {
swfu.startUpload(); // <-- The actual method that begins the file upload request
} catch (e) {
}
return false;
}
function swfuProgress(){ ...
function swfuError(){ ...
function swfuSuccess(){
//update input element containing filename or id to send with form
//update a status box with "Success"
//uploadSuccess = true
//form.submit() once more, this time uploadSuccess will tell the function to continue on and actually submit itself
Useful URL to understand SWFUpload process : http://www.dconstructing.com/2010/07/08/making-swfupload-work

Related

Returning Uploadifive Ajax 'Error/Success' data from Codeigniter Controller

I'm using the Uploadifive upload plug-in. It works as it should. However, I'm having a hard time passing error and success messages from my controller back to my view via the plug-in. I'm logging console and log errors. But can't seem to return any controller errors back to the Uploadifive call to display in my view.
In short, I want to output either an error or success message from my controller (via the $result var) back to my ajax function to embed into my view.
The alert, alert(data.result) outputs "undefined".
JS function:
$('#file-upload').uploadifive({
...
'onUpload': function(file) {
console.log('upload complete!');
},
'onUploadComplete' : function(file, data) {
console.log('The file ' + file.name + ' uploaded successfully.');
// returned error/success message here
alert(data.result);
},
'onError': function(errorType) {
console.log(errorType);
}
});
CI Controller method:
function add_document() {
// If Ajax request, proceed:
if(isset($_POST['is_ajax'])) {
if (!$this->upload->do_upload()) {
// If file upload failed or is invalid,
// display error notification
$result = array('error' => $this->upload->display_errors());
echo json_encode($result);
}
else {
// If file upload was successful
$result = 'success!';
echo $result;
...
}
}
// if not, redirect to upload page
else {
redirect('upload');
}
}
I figured out how to get this to work with my controller code. Uploadifive is not well documented, so it's been a shaky ride. But none the less, here's how I got it to function the way I wanted. Hopefully this helps others.
In my controller, I replaced the echo json_encode($result); line with the below. Specifying the array key I want to use (i.e. error) and the outputting of the result as html.
echo html_entity_decode($result['error']);
In my javascript function, all I simply needed to do was output the data... .result was not needed in the alert. Note, I decided to attach the result to some html versus an alert.
// Display Error/Success Messages
$('.status').html(data);

Dropzone.js remove button with php

I use dropzone.js for a nice upload form.
I linked the php code to upload the files and i setted addRemoveLinks=true so i have the remove button.
I need an idea how to efectivly delete the filse uploaded with a php code when i hit remove button.
The php is simple to do but i need t know how to relate them.
I already tryed using $.post in this function removedfile: function(file) but no succes.
removedfile: function(file) {
$.post("test.php");
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
},
First off, you shouldn't simply overwrite the default removedfile event handler, but rather register your own handler along with it.
You need to first get the ID back from the server (so you know how to relate to it) and then use this to setup the delete call.
Dropzone.options.myDropzone = {
init: function() {
this.on("success", function(file, response) {
file.serverId = response; // If you just return the ID when storing the file
// You can also return a JSON object then the line would
// look something like this:
//
// file.serverId = response.id;
//
// In that case make sure that you respond with the mime type
// application/json
});
this.on("removedfile", function(file) {
if (!file.serverId) { return; } // The file hasn't been uploaded
$.post("delete-file.php?id=" + file.serverId); // Send the file id along
});
}

Add papameters to AJAX response and then apply actions based on return parameter

I have a page (page1)that calls another page (page2) via AJAX.
How do I include parameters to page2 response and parse them in success : function(data)?
is there any way to add parameters to http response object and then access those parameters?
Reason:
page2 generates some HTML. It could be good or bad html message. If it is a good message, I need to add parameters (hidden) and then add that good message to Success div. if message is an error, I need to add this message to 'Error div'.
I can do it bad way: In Page2 I can add hidden element; then in page1 I can create some temp hidden div and add response to that div. Then access hidden element in hidden div and get it's value. Then get message from that div and paste it to designated div. But this seems to be too unprofessional.
PAGE1:
function registeruser(){
jQuery(function($) {
$.ajax( {
url : "page2.php",
type : "POST",
data: {
registerFname : document.getElementById('registerFname').value,
registerLname : document.getElementById('registerLname').value,
registerLEmail : document.getElementById('registerEmail').value,
registerPassword : document.getElementById('registerPassword').value,
ts : (new Date().getTime())
},
success : function(data) {
//need to apply logic here based on the return parameters
//if (SOME_PARAMETER === 'success'){
// document.getElementById('registerPresentation').innerHTML = data;
//}
//else {
// document.getElementById('registerPresentationErrorDIV').innerHTML = data;
//}
//need to get rid of item below
document.getElementById('registerPresentation').innerHTML = data;
}
});
});
}
page2.php
$a=array('err'=>0,html=>'dfhsxdfhbcfvyhdgfr');
json_encode($a);
page1.php
success : function(data) {
if (data.err=='0'){...}else{...}
}

$.post json request doesn't return any result

Well, another try:
this is all the jquery code i'm using maybe i made something wrong in the code before $.post(); i call the following function with the onclick of the same form...
function setLogin()
{
$('#login-form').submit(function(e) {
e.preventDefault();
//passing form field to vars
var formUsername=$("#login-form #username").val();
var formPassword=$("#login-form #password").val();
//checks on fields lenght
if((formUsername.length<6))
{
$("#ajax-output").html("<div class='error'>Attenzione username troppo breve!</div>");
}
else if((formPassword.length<6))
{
$("#ajax-output").html("<div class='error'>Attenzione password troppo breve!</div>");
}
else
{
$.post(
//the url
'?module=login',
//data got from login form
{
"username": formUsername,
"password": formPassword,
},
//response
function(data){
$("#ajax-output").html(data.reply)
},
//type
"json"
);
}
});
}
i tried with only this code in php file and it still doesn't return anything...
function Login()
{
//just to try
echo json_encode(array('reply'=>'foo'));
}
it still doesn't work...
Are you sure the post is being run in the first place?
Use Firebug! (or chrome's built-in developer tools)
You can use firebug to pick apart every bit of a web page.
It has a "net" tab that shows every request that is made by the browser, including AJAX requests, and their results, headers and contents.
Use it to see if your requests is really being made, and what the result is. Then take it from there.
Make sure that you're setting a header for the content type when responding - the browser may not attempt to use the JSON if it doesn't know it's receiving JSON.
function Login()
{
header('Content-Type: application/json');
echo json_encode(array('reply'=>'foo'));
}

Stop a form load based on the return data from an ajax callback

Hello I am working with an ajax post function, where I send data and my callback from PHP returns some data back. Based on the data returned I make the decision, either to go forward or allow the user to stay on the page and make changes.
if (validateStep(step))
{
if(step==1)
{
var data = document.getElementById('hiddenContact').value;
$.post('/app/controller/action', {'data':data}, function(returndata){if(returndata.match('not Unique'))alert('Contact source already exists'); else if(returndata.match('not posted')){alert("Not posted to the database");return false;}});
}
step = step + 1;
form[0].action = '/app/controller/index/step:'+step;
document.getElementById('step').value = step;
form[0].submit();
}
Here I am trying to stop the application going ahead when the return data is matched to "not posted", and I am throwing an alert and then a return false to stop the operation. I am unable to stop the application from going to next step though. Though it is returned false, the operation continues to the next step, but when I comment the last 4 lines which increment the step, set the action and submit, it stays on the page and the alert is thrown.
Does anybody know what I should do in order halt my process from submission??
AJAX calls are asynchronous. The "false" you are returning is on the success callback, not on the handler you have shown there. So the last four steps always execute, before the AJAX call even reaches the server. You can fix this by changing ajax response callback to deal with this, like so:
if (validateStep(step))
{
var next_step = function() {
step = step + 1;
form[0].action = '/app/controller/index/step:'+step;
document.getElementById('step').value = step;
form[0].submit();
}
if(step==1)
{
var data = document.getElementById('hiddenContact').value;
$.post('/app/controller/action', { 'data':data }, function(returndata) {
if (returndata.match('not Unique')) alert('Contact source already exists');
else if (returndata.match('not posted')) alert("Not posted to the database");
else next_step();
});
}
else next_step();
}
your process to continue to the next step is outside of your IF statement and will always run.
can you not do this:
if (validateStep(step))
{
if(step==1)
{
var data = document.getElementById('hiddenContact').value;
$.post('/app/controller/action', {'data':data}, function(returndata){
if(returndata.match('not Unique')) {
alert('Contact source already exists');
step = step + 1;
form[0].action = '/app/controller/index/step:'+step;
document.getElementById('step').value = step;
form[0].submit();
} else if (returndata.match('not posted')){
alert("Not posted to the database");
return false;
}
});
}
}

Categories