In my application im getting the data from database using ajax call as json array data. But some times i may not get the data from database based on condition. How can i check whether there is any data in the ajax returned array.
Here is my code..
Ajax Call:
$.ajax({
type:'POST',
url:'user_panel/index',
data: 'ov_prem_home_id='+home_id,
dataType: 'json',
cache: false,
success: function(dataResponse){
document.getElementById('ov_prem_title').value=data[0]['title'];
}
});
PHP Code
$home_id=$_POST[home_id];
$ov_result=getPremOveriewData($home_id);
echo json_encode($ov_result);exit;
I tried the conditions like isset(dataResponse),if(dataResponse=='')
but i didn't got anything
If what you want is to check the data from the Javascript end, you could use something like:
$.ajax({
type:'POST',
url:'user_panel/index',
data: 'ov_prem_home_id='+home_id,
dataType: 'json',
cache: false,
success: function(dataResponse){
if (data && dataResponse.length>0 && dataResponse[0]['title'])
{
document.getElementById('ov_prem_title').value=dataResponse[0]['title'];
}
else
{
//Empty
}
}
});
The simple way:
success: function(dataResponse){
if(!dataResponse){
// its empty
}
}
And also you could insure yourself a bit more by doing this in PHP:
echo (empty($ov_result) ? null : json_encode($ov_result));exit;
This will return nothing (null
) if $ov_result
is empty
If the response is empty it will evaluate to false, so simply do if(dataResponse)
$.ajax({
type:'POST',
url:'user_panel/index',
data: 'ov_prem_home_id='+home_id,
dataType: 'json',
cache: false,
success: function(dataResponse){
if (dataResponse) {
document.getElementById('ov_prem_title').value=data[0]['title'];
}
}
});
$.ajax({
type:'POST',
url:'user_panel/index',
data: 'ov_prem_home_id='+home_id,
dataType: 'json',
cache: false,
success: function(dataResponse){
if(typeof dataResponse != 'undefined' && dataResponse.length > 0 )
document.getElementById('ov_prem_title').value=data[0]['title'];
}
});