If the request succeeds and truly returns a blank string, your check would be fine, although you don't need the second half of it. E.g.:
if (data) {
// Yes it's there
} else {
// No, it's blank
}
...is sufficient. But if it may have any whitespace, you'll need to trim
first:
if (data.trim()) {
// Yes it's there
} else {
// No, it's blank
}
(Some old browsers like IE8 may not have trim
, but you can easily shim/polyfill it.)
To handle the error case, add a .fail
handler; for cleanliness, let's move the success handler to .done
as well, remove the declaration of the argument we're not using, and remove the unnecessary blank object.
That gives us:
$.post('blog.php')
.done(function(data){
if (data.trim())
{
$("#readmore").before(data);
}
else
{
alert('no more text');
}
})
.fail(function() {
// it failed
});
Note that that assumes the Content-Type
on the response is text/html
or text/plain
or similar, and so you'll get back a string. From what you've said, that's probably true.
You can always see exactly what's going on by using the debugger built into your browser:
Open the developer tools using the menu or F12 (on IE and some others) or Ctrl+Shift+I (Chrome and some others, I think it's Cmd+Shift+I on Mac OSX).
Switch to the Source tab (perhaps called Debugger on IE)
Find your code, there's usually some way to browse the loaded scripts.
Click in the left-hand gutter (next to the line number) of the first line in your done
handler and a red mark or bar should appear, which means there's a breakpoint there that will stop your code. Do the same for the first line inside your fail
handler.
Trigger the post operation. One of your breakpoints should get hit, causing execution to stop at that point.
If it's in the done
handler, hover your mouse over data
to see exactly what's in it (or switch to the "Console" tab, type data
, and press enter, and it will show you the content of the data
argument).