Welcome Guest, Not a member yet? Register   Sign In
[SOLVED]Need help with phpletter.com/AjaxFileUpload
#1

[eluser]Cgull[/eluser]
Hello,

I am trying for days now to find a way to submit a from that uploads a file as well with Ajax.

I read lots of forum posts and tutorials but can't get it right.

The last one I am trying is the one from here: http://www.phpletter.com/Demo/AjaxFileUpload-Demo/

Very very confused.

If you don't mind, would like to take it step by step,
First question is: how do I display the loading div after selecting a file.

Second question: how do I submit the form and check in my controller if the user was trying to upload a file, I want to save the file name to the database and do the whole codeigniter upload code only if a file was uploaded.
Would I check it in the controller like this:
Code:
if($_FILES['image']['error'] === 0)

My code:

My view - I am putting here only the parts from the view that I think are relavent:
Code:
<?php echo form_open_multipart($url, array('id'=>'issueform')); ?>
<tr>
  <td>Image</td>
  <td>
    $image = array(
              'name' => 'image',
              'class'   => 'fileUpload',
              'value' => set_value('image', $issue->image)
);
    echo form_upload($image); ?&gt;
    <div id="loading"><img src="&lt;?php echo site_url('img/loader.gif'); ?&gt;" alt="loading" /></div>
    </td>
</tr>
<tr>
<td colspan="2"  right">&lt;?php echo form_submit('submit', 'Save', 'class="btn btn-primary"'); ?&gt;</td>
</tr>
</table>
&lt;?php echo form_close();?&gt;
[removed]
$(function() {
  $("#loading").hide();

  $('.fileUpload').on('click', function()
  {
//starting setting some animation when the ajax starts and completes
$("#loading")
          .ajaxStart(function(){
   $(this).show();
})
.ajaxComplete(function(){
   $(this).hide();
});
  });


  $('#issueform').on('submit', function(e)
{
$.ajaxFileUpload
(
         {
  url:'/admin/issue/edit',
  secureuri:false,
  fileElementId:'fileUpload',
  dataType: 'JSON',
  beforeSend:function()
  {
   $("#loading").show();
  },
  complete:function()
  {
   $("#loading").hide();
  },    
  success: function (data, status)
  {
   if(typeof(data.error) != 'undefined')
   {
    if(data.error != '')
    {
     alert(data.error);
    }else
   {
    alert(data.msg);
   }
  }
},
error: function (data, status, e)
{
  alert(e);
}
}
)
  
return false;
});

});
[removed]

Right now, after I select a file to upload, I don't see the loading div and I am totally confused with all the tutorials I read and all the experiments I tried.

Please, please can someone help me?
#2

[eluser]TheFuzzy0ne[/eluser]
[quote author="Cgull" date="1364576858"]
First question is: how do I display the loading div after selecting a file.[/quote]

Hmm... If you copied the tutorial, it should be working. I see you've taken initiative to do it your own way, but I'd suggest following the tutorial first, and making sure it works. Then you can get creative and move things around, checking each step of the way.

As it stands. you may be setting up your hook on the upload button before the DOM is actually ready, or have an error in your syntax.

[quote author="Cgull" date="1364576858"]Second question: how do I submit the form and check in my controller if the user was trying to upload a file, I want to save the file name to the database and do the whole codeigniter upload code only if a file was uploaded.
Would I check it in the controller like this:
Code:
if($_FILES['image']['error'] === 0)
[/quote]

Sure!

[quote author="Cgull" date="1364576858"]Right now, after I select a file to upload, I don't see the loading div and I am totally confused with all the tutorials I read and all the experiments I tried.[/quote]

When you're using Javascript, it's always a good thing to know how to use the Javascript console. If you use Firefox, you can download Firebug, which is one of the best Web development tools around. [url="http://www.getfirebug.com/"]Firebug[/url] will show you when there are any errors, and also allows you to monitor your AJAX requests. In a nutshell, it's pretty darn awesome for debugging Javascript.
#3

[eluser]Cgull[/eluser]
Hello FuzzyOne Smile

Thanks for answering me.

The tutorial is not much of a tutorial, and I do use firebug and I tried many things before I decided to post here.

