Bjorn Lottering
Bjorn Lottering

Reputation: 83

Execute PHP on server with AJAX

Hi I am trying to get ajax to execute code on the server and return the result:

<script>
    $(document).ready(function(){
        $.post('includes/gallery/gallery.php', function(data){
            $('#galleryTab').html(data);
        });
    });
</script>

class Main{
public static function generateGallery(){
    $path = 'includes/gallery/';
    $results = glob($path . '*' , GLOB_ONLYDIR);
    $dirCount = 0;
    foreach ($results as $result) {
        $resultBaseName = basename($result);
        if ($resultBaseName === '.' or $resultBaseName === '..') continue;
        echo '<h2>'.$resultBaseName.'</h2>';
        if (is_dir($path . '/' . $resultBaseName)) {
            $dir = $path.$resultBaseName.'/';
            $images = glob($dir."*.jpg");
            $imageCount = 0;
            foreach($images as $image) {
                echo '<div class="galleryImage" id="openImage'.$imageCount.$dirCount.'"><img src="'.$image.'" /></div>';
                $imageCount++;
            }
        }
        echo '<br />';
        $dirCount++;
    }
}
}

It is not executing the PHP on the server, please help

Upvotes: 1

Views: 865

Answers (2)

Jijo John
Jijo John

Reputation: 1375

The code you provided is not enough. You should Return your result from the function as an array and encode it with json_encode php function or in any other interchange formats. see the below statement.

            $returnResult = json_encode($array);

Then use $.ajax({}) jquery method in your client side. See the example below.

 $.ajax({

      url : url , // <-your url here
      method : post or get ,
      data : { field: value }, //provide the values you are passing  <-
      dataType: json or html,  //data interchange format
      success : function(data){

        console.log(data.value);

       }

      });

see jquery $.ajax({}) documentation here Jquery documentation link

Upvotes: 1

tcak
tcak

Reputation: 2212

You defined your class and its method there, but you are not calling it based on the code you show us. Call the "generateGallery" method from "main" class, and it should work.

Upvotes: 1

Related Questions