I have a question about ajax, php si mysql..

In mysql i have a table playlists and here is the code for php:

$playlist_result = mysql_query("SELECT *, COUNT(playlist_id) AS NumOccurrences FROM playlists WHERE created_by=$user_id GROUP BY playlist_id HAVING ( COUNT(playlist_id) > 0 ) ORDER BY date DESC");
if($playlist_result_count > 0)
while($row_playlist=mysql_fetch_assoc($playlist_result)) {

  $playlist_name = $row_playlist['playlist_name'];
  $playlist_id = $row_playlist['playlist_id'];

echo '<table width=100%><tr class=comment><td style=padding:2px; class=comment_box align=left><ul class=manager><li>';
echo '<a href='#' class='add_to_playlist'><span><b>'.$playlist_name.' - '.$playlist_id.'</b></span></a>';
echo '</li></ul></td></tr></table>';
} else  {

echo '<b>You don`t have any playlist yet</b>';


Php shows all the playlists i have in my table, the name and id of the playlist. Then, the ajax part, when I click on the name of a playlist i want to insert the clicked playlist id to mysql.:

<script type='text/javascript'>
	//get the id
  var user_id = <?php echo $user_id; ?> ;
  var id = <?php echo $itemid; ?>;
  var playlist_id = <?php echo $playlist_id; ?>;
  var parent = $(this);

	// show the spinner
	$(this).html("<img src='spinner.gif'/>");
	//fadeout the vote-count 

	//the main ajax request
			type: "POST",
			data: "action=add_to_playlist&id=" + id + "&user_id=" + user_id + "&playlist_id=" + playlist_id,
			url: "add_to_playlist.php",
			success: function(msg)
				//fadein the vote count

It`s working fine but in mysql is inserted the id of the last created playlist, not the one that I clicked.
What am I doing wrong?

Thanks for your help.


I can't debug this but I can help you to do so. What you need is a debug strategy. The way I would do it is as follows:

  1. Browse the page
  2. View source, select all, copy then paste into a new document.
  3. Save as "debug.html"
  4. Inspect the javascriopt & HTML to see if it's what you expect
  5. Get it straight in your mind what the ajax "data" string should be.
  6. Amend the javascript to suppress the ajax call and to alert the ajax "data" string instead
  7. Now you are in a good position to start debugging (if necessary, refer to the API for the javascript framework you are using (Prototype?); browse | amend | browse | amend | browse | amend | browse ....
  8. Once you are happy that the correct ajax "data" string is being composed, then work the changes into your original page.

This approach avoids the complexity of working in two languages (php and javascript) at the same time.

It's probably something quite simple.


commented: Well done explained +0

Thank you for your reply..I got this working..i changed in javascript:

var playlist_id = <?php echo $playlist_id; ?>;

with this:

var element = $(this);
var playlist_id = element.attr("id");

And added id='$playlist_id' to <a> of the playlists..

Well done. I wondered if it might be in that area.