All the tutorial says is that:
Quote:1. include jquery.js & ajaxfileupload.js javascript files
I included the files

Quote:2. create a function to be fired when the upload button clicked.
e.g.
function ajaxFileUpload()
{
//starting setting some animation when the ajax starts and completes
$("#loading")
.ajaxStart(function(){
$(this).show();
})
.ajaxComplete(function(){
$(this).hide();
});
That's what I'm trying to do here:
Code:
$('.fileUpload').on('click', function()
  {
   //starting setting some animation when the ajax starts and completes
   $("#loading")
   .ajaxStart(function(){
     $(this).show();
   })
   .ajaxComplete(function(){
     $(this).hide();
   });
});
Quote: /*
prepareing ajax file upload
url: the url of script file handling the uploaded files
fileElementId: the file type of input element id and it will be the index of $_FILES Array()
dataType: it support json, xml
secureuri:use secure protocol
success: call back function when the ajax complete
error: callback function when the ajax failed

*/
$.ajaxFileUpload
(
{
url:'doajaxfileupload.php',
secureuri:false,
fileElementId:'fileToUpload',
dataType: 'json',
success: function (data, status)
{
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}else
{
alert(data.msg);
}
}
},
error: function (data, status, e)
{
alert(e);
}
}
)

return false;

}
Trying to make it all happen when I submit the form and not when I upload the file.
Code:
$('#issueform').on('submit', function(e)
{
  $.ajaxFileUpload
  (
   {
    url:'/admin/issue/edit',
    secureuri:false,
    fileElementId:'fileUpload',
    dataType: 'JSON',
    beforeSend:function()
    {
     $("#loading").show();
    },
    complete:function()
    {
     $("#loading").hide();
    },    
    success: function (data, status)
    {
     if(typeof(data.error) != 'undefined')
     {
      if(data.error != '')
      {
       alert(data.error);
      }else
      {
       alert(data.msg);
      }
     }
    },
    error: function (data, status, e)
    {
     alert(e);
    }
   }
  )
  
  return false;

});

I don't get any errors in firebug.

I also looked at their online example, looked in the page source code.

Tried that:
Code:
echo form_submit('submit', 'Save', 'class="btn btn-primary" onClick="ajaxFileUpload()"');
?&gt;
[removed]
$(function() {
$("#loading").hide();

  function ajaxFileUpload()
    {
        //starting setting some animation when the ajax starts and completes
        $("#loading")
        .ajaxStart(function(){
            $(this).show();
        })
        .ajaxComplete(function(){
            $(this).hide();
        });
      
        /*
            prepareing ajax file upload
            url: the url of script file handling the uploaded files
                        fileElementId: the file type of input element id and it will be the index of  $_FILES Array()
            dataType: it support json, xml
            secureuri:use secure protocol
            success: call back function when the ajax complete
            error: callback function when the ajax failed
          
                */
        $.ajaxFileUpload
        (
            {
                url:'doajaxfileupload.php',
                secureuri:false,
                fileElementId:'fileToUpload',
                dataType: 'json',
                success: function (data, status)
                {
                    if(typeof(data.error) != 'undefined')
                    {
                        if(data.error != '')
                        {
                            alert(data.error);
                        }else
                        {
                            alert(data.msg);
                        }
                    }
                },
                error: function (data, status, e)
                {
                    alert(e);
                }
            }
        )
      
        return false;

    }

});
[removed]
Getting these errors:
ReferenceError: ajaxFileUpload is not defined
[Break On This Error]

ajaxFileUpload()

onclick (line 2)

ReferenceError: $ is not defined
[Break On This Error]

