Reputation: 677
I have a product page that I am trying to implement a rating system on.
Each product page will have the information:
productID - The ID of the product
User - The username of the user logged in
I have the following HTML for the star rating:
<fieldset id='ratingStars' class="rating">
<input class="stars" type="radio" id="star5" name="rating" value="5" />
<label class = "full" for="star5" title="Incredibly Powerful - 5 stars"></label>
...
<input class="stars" type="radio" id="star1" name="rating" value="1" />
<label class = "full" for="star1" title="Unusable - 1 star"></label>
</fieldset>
I have a javascript file that is called when one of the stars is clicked, it calls a PHP file that will connect to the database and add the rating to the product:
$(document).ready(function () {
$("#ratingStars .stars").click(function () {
$.post('../resources/add_rating_to_product.php',{rate:$(this).val()},function(){
});
});
});
The PHP file just connects to the database and inserts the rating into a rating table. It expects to be POSTed the data for the username, productid, and rating.
Maybe this is a stupid question, but how do I POST that data from the javascript file? I understand how to get the rating because of the object being clicked but how do I send the other 2 if they aren't in the scope of the php file. And how do I do this securely?
It's very possible that I'm going about this all wrong so any help is appreciated!
Upvotes: 1
Views: 64
Reputation: 4760
You can serialize your form and use the onSubmit event handler. Haven't tested code.
Given the following form:
<form id="ratingsForm" action="../resources/add_rating_to_product.php" method="POST">
<input type="radio" name="rating" value="5" />
<input type="radio" name="rating" value="1" />
<input type="hidden" name="productId" value="<?php echo $productId; ?>" />
<input type="submit" name="submit" value="submit" />
</form>
You can use an event handler to serialize the form data and post it using AJAX.
$(document).ready( function() {
$("#ratingsForm").on("submit", function(){
$.ajax( {
type: "POST",
url: $(this).attr( 'action' ),
data: $(this).serialize(),
success: function( response ) {
console.log( response );
}
} );
});
} );
Upvotes: 1