I have jQuery AJAX function that returns HTML after querying a database. Depending on the result of the query, the function will either return HTML code or nothing (i.e. blank) as desired.
I need to conditionally check for when the data is blank.
$.ajax({
    type:"POST",
    url: "<?php echo admin_url('admin-ajax.php'); ?>",
    data: associated_buildsorprojects_form,
    success:function(data){
        if(!data){  
        //if(data="undefined"){
        //if(data==="undefined"){
        //if(data==null){
        //if(data.length == 0){
        //if ( data.length != 0 ){
        //if(data===0){
        //if(data==="0"){   
            alert("Data: " + data);
        }
    },
    error: function(errorThrown){
        alert(errorThrown);
        alert("There is an error with AJAX!");
    }               
});
I've tried a variety of conditions but none correctly check the data. Based on my findings, a blank alert message does not mean data is
If it's none of these things, how can I therefore conditionally check for the data that yields a blank alert message?
The following correct answer was provided in the comment section of the question by Felix Kling:
if (!$.trim(data)){   
    alert("What follows is blank: " + data);
}
else{   
    alert("What follows is not blank: " + data);
}
                        //if(data="undefined"){
This is an assignment statement, not a comparison. Also, "undefined" is a string, it's a property. Checking it is like this: if (data === undefined) (no quotes, otherwise it's a string value)
If it's not defined, you may be returning an empty string. You could try checking for a falsy value like if (!data) as well
if(data.trim()==''){alert("Nothing Found");}
                        This worked form me.. PHP Code on page.php
 $query_de="sql statements here";
 $sql_de = sqlsrv_query($conn,$query_de);
      if ($sql_de)
      {
        echo "SQLSuccess";
       }
         exit();
and then AJAX Code has bellow
jQuery.ajax({
                    url  : "page.php",
                    type : "POST",
                    data : {
                            buttonsave   : 1,
                            var1         : val1,
                            var2         : val2,
                              },
                  success:function(data)
                           {
                     if(jQuery.trim(data) === "SQLSuccess")
                                   {
                           alert("Se agrego correctamente");
                          // alert(data);
                                      } else { alert(data);}
                              },
                   error: function(error)
                           {
                    alert("Error AJAX not working: "+ error );
                              } 
               }); 
NOTE: the word 'SQLSuccess' must be received from PHP
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With