Reputation: 721
I'm trying get a simple ajax call working with yii, not using the native yii means. My goal is to populate state and city fields on input from a zip code field, using a db look up in the create action. I have a separate javascript file,
$('#Accounts_zip').bind('focusout',function(){
$.ajax({
type: 'POST',
url:'/gatesadmin/index.php?r=Accounts/Ziplookup',
data: {zip:$('#Accounts_zip').val()},
success: function(datain, textStatus, jqXHR) {alert(datain.statecode);} ,
error: function(jqxhr, textStatus, errorthrown){alert(errorthrown);},
dataType:JSON
});
alert($('#Accounts_zip').val());
});
and in my AccountsController I have:
public function actionZiplookup()
{
$z = new ZipDao();
$row = $z->GetCityStateByZip($_REQUEST['data']);
header('Content-Type: application/json; charset="UTF-8"');
echo CJSON::encode(array('output'=>$row));
}
and my form is out of the box generated CRUD:
...
<div class="row">
<?php echo $form->labelEx($model,'zip'); ?>
<?php echo $form->textField($model,'zip',array('size'=>10,'maxlength'=>10)); ?>
<?php echo $form->error($model,'zip'); ?>
</div>
...
I know the javascript is working because I get my alert, and if I call the URL directly yii fires the actionZiplookup event because I'm getting the returned json. I just can't seem to be able to get the form to invoke the ajax successfully because I get External Server error in the jquery ajax failure event. I've combed through the net and the closest examples I can find embed the javascript in the form itself and use the Yii::app()-createUrl() method to define the url, but there has to be a way getting the controller action to fire while keeping javascript code in a separate file.
Any help would be greatly appreciated.
Upvotes: 0
Views: 757
Reputation: 721
It turns out what I was missing can be found here: How to get response as json format(application/json) in yii? It all has to do with telling the controller to ignore the layout, etc.
Upvotes: 0