$(function() {


And that's why I posted here, trying to get help in understanding what I need to do to make this AjaxFileUpload script work with my form.

Thank you.
#4

[eluser]TheFuzzy0ne[/eluser]
Since you use Firebug, you have console.log() at your disposal. You should be able to use that to debug your code and find out what's going wrong.
#5

[eluser]Cgull[/eluser]
Ok, I had no success with this code.

I changed the code and now the file is being uploaded but I don't know how to redirect to another page if the form was submitted successfuly.

The form is open in a modal window.

The whole form is inside a div tag with a status id

My controller echos success if everything is fine.

If I alert the data from success I get this: success<div id="form">

Code:
var options = {
target: '#status',
success: function(data) {
  if(data == 'success<div id="form">')
   [removed].replace("http://thinklocal.dev/admin/province");
    }
};

// pass options to ajaxForm
$('#issueform').ajaxForm(options);

Everything works fine besides the fact that the page is not redirecting on success.

I also tried this way, but this one just closes the modal window on submit and opens the form in a new window
Code:
$('#issueform').submit( function()
{
   var bar = $('.bar');
   var percent = $('.percent');
   var status = $('#status');

   $(this).ajaxForm({
     beforeSend: function() {
       status.html();
       var percentVal = '0%';
       bar.width(percentVal)
       percent.html(percentVal);
     },
     uploadProgress: function(event, position, total, percentComplete) {
       var percentVal = percentComplete + '%';
       bar.width(percentVal)
       percent.html(percentVal);
     },
     success: function(xhr) { //[removed].replace("http://thinklocal.dev/admin/province");
       status.html(xhr.responseText);
     }
   });
});

Can someone please help?
#6

[eluser]TheFuzzy0ne[/eluser]
I think your "submit" function needs to return false in order to prevent the default action. It looks to me as if your form is being submitted normally, and not via AJAX.
#7

[eluser]Cgull[/eluser]
The problem is, if I return false, then nothing happens when I click the submit button.
#8

[eluser]TheFuzzy0ne[/eluser]
Perhaps you're returning false in the wrong place?
Code:
$('#issueform').submit( function()
{
   var bar = $('.bar');
   var percent = $('.percent');
   var status = $('#status');

   $(this).ajaxForm({
     beforeSend: function() {
       status.html();
       var percentVal = '0%';
       bar.width(percentVal)
       percent.html(percentVal);
     },
     uploadProgress: function(event, position, total, percentComplete) {
       var percentVal = percentComplete + '%';
       bar.width(percentVal)
       percent.html(percentVal);
     },
     success: function(xhr) { //[removed].replace("http://thinklocal.dev/admin/province");
       status.html(xhr.responseText);
     }
   });
  
   return false; // After the code above has been executed.
});
#9

[eluser]Cgull[/eluser]
Thanks again for trying to help.

I am putting the return false in the right place:
Code:
$(function() {
$('#issueform').submit( function()
{
   var bar = $('.bar');
   var percent = $('.percent');
   var status = $('#status');

   $(this).ajaxForm({
     beforeSend: function() {
       status.html();
       var percentVal = '0%';
       bar.width(percentVal)
       percent.html(percentVal);
     },
     uploadProgress: function(event, position, total, percentComplete) {
       var percentVal = percentComplete + '%';
       bar.width(percentVal)
       percent.html(percentVal);
     },
     success: function(xhr) { //[removed].replace("http://thinklocal.dev/admin/province");
       status.html(xhr.responseText);
     }
   });
  
   return false; // After the code above has been executed.
});  

});

Looking at the page source, my form does get the right id:
&lt;form acti method="post" accept-charset="utf-8" id="issueform" enctype="multipart/form-data"&gt;

My button: &lt;input name="save" value="Save" class="btn btn-primary" type="submit"&gt;

Clicking on submit, nothing happens.
No errors in firebug.

Tried to add alert in the success:
Code:
success: function(xhr) { //[removed].replace("http://thinklocal.dev/admin/province");
    alert('in');
       status.html(xhr.responseText);
     }
No alert is coming up.

Added alert on submit:
Code:
$('#issueform').submit( function()
{
  alert('submit');
Do get this alert.

Tried to add complete:
Code:
complete: alert('in');
Got the alert

Tried to change success to complete:
Code:
complete: function(xhr) { alert('in');
       status.html(xhr.responseText);
     }
Nothing happens.

Tried to jump off the roof, couldn't find a ladder....
#10

[eluser]TheFuzzy0ne[/eluser]
Code:
complete: alert('in');

That alert() will execute regardless, as that function is executed immediately. If you wrap it in a function, you'll see it's not being called at all.

Have you tried hooking into the 'error' event? Taken from this page: http://api.jquery.com/jQuery.ajax/

Quote:error
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )
A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests. This is an Ajax Event.




Theme © iAndrew 2016 - Forum software by © MyBB