Gags
Gags

Reputation: 3829

PHP function returning null on Ajax call

I have an Ajax Call when tab is clicked in bootstrap 3.0

Below is the JS code

$('[data-toggle="tab"]').click(function (e) {   
   var $this = $(this);
   loadtab = $this.attr('href');
   if(loadtab=="#odhis"){
        var email = $("#email");
        $.ajax({
              type: "POST",
              url: "../orders.php",
              data: {'email':email.val()},
              dataType: "json",
              success: function(response){
               console.log(response);
              },
              error: function(xhr, status, error){
               console.log(xhr.responseText);
              }
       });
    }
});

PHP file orders.php

function getCustomOrderHistory(array $data){
    $cstm = array();
    if( !empty( $data ) ){  
        $trimmed_data = array_map('trim', $data);
        $mail = mysqli_real_escape_string( $this->_con,  $trimmed_data['email'] );
        $checktable = "SELECT * from `orders` WHERE csmail='$mail'";
        $resultcstm = mysqli_query($this->_con, $checktable);
        while($row = mysqli_fetch_array($resultcstm)){
            $cstm[] = $row;
        }
    }
    return $cstm;
}

Now, when i print_r($cstm) then it prints the results in PHP file. but in JS success response is empty.

Any help please?

Upvotes: 2

Views: 73

Answers (1)

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

Since your dataType: "json", instead of return just encode the $cstm array and echo it, like this:

function getCustomOrderHistory(array $data){
    $cstm = array();
    if( !empty( $data ) ){  
        $trimmed_data = array_map('trim', $data);
        $mail = mysqli_real_escape_string( $this->_con,  $trimmed_data['email'] );
        $checktable = "SELECT * from `orders` WHERE csmail='$mail'";
        $resultcstm = mysqli_query($this->_con, $checktable);
        while($row = mysqli_fetch_array($resultcstm)){
            $cstm[] = $row;
        }
    }
    $json = json_encode($cstm);
    echo $json;
}

Upvotes: 2

Related Questions