user1351482
user1351482

Reputation: 379

$.post AJAX request: How to check if returned value is empty

I have an AJAX call using the $.post() method and wanted to know how I can check if the returned value is empty or not.

This is the code:

$.post(site_url, function(data) {
    if(!data) {
      alert('Nope');
    } else {
      alert('Yay');
    }
});

But this does not work. I also tried checking if the object is NULL or =="", but still no effect..

EDIT

data.length made the job! Thanks, guys

Upvotes: 0

Views: 3487

Answers (4)

Domain
Domain

Reputation: 11808

Try this :

If the string comparison with ajax-response fails, then try sending numeric value in ajax-response and compare.

**demo.php**
<php
$temp = some_function();
//If the function returns null then send 1, else the value returned
if(temp!='')
   echo 1;
else
  echo $temp;
?>

$.post(demo.php, function(data) {
if (data != 1)
{
  alert('null');
}
else
{
  alert(data);
}
});

Upvotes: 0

rajukc47
rajukc47

Reputation: 11

Try this.

$.post(site_url, function(data,status) {
    alert("Status="+status);
});

This will display the status of ajax request("success", "notmodified", "error", "timeout", or "parsererror")

Upvotes: 1

Moeed Farooqui
Moeed Farooqui

Reputation: 3622

Try this:

   $.post(site_url, function(data) {
        if(!empty(data)) {
        alert('Yay');  
        } else {
        alert('Nope');
        }
    });

Upvotes: 0

Subhajit
Subhajit

Reputation: 1

You can try this

typeof(data.responseText) === null

Upvotes: 0

Related Questions