for this specific problem i am using Tag-it https://github.com/aehlke/tag-it , a jQuery plug-in that is specific to using tags
I have a list of tags i am using ajax to populate using jQuery ui autocomplete
What I need to do is issue a return false to a specific function BeforeTagAdded when the ajax call returns false, essentially saying the database rejected this tag entry, do not show the tag in the client browser
The developer states that "To clarify, just return false in your callback to reject the tag." that is what i am trying to accomplish
What I have tried in addition to the below code:
The only thing the ajax call returns is a result:true or result:false in the meantime I will work up a jsfiddle in addition to the below code
beforeTagAdded: function(event, ui) {
if ( !ui.duringInitialization){ //do not fire on page initialization
$.ajax({
url: "handlers/tags.ashx",
dataType: "json",
data: {
idnumber: entity_id,
tag: ui.tagLabel,
operation:"tag"
}
}).done(function(data){
if(data.result == false){
event.preventDefault();
event.stopPropagation();
}
}).complete(function(data){
});
}
},
Ajax is asynchronous. complete
/ done
/ success
/ etc are event handlers. They won't fire until the event representing the receipt of the HTTP response has arrived.
You can't return from inside those event handlers, or modify the event from the beforeTagAdded
function because the beforeTagAdded
will have finished and returned before the HTTP response is received.
You need to rethink your approach. This will probably involve always canceling the beforeTagAdded
event, but programmatically restarting it from inside the Ajax event handler.
beforeTagAdded: function(event, ui) {
if ( !ui.duringInitialization){ //do not fire on page initialization
event.preventDefault();
event.stopPropagation();
$.ajax({
url: "handlers/tags.ashx",
dataType: "json",
data: {
idnumber: entity_id,
tag: ui.tagLabel,
operation:"tag"
}
}).done(function(data){
if(data.result != false){
something(); // that would have happened if you hadn't called preventDefault before
}
}).complete(function(data){
});
}
},
Why don't you just separate your AJAX from the beforeTagAdded function and use beforeTagAdded as a callback?
Something like this:
beforeTagAdded : function (event, ui, data) {
if (!ui.duringInitialization) {
// do something with the data
}
},
initAjax : function(event, ui) {
// make sure entity_id is defined
var entity_id = '';
$.ajax({
url: "handlers/tags.ashx",
dataType: "json",
data: {
idnumber: entity_id,
tag: ui.tagLabel,
operation:"tag"
}
}).complete(function (data) {
beforeTagAdded(event, ui, data);
});
}
Then elsewhere in your code wherever you call beforeTagAdded()
switch it to initAjax()
. Now you have the ajax data inside of beforeTagAdded to do whatever you need to do with it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.