Php函数返回是一个使用Ajax的空数组,否则不是
I'm using CakePHP framework. My problem is that when I print a php function then it gives me an array with a lot of members but when using the same function with Ajax then the response is empty.
Ajax response function:
public function functionOne(){
$this->autoRender = false;
if ($this->request->is('ajax')) {
if(!$this->request->data['amount']) {
$json['errors'][] = 'Fill in all the required fields';
}elseif(!is_numeric($this->request->data['amount'])){
$json['errors'][] = 'Field amound has to be a number';
}
if(!$this->request->data['currency_from']){
$json['errors'][] = 'Fill in all the required fields';
}
if(!$this->request->data['currency_to']){
$json['errors'][] = 'Fill in all the required fields';
}
if(!$this->request->data['rate_date']){
$json['errors'][] = 'Fill in all the required fields';
}
if(isset($json['errors'])){
$json['status'] = 'error';
}else{
$json['status'] = 'success';
$json['curs'] = $this->functionTwo($this->request->data['date1']);
$json['rates'] = $this->functionThree($this->request->data['date'], $this->request->data['from'], $this->request->data['to'], $this->request->data['amount']);
}
print_r(json_encode($json));
}
}
View file ajax request:
$(document).ready(function(){
$('#converter').on('submit', function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
url: '<?php echo $this->Html->url(array(
"controller" => "cur",
"action" => "functionOne"
));
?>',
data: form.serialize(),
type: 'post',
async: true,
success: function (data) {
var json = data;
if (json.status == 'error') {
$('#errors').show();
$('#currencies').hide();
$('#errors').html('');
$.each(json.errors, function (k, v) {
$('#errors').append("<span>" + v + "</span>");
});
}
if (json.status == 'success') {
var json = data;
$('#errors').hide();
$('#currencies').show();
}
}
});
})
});
getCur method returns an array in format "code" => "name". It gets the currencies from reading different sources XML files. When I print the function outside of the response it gives me a correct result but with ajax it just gives me an empty array.
Errors are coming through the response though.
Thanks!
Mistake was that I created the instances inside the method so ajax thought that I did not have any.
Thanks for replying!
What version of Cake are you using??
Depends on the version of cake.
1.3.x:
$this->RequestHandler->isAjax();
2.x
$this->request->is('ajax');
Also can you check your chrome network tab for any specific issue.
Try to :
- echo your json like
echo json_encode($json);
-
In success callback, parse data variable by using :
success : function(data){ var json = $.parseJSON(data); console.log(json); }
See the data inside console.