I hope you can help me. I’ve successfully coded some lines to make a CHtml::textField to dispatch an AJAX request, via its ‘ajax’ property.
However, the contents of the widged needs a mask, so I should switch from CHtml::textField to CMaskedTextField. The problem is that the latter has no ‘ajax’ support.
Is there any workarounds available? Thanks in advance.
I’ve managed to find a solution. I just put the following code at the bottom of the view containing the widget which should dispatch the AJAX request.
<?php
if (! Yii::app()->clientScript->isScriptRegistered('scriptkey', CClientScript::POS_READY)) {
$fn_success = 'function(json) {
// The body of your success function goes here
}';
$fn_error = 'function(jqXHR, textStatus, errorThrown) {
// Just to let the user know if anything goes wrong
alert(textStatus);
}';
$fn_before_send = 'function(jqXHR, textStatus) {
// Turn "Please wait..." message on. I used a CJuiDialog for that.
$("#wait").dialog("open");
}';
$fn_complete = 'function(jqXHR, textStatus) {
// Turn "Please wait..." message off
$("#wait").dialog("close");
}';
// Determines the absolute path to the action to be called via AJAX.
// This step is mandatory, as Yii won't help here.
$url = Yii::app()->request->baseUrl . '/controller/action';
// Picks up the ID of the element on whose change AJAX will be dispatched
$element = CHtml::activeId($model, 'my_masked_text_field');
// Putting it all together
$script = "
$('#$element').change(function() {
$.ajax({
type: 'POST',
url: '$url',
cache: false,
success: $fn_success,
dataType: 'json',
data : $('form').serializeArray(),
error: $fn_error,
beforeSend : $fn_before_send,
complete: $fn_complete
});
});
";
// Register the above script in jQuery's ready() function
Yii::app()->clientScript->registerScript('scriptkey', $script, CClientScript::POS_READY);
}
?>
Anyway why do you think CMastedTextField does not have ajax support… if you check the source… you will see that it calls CHtml::textField() so if it works there should work even here…
You should be right. Nevertheless, I didn’t manage to work with AJAX in CMaskedTextField directly. I’ve got an error, something like “CMastedTextField has no ‘ajax’ property”. The solution I found was to handle jQuery AJAX capabilities without the intermediation of Yii.