I need to return multiple values from a ColdFusion function in an ajax callback function. Here's what I've got:
$('input[name="StateName"]').live('change', function() {
var StateID = $(this).parents('tr').attr('id');
var StateName = $(this).val();
$.ajax({
url: 'Remote/State.cfc'
,type: "POST"
,data: {
'method': 'UpdateStateName'
,'StateID': StateID
,'StateName': StateName
}
,success: function(result){
if (isNaN(result)) {
$('#msg').text(result).addClass('err');
} else {
$('#' + result + ' input[name="StateName"]').addClass('changed');
};
}
,error: function(msg){
$('#msg').text('Connection error').addClass('err');
}
});
});
If I trap a database error, then the success callback is fired, and the result is Not a Number (It is in fact, the text of the error message). I need the function to also pass back other values. One might be the primary key of the row that caused the error. Another might be the old StateName, so that I can refresh the old value on the screen so that the client will know absolutely for sure that their change did not take effect.
I guess I'm breaking the rule of atomicity here and need to fix that, because I'm using result as both the primary key of the row that was updated, or it's the error message if the update fails. I need to return both the primary key and the error message.
Your remote function could return a **JSON string**, containing an object, I suppose.
It would allow you to have several values inside a single "value".
And JSON being Javascript Object Notation, it's quite easy to read it in Javascript -- and there are libraries to serialize data to JSON in lots of languages.
For example, here's a JSON string :
{"status":1,"message":"this is a message","data":{"test":"plop","hello":"world"}}
This corresponds to an object with 3 properties :
status
message
data
; which is itself another object, that contains two properties.Returning this kind of string from your AJax call should not be too hard -- and that's a pretty flexible, and really prowerful, system.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With