0

I am trying to integrate an image with movie titles in my auto-complete text-box. For this, I have crawled list of movie titles and their poster links (link to the image of movie) in table "film_Posters" of mysql database.

Question:

Why I get null? Sorry if this question is asked many times, but I really couldn't fix it yet... (Please see the image below):

This is my php file:

<?php
if (isset($_GET['term'])){
    $arr = array();
    try {
        $conn=new PDO('mysql:dbname=imdb;host=localhost', 'user', 'pass');
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $stmt = $conn->prepare('SELECT DISTINCT movieName, posterLink FROM film_Posters WHERE movieName LIKE :term limit 0, 10');
        $stmt->execute(array('term' => '%'.$_GET['term'].'%'));

        while($row = $stmt->fetchAll(PDO::FETCH_ASSOC)) {
                  $arr[]=array('value'=>$row['movieName'], 
                               'label'=>$row['movieName'],
                               'icon'=>$row['posterLink']);                    
         } 
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }

    echo json_encode($arr);
}
?>

and this is my html/javascript file:

<!DOCTYPE html>
<html>
<head>
<link href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.min.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>

<fieldset id = "q27"> <legend class="Q27"></legend>
<label class="question"> What are your favorite movies?<span>*</span></label>
<div class="fieldset content"> 

<div id="m_scents">
<label style="margin-bottom:10px;" for="m_scnts">
<input type="text" id="m_scnt" size="20" name="q27[]"
value="" placeholder="Enter text" />
</label>
</div>
</div>
</fieldset>   

<script type = text/javascript>
(function($){      
  var $title = $('#m_scnt');

  $(function () {
    var arr = <?php echo json_encode($rows); ?>;
  });

  $title.autocomplete({
    minLength: 2,
    source: testfilmsauto.php,
    focus: function( event, ui ) {
      $title.val( ui.item.label );
      return false;
    }
  });

  $title.data( "ui-autocomplete" )._renderItem = function( ul, item ) {

    var $li = $('<li>'),
        $img = $('<img>');  

    $img.attr({    //I AM NOT SURE ABOUT THIS PART 
      src: <?php echo $rows['posterLink']?>,
      alt: <?php echo $rows['movieName']?>
    });   
    $li.attr('data-value', item.label);
    $li.append('<a href="#">');
    $li.find('a').append($img).append(item.label);       
    return $li.appendTo(ul);
  };     
})(jQuery);    
</script>    
</body>
</html>

UPDATE:

Here is the updated php file with the answers from @meda and @marc:

<?php
if (isset($_GET['term'])){
    try {
        $conn=new PDO('mysql:dbname=imdb;host=localhost', 'user', 'pass');
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $stmt = $conn->prepare('SELECT DISTINCT movieName, posterLink FROM film_Posters WHERE movieName LIKE :term limit 0, 10');
        $stmt->execute(array('term' => '%'.$_GET['term'].'%'));

        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }  
    echo json_encode($rows);
}
?>

Now, I don't see null message any more, but auto-complete doesn't work at all.. I think the problem is related to javascript part... I really appreciate any help.

3
  • Where does $arr (in json_encode($arr)) come from in your HTML file? Commented Oct 21, 2014 at 15:29
  • @AbraCadaver :)) you are right Commented Oct 21, 2014 at 15:37
  • @FelixKling: I defined it in php file.. I am very new to javascript and json so sorry if I have some basic mistakes.. Commented Oct 21, 2014 at 15:45

2 Answers 2

1

You're doing your fetch loop wrong:

    while($row = $stmt->fetchAll(PDO::FETCH_ASSOC)) {
                        ^^^^^^^^

fetchAll() returns ALL of the rows as an array of arrays, e.g.

$rows = array(
    0 => array( contents of row #1)
    1 => array( contents of row #2)

Which means the while() loop is utterly pointless. fetchAll will work only ONCE anyways, so there's no point in looping. All you need is

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC)
echo json_encode($rows);

And then in your client-side javascript:

 text_to_display = data_from_server[0].movieName;
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks a lot for your answer, Sorry, but I didn't understand the javascript part... what is text-to-display? how can I use $rows of php file in javascript? :|
I mean how can I integrate the movie image with it's title to be shown in the suggest list of auto-complete text box?
i think that text-to-display is pseudocode, and for use $row inside javascript just open <?php $rows ?>
@Andrea_86: Thanks for help, but with this answer(Marc answer), I don't know what should I write for img src in javascript file... I used jsbin.com/citeyulemo/edit?html,js,output as sample, but I am really confused about what I should do to integrate image with title... :| I hope I could clarify
like i see in the example link in the src valu you must put the absolute path of the folder with the icons, or not?!
|
1

Here is all you need for the pdo Code:

PHP

if (isset($_GET['term'])){
    $rows = array();
    try {
        $conn=new PDO('mysql:dbname=imdb;host=localhost', 'user', 'pass');
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = 'SELECT DISTINCT movieName, posterLink 
                FROM film_Posters 
                WHERE movieName LIKE :term limit 0, 10';
        $stmt = $conn->prepare($sql);
        $stmt->execute(array('term' => '%'.$_GET['term'].'%'));
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }

    echo json_encode($rows);
}

As for the javascript, I don't see any request. You should be performing POST or GET ajax request, this is way it is null

jQuery:

(function($){

  var $movie = $('#m_scnt');
  var movies = "";

    $.ajax({
      dataType: "json",
      url: 'auto.php',
      success: function(response){
        movies = response;
        alert(JSON.stringify(response));
        $movie.autocomplete({
        minLength: 0,
        source: movies,
        focus: function( event, ui ) {
          $movie.val( ui.item.label );
          return false;
        }
        });

        $movie.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
            var $li = $('<li>'),
                $img = $('<img>');


            $img.attr({
              src: 'https://path/to/your/images/' + item.posterLink,
              alt: item.label
            });

            $li.attr('data-value', item.label);
            $li.append('<a href="#">');
            $li.find('a').append($img).append(item.label);    

            return $li.appendTo(ul);
        };
    }
    });  
})(jQuery);

12 Comments

Thanks a lot for your answer, but now my problem is with javascript part... I am using jsbin.com/citeyulemo/edit?html,js,output as a sample, but if you see the link, it defined an array in javascript file.. now I really don't know what should I write in img src part ..
He is injecting the JSON directly into javascript variable, not via AJAX. Don't know why he is echoing JSON after it is created though.
@MikeBrant yes very strange I updated my answer to show how to achieve this. by the way mOna seems to be a she lol
@MikeBrant: actually I am very new to javascript and json.. So, I just searched to see how I can use php array in js/html file and It was the result of what I have found... So, sorry if I did some basic mistakes... I had no idea.
@meda: Thanks a lot for your kind support:) I will try it and update you about the result :p
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.