1

i want to use the value of a php variable within a jquery ajax function. i however first need to test if the variable has value.

i know that i can test the length of a object like this:

if ($(selector).length)

i am not sure how i can test if a jquery variable has value. below is my test;

 $idAjax = 15;

<script>
jQuery(document).ready(function(){

 function ajaxMessagesCount(){   

      var  theData =  <?php echo $idAjax ?>;

  if (theData.length){
//do somting
}

})
</script>
6
  • Is there any problem with .length? Commented Aug 4, 2015 at 8:36
  • The only jQuery you have is the document.ready. The rest is plain JavaScript Commented Aug 4, 2015 at 8:41
  • I think you just need to enclose <?php echo $idAjax ?> with double quotes. Then your test will work just fine. Commented Aug 4, 2015 at 8:46
  • No he does not. See other answers and their comments. The value is an integer Commented Aug 4, 2015 at 8:46
  • even though it is an integer the fact that it is enclose with double qoute it will be converted to string so checking the length of the variable will work just fine. Commented Aug 4, 2015 at 8:47

1 Answer 1

0

If you want to check if variable exists, and it's not empty, try this:

if (typeof variable !== 'undefined' && variable)
Sign up to request clarification or add additional context in comments.

2 Comments

Your code will fail if the value of the $idAjax is falsy. Such as the valid value 0
if its valid value it ok to use only typeof part

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.