JDoe JDoe - 29 days ago 4x
Javascript Question

Ajax request to return element used in Jquery

I am making a POST request with Ajax to retrieve star ratings for 10 products I am showing on the website.

The request I make 10 times via php loop to build the page is:

function returnRating($id) {
url: "returnRating.php",
type: 'POST',
data: {
id: $id
$("#sp"+id).html(response); <- replace html for span element for each of the products


The ajax Php file ("returnRating.php") contains function connecting to the database and creating html code for the star rating:

$bdd = new db();

$id = $_POST['id'];

function starBar($numStar, $mediaId, $starWidth) {

///Retrieving the rating, creating star elements to put in span for each product. Rating element class is .rating
return $starBar;

echo starBar(5, $id, 25);


To interact with the star ratings I am using Jquery script:

$(document).ready(function() {
$(".rating").on("change", function(ev, data){ saveRating($(this).parent().attr("id"), data.to, data.to, "25px"); <- activate script saving the new rating


My question is - where should I put the saving script? When I put it in the main page the selector doesn't work at all. I have put it in the returnRating.php file I'm requesting via Ajax and it appears to be working as it activates function saveRating. However it does it 10 times each time I click on a single star rating.

What is the correct way of using Jquery selectors on the content generated by php ajax request?


I have found an answer to my question. The issue I was experiencing was js bubbling which was causing event to execute 10 times.

Solved by adding a line



$(".rating").on("change", function(ev, data){  
    saveRating($(this).parent().attr("id"), data.to, data.to, "25px");