Background: I’m working on a management page for musicians. Lets say the user creates an album, then uploads a song into the album. I’m using ajax posts with the jQuery form plugin.
First, I worked on uploading songs into existing albums (works great).
Then, I worked on creating new albums and showing up without a refresh using .append() and .attr (works great).
Now I’m working on uploading a song to the album that showed up thanks to the append()’s.
Problem: When the album that is created is prepared, it’s grand. All the values and functions are the exact same as the album loaded when the page renders.
When I attempt to upload a song, I get an error server-side. It takes the exact same functions i’m using to upload a song to the ajaxed album as the initial page rendering album.
I refresh the page, and I can upload a song.
I’m using jQuery.form plugin, and I thought it would be because the function was inside the $(document).ready(function { … }
the uploading script:
$('form#uploadSongToAlbum').submit(function() {
$(this).ajaxSubmit({
target: 'login/uploadSongToAlbum.php',
dataType: 'html',
beforeSubmit: function() {
alert(showRequest);
$.jGrowl("Uploading... hold on...<br />", { life:1000 });
},
success: function() {
selectUploadedID();
},
error: function() {
$.jGrowl(textStatus, { header:"<span style='color:red'>Error:</span>", sticky: true });
}
});
return false;
});
Now, looking further into the problem, I opened up the console in Chrome, went to network and recorded the posted requests for both the ajaxed upload and the page-loaded upload, and I discovered very different values.
Here are the ajaxed upload post values (this one breaks):
Form Data:
file:silence2.mp3
album:80
and here are the page-loaded post values (this one works):
Request Payload:
——WebKitFormBoundaryZpJpGxBLJEBRYadH
Content-Disposition: form-data; name=”file”; filename=”silence2.mp3″
Content-Type: audio/mp3——WebKitFormBoundaryZpJpGxBLJEBRYadH
Content-Disposition: form-data; name=”album”
80——WebKitFormBoundaryZpJpGxBLJEBRYadH–
Thank you soo much in advance, everyone. I must be doing something wrong. I can provide more code if necessary. Keep in mind: The html markup and values for both ajaxed albums and page-loaded albums are valid. It must be something jQuery that I’m doing wrong…
Try adding the
enctypeattribute to the form tag of the dynamically created content:Also, if your uploading script is called from within
$(document).ready, it will only be called once when the page loads. If you want it to apply to dynamically created forms, use the `live()’ method: