Hi all,
I have a function runAjax that functions correctly. Unfortunately I am struggling to return the value I get from the ajax query.
The ajax function assigns the returned value inside "contents" or "error" xml tags to the variable "result".
If I alert the result variable inside the ajax function it alerts the correct value (i.e if the xml value inside contents is "published" it alerts published).
However if I alert the returned value from the runAjax function it alerts an object instead of the value of the internal variable "result" which in the above example is "published".
function runAjax (data_obj){
return $.ajax({
url:"/ajax.php",
dataType: "xml",
data: data_obj,
success: function(data) {
// format result
var xml;
if (typeof data == "string") {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
var result;
if($("error",xml).text()){
result = [$("error",xml).text()];
} else{
result = [
$("contents", xml).text()
];
}
alert(result); //alerts the correct string for example "published"
return result;
}
});
}
$('ul.content li span.changeable').click(function(e){
e.preventDefault();
var method_set = $(this).parent().attr("class");
var id_set = $(this).parent().parent().find('li.id span').html();
var user = $(this);
var result = runAjax({method: method_set, id: id_set});
alert(result); //alerts an object not published
});
Im sure it has something to do with the way I am returning the variable but I can't figure it out. Any input would be much appreciated.
Regards Luke
UPDATE: This is the revised code that works thanks to all the input from people below:
function runAjax (data_obj,callback){
$.ajax({
url:"/ajax.php",
dataType: "xml",
data: data_obj,
success: function(data) {
// format result
var xml;
if (typeof data == "string") {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
var result;
if($("error",xml).text()){
result = [$("error",xml).text()];
} else{
result = [
$("contents", xml).text()
];
}
if ( typeof(callback) == "function") {
callback(result);
}
}
});
}
$('ul.content li span.changeable').click(function(e){
e.preventDefault();
var method_set = $(this).parent().attr("class");
var id_set = $(this).parent().parent().find('li.id span').html();
var user = $(this);
runAjax({
method: method_set,
id: id_set
},
function(result){
$(user).html(result.join('')); //this is instead of alert(result);
}
);
});