1

The user is required to click on an actor from a actors list. The existing movie titles are removed and then only movies titles pertaining to the chosen actor show.

My "dvdtitle" listbox receives a list of "Undefined" after an actor is chosen. However I checked the response data from json_encode function with $('#actor').text(data) to get it visual and I do get correct.

[{"503":"Caught In The Crossfire"},
{"690":"Dead Man Running"},
{"1064":"Get Rich Or Die Trying"},
{"1145":"Gun"},{"1254":"Home of The Brave"},
{"2184":"Righteous Kill"},
{"2519":"Streets Of Blood"},
{"3273":"Twelve"}]

I don't know what I'm doing wrong.

//getactors.php
include("includes/connection.php");

$q = $_POST['input'];
$final_array = array();

$resultActor = mysql_query("SELECT id, title, plot, catagory, release_date, rated FROM dvd WHERE actors LIKE '%".$q."%' ");

while($rowActor = mysql_fetch_array($resultActor)) {
    $final_array [] = array( $rowActor['id']   => $rowActor['title'] ); 
}

echo json_encode($final_array); 


// JavaScript Document
$('#actorsname').click(function(){

    var actorValue = $('#actorsname option:selected').text();
    $.ajax({
        type: "POST",
        url: 'getactors.php',
        data: {input: actorValue},
        cache: false,
        datatype: "json",
        success: function(data) {
            $('#dvdtitle option').each(function(i, option) {
                $(option).remove();    // Empty DVD Listbox
            });

            $('#actor').text(data);   //  to visualy check my json Data

            $.each(data, function(i, j) { 
                var row = "<option value=\"" + i.value + "\">" + j.text + "</option>";
                $(row).appendTo("select#dvdtitle");
            });
        }
    });
});
BartekR
  • 3,827
  • 3
  • 24
  • 33
Nico
  • 35
  • 1
  • 6

2 Answers2

4

The problem is that your Ajax is returning an object containing one key/value pair with the movie ID as a key and the movie title as a value. This makes retrieving the data more difficult because you don't know in the each loop which ID to look for.

Ideally, you'd have your JSON formatted this way instead:

[
    {"id":503,"title":"Caught In The Crossfire"},
    {"id":690,"title":"Dead Man Running"}
]

That would allow you to retrieve the data in your each loop using j.id and j.title because the JSON uses "id" and "title" as keys. But because you don't have it organized that way, you need to loop through each key/value pairs of the object.

Ideally, you'd want to change your PHP to this:

$final_array[] = array(
    'id' => $rowActor['id'],
    'title' => $rowActor['title']
);

And use j.id and j.title (e.g. var row = "<option value=\"" + j.id + "\">" + j.title + "</option>";).

Here's an example without modifying your PHP code: This example is based on your example above. The data variable is what's received in your Ajax request.

// This is the data retrieved using Ajax.
var data = [{"503":"Caught In The Crossfire"},{"690":"Dead Man Running"},{"1064":"Get Rich Or Die Trying"},{"1145":"Gun"},{"1254":"Home of The Brave"},{"2184":"Righteous Kill"},{"2519":"Streets Of Blood"},{"3273":"Twelve"}];

// Loop through each object in the data array.
$.each(data, function(key, movie)
       {
           // Because the ID is a key and the title a value, we can't determine the ID/title unless we loop through each one of the key/value pairs in the object. Each movie only has one key/value pair so this won't be a problem.
           $.each(movie, function(id, title)
                  {
                      $('<option />').attr('value', id).text(title).appendTo('select#dvdtitle')
                  });
       });

jsFiddle: http://jsfiddle.net/j7HGr/

I hope that makes sense.

PS: You may also want to change $q=$_POST['input']; to use mysql_real_escape_string to prevent SQL injections.

Francois Deschenes
  • 24,816
  • 4
  • 64
  • 61
  • Hey, is there something painfully obvious I messed up in my answer? I was trying to convey the javascript portion of what you said, but I seem to have faltered at some point. – mowwwalker Jan 23 '12 at 22:18
  • @Walkerneo, you had it right. Perhaps you were missing the explanation or like I suggested above, that changing the JSON may be a better way to go. – Francois Deschenes Jan 23 '12 at 22:22
  • Thanks for your quick response. I tried your suggestion example based on my json output however my output in the movie listbox now shows vertically each letter, quote, periods, and brackets of the data. I will keep trying stuff I guess. – Nico Jan 24 '12 at 00:35
  • Just to let you know that when I use the Var Data as you showed your method works nicely. So why am I getting a vertical output of the data when I use the same JSON data? – Nico Jan 24 '12 at 01:14
  • I get the same results with Chrome, Firefox and Ie8 – Nico Jan 24 '12 at 01:19
-2

data is an array of objects. The value of i is the index of the object, and j is the object.

Here:

$.each(x, function(i, j){ 
    $.each(j, function(k, v){
        var row = "<option value=\"" + k + "\">" +v+ "</option>";                
        $(row).appendTo("select#dvdtitle");  
    });   
  });

You can see the jquery documentation for more information: http://api.jquery.com/jQuery.each/

mowwwalker
  • 16,634
  • 25
  • 104
  • 157
  • @paislee, I initially told him the problem so he could work on it by himself. I then updated my answer to what he should do. – mowwwalker Jan 23 '12 at 22:00
  • the first sentence implies no problem. – calebds Jan 23 '12 at 22:03
  • @paislee, I don't understand your dilemma here. The problem is that `data` is an array of objects, so `i` is the index for each object `j` in the array. `i.value` isn't valid javascript, nor is `j.text`. He needs to iterate over each object in the array, then iterate over each key value pair. – mowwwalker Jan 23 '12 at 22:11
  • Hinting at an answer doesn't help the OP or anyone who finds this later. – Herbert Jan 23 '12 at 22:22
  • Thanks for your quick response. I tried your suggestion example based on my json output however my output in the movie listbox now shows vertically each letter, quote, periods, and brackets of the data. I will keep trying stuff I guess – Nico Jan 24 '12 at 02:04
  • @Nico, Did you do BOTH things that Francois said to do? You were only supposed to do one. Either change the php, or change the javascript, not both. – mowwwalker Jan 24 '12 at 02:07
  • @Nico, Please update your question with the code you are currently using. Both PHP and javascript. – mowwwalker Jan 24 '12 at 02:08
  • I used $.getJSON with second example – Nico Jan 24 '12 at 22:05
  • $.each(data, function(key, movie) { // Because the ID is a key and the title a value, we can't determine the ID/title unless we loop through each one of the key/value pairs in the object. Each movie only has one key/value pair so this won't be a problem. $.each(movie, function(id, title) { $('').attr('value', id).text(title).appendTo('select#dvdtitle') }); }); – Nico Jan 24 '12 at 22:06
  • and this worked , I dont know why the Ajax call gave me verticle list of all the data. Thanks alot for your help until next time :) – Nico Jan 24 '12 at 22:07