.on('complete', function(id, name, response) {
console.log(id);
console.log(response);
console.log(name);
$("input").attr({
type: 'hidden',
name: id
}).val(name).appendTo('form');
})
.on('deleteComplete', function(id, xhr, isError) {
console.log(name);
$('input[name=' + id + ']').remove();
});
I'm using latest FineUploader to upload images and add the image filenames as hidden fields (correct way) to post their location to PHP for further processing.
The issue is id is common between the two callbacks but it returns an object and I'm sure how to handle it. I just need to store/post the filename location to PHP.
The parameters for your callbacks are incorrect. If you are using the jQuery plug-in wrapper for Fine Uploader, each event handler always has an initial parameter of Event. That is, the jQuery event object associated with the event you are handling.
Just to be clear, you code should look like this:
.on('complete', function(event, id, name, response) {
...
})
.on('deleteComplete', function(event, id, xhr, isError) {
...
});
This is one of many reasons why I have advised users to avoid using the jQuery plug-in wrapper. It makes working with Fine Uploader callbacks more confusing, and provides absolutely no benefits. In light of this, if you still want to use the jQuery plug-in wrapper for some reason, you should consider declaring your callback handlers as part of a callback option passed as part of the initial configuration options when constructing a Fine Uploader instance.
Related
I'm trying to add a link to delete a row from a mysql database using jquery and ajax. The data is currently displayed in a table. For some reason, the Click event isn't triggering.
Here's my AJAX call:
<script>
$(document).ready(function() {
/* load table with page load*/
$("#sort tbody").load("inc/index_table.php");
/* row deletion */
$(".deletelink").click(function(){
var id = $(this).attr("id");
$.ajax({
beforeSend: function (request) {
var answer = confirm("Are you SURE you want to delete this?/nThis action is NOT reversible.")
if (answer){ return(true); }
else { return(false); }
},
type: "POST",
url: location.href,
data: "delete="+id,
error: function() {
console.log("Theres an error with AJAX deletion");
},
success: function(){ //a.td.tr.remove just that row rather than the whole table
$this.parent().parent().remove();
console.log("Deleted.");
}
});
});
});
</script>
And the relevant HTML:
this is part of a while loop that prints a table from my database:
<td><a class="deletelink" id="'.$row["id"].'"><img src="images/delete.png" alt="Delete"></a></td>';
My code specifies <a class="deletelink"> but it's not registering with $(".deletelink").click(function(){ });
Does anyone see what could be wrong here or have an alternate method to suggest?
Looks like you are loading the elements dynamically. You can only bind to elements which currently exist in the DOM. To bind to elements which you are about to add, you must attach the event to a static element, the closer it is to the dynamic content, the better.
Try using on() with a delegate.
$("#sort tbody").load("inc/index_table.php");
/* row deletion */
$("#sort tbody").on("click", ".deletelink", function(){
//...rest of code the same
});
on() was added in jQuery 1.7. If you are using a previous version, but higher than 1.4.2 you can use delegate() instead.
$("#sort tbody").load("inc/index_table.php");
$("#sort tbody").delegate(".deletelink", "click", function(){
//...rest of code the same
});
If #sort or tbody of $("#sort tbody") is also dynamic then $("document").on("click", "#sort tbody .deletelink", function(){...}) would work as well, though anything closer than document is better off course.
Edit
I'm just looking at your code again, the delegate binding should work, however, using load()'s success callback should work with your existing code too.
The callback is executed ones load has successfully completed. I'm not 100% certain but I'm assuming that when success is called that the elements already have been loaded into the DOM and as such the normal bindings should work.
If that doesn't work the dynamic bindings mentioned above should.
$("#sort tbody").load("inc/index_table.php", function(){
/* row deletion */
$(".deletelink").click(function(){
// .. your code as before.
});
});
to make sure the table is fully loaded, try to declare the click function, in the callback of .load() like,
$("#sort tbody").load("inc/index_table.php", function() {
/* row deletion */
$(".deletelink").click(function(){ ....
});
});
Try using .on() to bind the events to the elements
$(".deletelink").on('click',function(e){
e.preventDefault();
Also make sure to add preventDefault to stop the default functioning of the link
The problem is that your delete link appears after the table loads. So when page was loaded and DOM tree was built, it wasn't there. So you can't attach a click to it.
You can try live(). This can be used as
$(".deletelink").live('click',function(){
// ajax call handling code here
});
This function attaches event after the element has been introduced in the DOM. However, this function is a bit greedy as it keeps on scanning entire DOM tree on any DOM change. So use with caution
Interested in building my own drag'n'drop file uploader using JQuery/AJAX/PHP.
Basically I want a file-uploader that users of my site can just drag the file from their computer into a div I created, and it will then upload the file for them to the selected destination.
I would like to build this from scratch, and not use any plugins so that I can better manipulate the restrictions (file types, size, destination folders, etc.)
Have scoured google with no luck, only plugins. Can anyway steer me in the right direction?
UPDATE
Ok, so I figured out how to do what I want. Just set the file input field opacity to 1 so it is hidden, and you can still drag a file into that general area and if you hit the text field it will catch it. HOWEVER, I would like to know how to increase the height/width on the file input field (tried basic css on the file, but it only increases the 'browse' button size and not the actual field where you can drop the file into. Any ideas how to do this?
I basically want a big square div that says 'Drop file here'. So I need to resize the input field.
Just to chime in here, as I've been doing this as well the last couple of days. From what I understand if you're binding the drop event through jQuery you need to access that event.dataTransfer object by going through the event.originalEvent object in the event provided by jQuery.
Example:
In this I bind to both the dragover as well as drop events, as this was necessary to prevent it from performing the default action (found that solution here: Prevent the default action. Working only in chrome )
$('#dropzone').bind('dragover drop', function(event) {
event.stopPropagation();
event.preventDefault();
if (event.type == 'drop') {
console.log(event.originalEvent.dataTransfer.files);
}
});
Also there seems to be a bug where if you console.log() the event.dataTransfer (or event.originalEvent.dataTransfer) it's files array is empty, it's pointed out here: event.dataTransfer.files is empty when ondrop is fired?
To better answer the OPs question (I just noticed the rest of it, and I know it's old but some one might find this helpful):
My implementation is in jQuery, so I hope that's alright:
var files = [];
// Attaches to the dropzone to pickup the files dropped on it. In mine this is a div.
$("#dropzone").bind('dragover drop', function(event) {
// Stop default actions - if you don't it will open the files in the browser
event.stopPropagation();
event.preventDefault();
if (e.type == 'drop') {
files.push(event.originalEvent.dataTransfer.files);
}
});
// Attach this to a an input type file so it can grab files selected by the input
$("#file-input").bind('change', function(event) {
files.push(event.target.files);
});
// This is a link or button which when clicked will do the ajax request
// and upload the files
$("#upload-button").bind('click', function(event) {
// Stop the default actions
event.stopPropagation();
event.preventDefault();
if (files.length == 0) {
// Handle what you want to happen if no files were in the "queue" on clicking upload
return;
}
var formData = new FormData();
$.each(files, function(key, value) {
formData.append(key, value);
});
$.ajax({
url: 'upload-ajax',
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
processData: false, // Don't process the files - I actually got this and the next from an SO post but I don't remember where
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR) { /* Handle success */ },
error: function(jqXHR, textStatus, errorThrown) { /* Handle error */ }
});
});
You could also bind to the other events in the accepted answer for doing effects like making the dropzone fade in so you can see it (that's on my todo list for my library). This is the core of the actual ajax file uploading I use, however.
I don't really have a convenient way to test that, but that's in essence how I did it (I essentially took all that code from the library I've been making and adapted it to fit a general code block on here in an easy to understand way). Hopefully this helps some people out. Starting from here it was actually really easy to go ahead and add in a file queue list, with the ability to delete files from the queue, so this should be a pretty good starting point.
You can use the HTML5 dragenter and dragleave events to create a dropzone.
Then by placing a file input inside the dropzone, and hiding it with CSS, you can upload the file when the change event for the input fires, like this
var dropzone = $("#dropzone"),
input = dropzone.find('input');
dropzone.on({
dragenter : dragin,
dragleave : dragout
});
input.on('change', drop);
function dragin(e) { //function for drag into element, just turns the bix X white
$(dropzone).addClass('hover');
}
function dragout(e) { //function for dragging out of element
$(dropzone).removeClass('hover');
}
function drop(e) {
var file = this.files[0];
$('#dropzone').removeClass('hover').addClass('dropped').find('img').remove();
// upload file here
}
FIDDLE
For those interested, I found this tutorial/demo to be helpful: http://www.viget.com/inspire/custom-file-inputs-with-a-bit-of-jquery/
Basically uses a <span> to cover the default input field.
I need to know how can I add data from the database without refreshing the field ? I mean just like the working of Add Contacts in the Email. If I click the 'Add' button, I need to open a small window and contacts within it. If I check one or two contacts and press insert, it should be inserted in the 'To' field without refreshing the parent page..!!
How can I do that in php or JavaScript ? Please help me :)
You'll need to use ajax to do so. Ajaxform is great plugin for dynamically adding data to a page from a form. You can use $.ajax from jquery as well. http://jquery.malsup.com/form/#ajaxForm
$(document).ready(function() {
var options = {
target: '#output1', // target element(s) to be updated with server response
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
//resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
};
// bind form using 'ajaxForm'
$('#myForm1').ajaxForm(options);
});
or regular ajax
$.ajax({
url : url,
data : {name : name}
dataType : 'json',
success : function(data) {}
});
You have to use AJAX, which today stands mostly for Asynchronous JavaScript And JSON. Since you seem to be new to this, I would strongly suggest using a good AJAX library like jQuery, YUI, Dojo, Prototype, etc. It will make your code much easier than doing it all by yourself, and probably also much more portable across browsers. Search for tutorials related to jQuery, AJAX and PHP. I've seen a good talk by John Resig some time ago who was demonstrating pretty much what you are trying to do with jQuery and PHP using very little code. Unfortunately I can't remember the title or link right now but you should be able to find it with no problems.
I can not quite understand your problem, but I think the dom operation can solve this.
Just take a look this example: http://jsfiddle.net/cyhello/Yfhrp/
Hope it helpful. Good luck!
I am trying to find an AJAX File uploader to use, I think i may go with this on below:
http://valums.com/ajax-upload/
The issue i am having is that i cannot figure out how to make a jQuery AJAX call when the uploader has finished uploading the file. Is this possible? I don't have to necessarily use this specific uploader.
This ajax uploader has an onComplete event callback, so you'll just have to pass your jQuery ajax call to it. Something like this:
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '/server/upload',
onComplete: function(id, fileName, responseJSON) {
// Here comes your jQuery ajax call
$.ajax({
url: 'ajax/post_process.php',
success: function(data) {
// ...
}
});
}
});
Hello try my beta ajax mutiple upload jquery based, simple efficient download it at: http://www.albanx.com/ . no flash, with progress, work over https, support main browsers..
you can use success function for calling the final function
I have a page with a list of items initially loaded from a include_once('show_calendarV2.php'); line.
Next to each item is a delete icon that triggers the following jquery to delete the item from the db and then update the page.
$('.delete_schedule_item').click( function() {
var id = $(this).next('input[type=hidden]').attr('value');
alert ( id );
$.ajax({
url: 'ajax/delete_schedule_item.php',
type: 'post',
data: { id: id },
dataType: 'json', // get back status of request in JSON
success: function(data)
{
//alert( 'item deleted' );
}
// if (data.status) {
// alert('success');
// }
// else {
// alert('error');
// },
//... other parameters/callbacks ...
});
$.get('show_calendarV2.php', {},
function(data)
{
//load the calendar data
$("#calendar").html( data );
});
});
Everything works fine the first time an item is deleted.
The item is deleted.
The new page loads.
But after the page loads the delete buttons? jquery calls? no longer function.
The same page is used to create the initial display as well as the refreshed one so am not sure why the code fails.
Ideas?
Try changing
$('.delete_schedule_item').click(function() {
to
$('.delete_schedule_item').live("click", function() {
If you load a bunch of new html, the function that you ran before wouldn't apply to it anymore. And since you're loading it via Ajax, the function isn't executed again once it's done loading.
The beauty of the live() and die() functions in jquery is that they take care of this situation. Whenever something new is loaded that matches the selector, the new elements are updated automatically.
The reason that it doesn't work any more is that the event handlers are added to the DOM elements themselves. When you load new HTML via AJAX, the old elements with the event handlers attached are removed and new elements, without the handlers are substituted in their place. There are two possible solutions: first, you can reapply the handlers to the newly loaded HTML. Just re-run the code that sets up the event handler on the HTML you've loaded. The other option, which you can use in this case because the click event is handled by live, is to use live event handlers as #womp and #karim79 suggest.
Note that there are some limitations with live handlers - they don't apply to all types of events (click works) and they don't work properly with propagation (i.e., stopping propagation doesn't work). See the jQuery docs for live for more info.
Use event delegation:
$('.delete_schedule_item').live("click", function() {...
Event delegation using live will automatically re-attach event handlers to newly injected elements. When you replace a section of your web page with fresh content via ajax, any event handlers bound to 'old' elements will not automatically get re-attached to the newly injected ones, unless you use event delegation (or re-attach the event handler within your ajax method's callback).
For event delegation with live to work, you will need to be using jQuery 1.3 or greater.