In the following example I am able to pass JSON representation of the country list and display it but I cannot display the message "Could not find any countries". Could you please check the code below:
Controller:
if ($this->model_abc->did_get_country_list($user_id)) {
$country["results"]= $this->model_abc->did_get_country_list($user_id);
echo json_encode($country);
}
else {
$country = array('message' => "Could not find any countries" );
echo json_encode($country);
}
JS file:
$.post('cont/get_country_list', function (country) {
$.each(country.results, function(i, res) {
var item = $('<div>'),
title = $('<h3>');
title.text(res);
item.append(title);
item.appendTo($("#country_list_is_got"));
});
},
"json").error(function() {
$( "#country_list_is_not_got").text(country.message);
});
Update:
I changed my code as following and now I get thise error from console: Uncaught TypeError: Cannot read property 'length' of undefined.
JS file:
$.post('cont/get_country_list', function (country) {
if (country.message !== undefined) {
$( "#country_list_is_not_got").text(country.message);
} else {
$.each(country.results, function(i, res) {
var item = $('<div>'),
title = $('<h3>');
title.text(res);
item.append(title);
item.appendTo($("#country_list_is_got"));
});
}
});
You're not setting an error reply code in the case where no countries are found, so it's not treated as an error by jQuery.
else {
header("HTTP/1.1 500 Error");
$country = array('message' => "Could not find any countries" );
echo json_encode($country);
}
Also, your error function needs to get the data from its parameter:
.error(function(xhr) {
country = $.parseJSON(xhr.responseText);
$( "#country_list_is_not_got").text(country.message);
});
The error-function is only called when the server responses with a 500-HTTP code (or 404, 403 or a timeout etc.). You are returning just valid JSON with a normal HTTP status-code, so the success-function is called. Within that success-function you should check if there was a message or not:
$.post('cont/get_country_list', function (data) {
if (data.message !== undefined) {
$( "#country_list_is_not_got").text(data.message);
} else {
$.each(country.results, function(i, res) {
var item = $('<div>'),
title = $('<h3>');
title.text(res);
item.append(title);
item.appendTo($("#country_list_is_got"));
});
}
});