views:

82

answers:

1

I am having trouble with uploading a file when using jquery.

I have the following HTML in a form.

<fieldset>
  <ul>
    <li> 
      <div class="field"><input size="35" type="file"
                             name="formFile" id="formFile"/></div> 
    </li>
    <li> 
      <div class="field"><input size="35" type="text" 
                             name="formFileName" id="formFileName" /></div>
    </li>
  </ul> 
</fieldset>

To post the data I am using $('#myForm').ajaxForm(

When I post the data and the recieved data contains some javascript, the javascript is not recognised.

I expected the javscriptcode to run when the data is recieved, but it happens to early. The results indicates that $ or jquery could not be found.

If I remove the name attribute from the input type=file element, there are no errors, but that is not the correct solution.

How could this happen?

A: 

You'll certainly need to ensure that the embedded JS is part of a callback function.

$('#myForm').ajaxForm(function() { 
  //Do your JS execution
}); 

I personally am not a fan of the abstracted $.get(), $.post() .$ajaxForm(), etc. since they remove so much of the functionality of the $.ajax() methods.

If it is important that you use the ajaxSubmit() method it takes any of the other $.ajax parameters so you'll probably want to async:false and set up success/error callbacks.

// attach handler to form's submit event 
$('#myFormId').submit(function() { 
    // submit the form 
    $(this).ajaxSubmit({
                       success: function(result){ callbackFunction(result); }
                       ,error: function(msg,XMLStatus,err){ errFunction(msg,XMLStatus,err); }
                       }); 
    // return false to prevent normal browser submit and page navigation 
    return false; 
});

Hopefully this should clear up some of the issue.

iivel