synapseradio
synapseradio

Reputation: 35

AJAX (jquery) to run PHP script not working

I am trying to make an ajax call to a php script that outputs images from a directory.

I have this as my php script:

<?php

 $con = @mysqli_connect('myhost','myusername','myuserpass','myuserDB') or die('Could not connect to the database.'." ". __FILE__ ." ". __LINE__);

 $photoFile = mysqli_query($con, 'select photoFile from photoInfo');
  while ($p = mysqli_fetch_array($photoFile)){
    echo '<img class="image" src='."../img/".$p['photoFile'].".jpeg />";
  };
 mysqli_close($con);

?>

And I'm trying to call it like this.

$(document).ready(function() {

   $.ajax({
       url: 'php/getImages.php',
       method: 'get',
       dataType: 'html'
           }).done(function(data){
          $('#imageBox').appendData(data);
     });
  });

What all am I doing wrong? When I run the php script on its own, it brings up the images but when I try to use ajax to call it, nothing happens.

Upvotes: 1

Views: 152

Answers (4)

Pushker Yadav
Pushker Yadav

Reputation: 856

put the breakpoint in data that in coming from server [your php script] and check it, it coming in right format or not.

Upvotes: 0

Krish R
Krish R

Reputation: 22711

Can you try this, use $('#imageBox').html(data); instead of $('#imageBox').appendData(data);

<script type="text/javascript">
    $(document).ready(function() {

            $.ajax({
                url: 'php/getImages.php',            
                method: 'get',
                dataType: 'html'
            }).done(function(data){
                $('#imageBox').html(data);
            });
        });

</script>


  <div id="imageBox"></div>

In getImages.php,

    <?php

    $con = @mysqli_connect('myhost','myusername','myuserpass','myuserDB') or die('Could not connect to the database.'." ". __FILE__ ." ". __LINE__);

    $photoFile = mysqli_query($con, 'select photoFile from photoInfo');
    while ($p = mysqli_fetch_array($photoFile)){
        echo '<img class="image" src="../img/'.$p['photoFile'].'.jpeg" />';
    };
    mysqli_close($con);

    ?>

Upvotes: 1

Harish Singh
Harish Singh

Reputation: 3329

$photoFile = mysqli_query($con, 'select photoFile from photoInfo');
while ($p = mysqli_fetch_array($photoFile)){
    $imgpath = "../img/".$p['photoFile'].".jpeg";
    echo '<img class="image" src="'.$imgpath.'" />';
};
mysqli_close($con);

Upvotes: 0

AAA
AAA

Reputation: 142

Try this code:

  while ($p = mysqli_fetch_array($photoFile)){
           $img_arr[]= '<img class="image" src='."../img/".$p['photoFile'].".jpeg />";
  };
echo json_encode($img_arr);
exit;

In javascript

$.get('php/getImages.php',function(data)
  $.each(data,function(k,e){
     html+=e;

});
$('#imageBox').appendData(html);
},'json');

Upvotes: 0

Related Questions