Voting Page using AJAX/JQuery - php

I am trying to figure this out and I think I am almost there but I am stuck figuring out how to use the variables properly.
I am making a page that allows a user to vote on one of three color M&Ms. By clicking the picture of one of the M&M's on the main html page, your vote will be carried over to a php page using JQuery/AJAX, and the PHP page will then update teh DBase.
My PHP page and Dbase are fine. I am stuck trying to figure out how exactly I can format my HTML page to send over the proper info to my php page so that when the red M&M is clicked, that info will go, the blue, etc etc.
Here are my HTML links:
<div id="red">
<img src="images/red.jpg" width="100%" />
</div>
<div id="blue">
<img src="images/blue.jpg" width="100%" />
</div>
<div id="green">
<img src="images/green.jpg" width="100%" />
</div>
and I want to send these over to my PHP page using JQuery and AJAX to then receive the updated vote counts. How would I formulate the AJAX/jQuery command so that when each link is clicked it sends over the color for that link? I dont need exact code here, just a pointer or two will help.

HTML:
<div id="red" data-color="red" class="answer">
...
</div>
<div id="blue" data-color="green" class="answer">
...
</div>
<div id="green" data-color="blue" class="answer">
...
</div>
JS:
$('.answer').click ( function (e) {
var color = $(this).attr("data-color");
$.ajax({
url: '/your/relative/endpoint',
type: 'POST',
data: '{ color: "'+color+'" }',
success: function (res) {
...
},
error: function (jqXHR) {
...
}
})
})
This will track each color and make the request to your server on click with the appropriate color. Remember that you should sanitize the input server side.

attach a click handler to each of the anchors
in your ajax request send the id of the parent div as a post parameter
Once the request is complete, update the corresponding div with the count from the result

Nick's answer is good just thought I would give you one more option:
<div id="red">
<a href="/vote.php?color=red" class='vote'><img src="images/red.jpg" width="100%" /></a>
</div>
<div id="blue">
<a href="/vote.php?color=blue" class='vote'><img src="images/blue.jpg" width="100%" /></a>
</div>
<div id="green">
<a href="/vote.php?color=green" class='vote'><img src="images/green.jpg" width="100%" /></a>
</div>
Javascript / jquery:
$('.vote').click(function() {
$.ajax({
type: 'POST',
url: $(this).attr('href'),
cache: false,
success: function(resp){
}
});
return false;
});

Is simple.
/****** JQUERY *******/
/**
* SEND NEW VOTE
* #param int color id of color
*/
function SendVote(color){
var count = '';
if( color == 1){
count = 'red';
}
if( color == 2){
count == 'blue';
}
if( color == 3){
count == 'green';
}
//send data via ajax,
var queryParams = {'color':color};
$.ajax({
data: queryParams,
type: "post",
url: 'path/to/vote.php'
beforeSend: function(){ // here you could add a loader (if you want)
//show loader
},
success: function(response){ // success here you get the response from the server
//response is not empty
if( response.length > 0){
$("#"+count+' span').html(response+' votes'); // then change the number of the counter
}else{
//and error on php, cause there response but is empty
}
},
fail: function(e){ //get fail ajax errors
console.log('fail '+e);
},
error: function(e){ // get errors
console.log('error '+e);
}
});
}
/*** ON vote.php (or your php script) *****/
if( isset($_POST['color']) ){
//do the things to add the new vote
//then echo the total of votes for the color
echo getVotes($_POST['color']); //this is the response that ajax will get
}
/********** html *******/
<div id="red">
<img src="images/red.jpg" width="100%" />
<span>
5 votes
</span>
</div>
<div id="blue">
<img src="images/blue.jpg" width="100%" />
<span>
4 votes
</span>
</div>
<div id="green">
<img src="images/green.jpg" width="100%" />
<span>
0 votes
</span>
</div>

Related

How can I send the value of the id through ajax and PHP

I want to pass value of the id of the product to cart.php by using AJAX and display it in a div.cart in index.php but I have no idea how. please help.
Product
Product Description
Add to Cart
$('a').on('click', function(e){
$.ajax({
url:
data:
})
e.preventDefault();
});
Of course you can :) !
So first, let's get things straight. You're showing a list of products as <div class="thumbnail"> form, right ? So your PHP/HTML should look a bit like this in reality :
<?php
foreach($database_recordset as $row) {
echo '
<div class="thumbnail>
<img src="'.$row['img_src'].'" alt="'.$row['img_alt'].'" />
<div class="caption">
<h4>'.$row['product_name'].'</h4>
<p>'.$row['product_description'].'</p>
<a id="p-'.$row['id'].'" onclick="addCart(this)">Add to Cart</a>
</div> <!-- You were missing a /div here if I guessed right the structure -->
</div>';
}
?>
so I simply labelled the link p-#ID where #ID is the id of the product from the database and added an onclick event with this as the argument. Now you need a function addCart that will contain the AJAX request.
<script type="text/javacscript">
function addCart(elm) {
// First we need the clean ID of the product
var id = elm.id.split('-')[1]; // We split with '-' as separator and take the second element of the resulting array
$.ajax({
url: "cart.php",
type: "POST", // or GET whatever but POST is usually better
data: { id: id },
success: function(response) {
if (response.status == 'OK') { // You should always test the response of an ajax request
// show a message, update the cart icon or whatever
}
}
});
}
</script>
you need to modify you code something like this. Href need to be removed else it will redirect you on that page. Give below is a sample of your code
<div class="thumbnail>
<img src="" alt="" />
<div class="caption">
<h4>Product</h4>
<p>Product Description</p>
<a id="id=(id from table products)">Add to Cart</a>
</div>
$('a').on('click', function(e){
$.ajax({
url: cart.php
data:{id:$(this).attr("id")}
})
e.preventDefault();
});
You need to stop the browser following the link, then make an ajax request and insert the response into the target div.
You can use jquerys load method to acheive that in a single call:
$('a.clickme').click(function(ev){
ev.preventDefault();
$('div.cart').load($(this).attr('href'));
});
Note i added a class to the link, else your code would capture all link clicks including site navigation etc
Add to Cart

Jquery UI sortable, write order into a MySql database

I'm currently using JQuery UI Dragabble, Droppable and sortable. I have two div sections at top and bottom of my php file were i'm dragging and dropping contents from bottom to top div sections.
In top div section i'm performing Sortable JQUery opertions my next requirment is when i perform sorting operation in top section its order should be automatically updated in my MYSQL DB i gotta stuck like how to pass the sorted order to my MySQL db via ajax and php file. Can somebody suggest some help in Achieving it!
Thanks!
Html/PHP code
<div class="drop_list">
<ol id="sortable" style="list-style:decimal;"></ol>
</div>
<div class="sort_list">
<ul id="draggable">
<?php
for($i=1;$i<=5;$i++)
{
?>
<li data-id='article_<?php echo $i;?>' class="draggable_li qitem" >
<div class="main_div">
<div class="secondary_div">
<div class="form_div">
<form>
<input style="width:15px;" type="checkbox" class="hello"/>
</form>
</div>
<label class="item_div">
<span class="item">Item = <?php echo $i; ?></span>
</label>
</div>
<button class="hello btn btn-success add_top">
Add to Top Stories
</button>
<span class="AH_section" style="display:none;float:right;">
<input type="checkbox"/>Home Section
<input type="checkbox"/>App Home Section
</span>
</div>
</li>
<?php
}
?>
</ul>
</div>
</div>
</div>
</div>
JQuery code
$(document).ready(function() {
$("#sortable").sortable({
revert: true,
refreshPositions: true ,
helper : 'clone',
cursor: "move",
delay: 1,
tolerance: 'pointer',
revert: 50
/*stop:function(event,ui){
var data = $(this).sortable('serialize');
}*/
}).serialize();
$("ol li").disableSelection();
$(".sort_list li").draggable({
//containment : "#container",
tolerance:"pointer",
helper : 'clone',
refreshPositions: true ,
revert : 'invalid',
opacity:.4,
});
$(".drop_list ol").droppable({
revert:true,
//hoverClass : 'ui-state-highlight',
greedy: true,
refreshPositions: true,
drop : function(ev, ui)
{
$(ui.draggable).clone().appendTo(this);
if($(this)[0].id === "sortable")
{
console.log($(this).closest("button").find('.hello'));
$(this).find('.hello').hide();
$(this).find('.AH_section').show();
//$(ui.draggable).draggable( 'disable' ); //this will not append dragged list at top of the container
ui.draggable.draggable( 'disable' ).closest('li').prependTo(ui.draggable.closest('ul')); //this will append dragged list at top of the container
return true;
}
}
});
});
change data-id='article_<?php echo $i;?>' to id='<?php echo $i;?>'
add this to your sortable(),
update: function (event, ui) {
var serial=$(this).sortable('serialize');
save_sortable(serial);
}
so here on update, you are calling save_sortable() function, from ajax , update your db in the order returned from sortable()
function save_sortable(serial)
{
$.ajax({
url: "path to your file to update in db.",
type: 'POST',
data: serial,
success: function (data) {
//alert(data);
}
});
}
You can add some id attribute to li, in my case will be get_id.
and then call below function onDropSendSort(); when you want, ie after drop.
<li data-id='article_<?php echo $i;?>' get_id="<?php echo $object_id; ?>" class="draggable_li qitem" >
function onDropSendSort() {
var data = [];
$('#draggable li').each(function() {
var id = $(this).attr('get_id');
data.push(id);
});
// data = [id_1, id_3, id_n];
$.ajax({
url: 'some_url',
type: 'POST',
data: {sort: data},
complete: function(res) {
console.info(res);
}
});
}

jQuery code does work after updating

I have page where an instant search results are displaying using PHP & AJAX and <a> tag onclick from response item, it generate preview of track. Everything is working fine but when I update my jQuery version from 1.7.2 to 1.11.3 or 2.1.4. It open link instead of generating preview.
My code
<!--<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function($)
{
$(".videos .expand-video a.soundcloud").live("click", function(){
var scURL = $(this).attr("href");
var scID = $(this).attr("id");
var embedAudio = "<iframe width=\"100%\" height=\"166\" scrolling=\"no\" frameborder=\"no\" src=\"https://w.soundcloud.com/player/?url="+scURL+"&color=ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false\"></iframe>";
$("#sc-"+scID).html(embedAudio);
return false;
});
var timer = null;
$("#keyword").keyup(function()
{
if(timer)
{
clearTimeout(timer);
}
timer = setTimeout(function()
{
var sc_keyword = $("#keyword").val();
var obj = $(this);
if(sc_keyword != '')
{
$(".ajax_indi").show();
var str = $("#fb_expand").serialize();
$.ajax({
type: "POST",
url: "fetch.php",
data: str,
cache: false,
success: function(htmlresp)
{
$('#results').html(htmlresp);
$(".ajax_indi").hide();
}
});
}
else
{
alert("Search for your favourite news");
$("#keyword").focus();
}
}, 1000);
});
});
</script>
I know .live() has been removed in version 1.9 onwards. So, I tried to update it to .on() but does not done it successfully
What I have tried to update from .live() to .on() is below
$(".videos .expand-video a.soundcloud").on("click", 'a', function(){
var scURL = $(this).attr("href");
var scID = $(this).attr("id");
var embedAudio = "<iframe width=\"100%\" height=\"166\" scrolling=\"no\" frameborder=\"no\" src=\"https://w.soundcloud.com/player/?url="+scURL+"&color=ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false\"></iframe>";
$("#sc-"+scID).html(embedAudio);
return false;
});
HTML OUTPUT Response of ajax request
<div class="videos" id="sc-80912043">
<div class="expand-video"> <a class="soundcloud" id="80912043" href="https://api.soundcloud.com/tracks
/80912043"><span></span> <img src="https://i1.sndcdn.com/avatars-000033051760-4ugg0i-large.jpg" width
="120" height="90" title="Play" alt="Play"/> </a> </div>
<div class="details">
<h6>DJ MHA - Menu Chad De (MHA Remix)</h6>
<p class="link">Gangzta Khan</p>
<p class="desc">DJ MHA - Menu Chad De (MHA Remix)..
Gangzta Khan ..</p>
</div>
</div>
<div class="videos" id="sc-24508938">
<div class="expand-video"> <a class="soundcloud" id="24508938" href="https://api.soundcloud.com/tracks
/24508938"><span></span> <img src="https://i1.sndcdn.com/avatars-000002625883-ve8pmk-large.jpg" width
="120" height="90" title="Play" alt="Play"/> </a> </div>
<div class="details">
<h6>Halka Halka Suroor - MHA Mix</h6>
<p class="link">DJ MHA</p>
<p class="desc">Yeh Jo Halka Halka Suroor Hai
Direct Download Link:
http://www.djmha.com/get.php?file=Halka_Halka_Suroor_-_MHA_Mix.mp3</p>
</div>
</div>
<div class="videos" id="sc-65996317">
<div class="expand-video"> <a class="soundcloud" id="65996317" href="https://api.soundcloud.com/tracks
/65996317"><span></span> <img src="https://i1.sndcdn.com/avatars-000002625883-ve8pmk-large.jpg" width
="120" height="90" title="Play" alt="Play"/> </a> </div>
<div class="details">
<h6>Zarina Taylor - (DJ MHA Remix)</h6>
<p class="link">DJ MHA</p>
</div>
</div>
You're being too specific with your selector before calling .on(). The way the function works is you select elements that will always exist on the page, and bind the delegated event handler to those. Since you're replacing the content of the <div> elements with class videos, your code should be this:
$(".videos").on("click", ".expand-video a.soundcloud", function(){
var scURL = $(this).attr("href");
var scID = $(this).attr("id");
var embedAudio = "<iframe width=\"100%\" height=\"166\" scrolling=\"no\" frameborder=\"no\" src=\"https://w.soundcloud.com/player/?url="+scURL+"&color=ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false\"></iframe>";
$("#sc-"+scID).html(embedAudio);
return false;
});
First, we select the .videos elements, then we bind a delegated event handler for a.soundcloud elements which are inside a .expand-video element (which are in turn inside a .videos element). That way, when you update the content of one of those elements in this line - $("#sc-"+scID).html(embedAudio); - the delegated event handler still exists.
I dont know why this worked in an old version!!!
So just for one video
<div class="videos" id="sc-80912043">
<div class="expand-video"> <a class="soundcloud" id="80912043" href="https://api.soundcloud.com/tracks
/80912043"><span></span> <img src="https://i1.sndcdn.com/avatars-000033051760-4ugg0i-large.jpg" width
="120" height="90" title="Play" alt="Play"/> </a> </div>
<div class="details">
<h6>DJ MHA - Menu Chad De (MHA Remix)</h6>
<p class="link">Gangzta Khan</p>
<p class="desc">DJ MHA - Menu Chad De (MHA Remix)..
Gangzta Khan ..</p>
</div>
</div>
This is a problem i have had a few times .on does not act the same as live with the active binding even though it's supposed to...
function gotAJAXResults(){
$(".videos .expand-video a.soundcloud").unbind("click");
$(".videos .expand-video a.soundcloud").click(function(e){
e.preventDefault();
var scURL = $(this).attr("href");
var scID = $(this).attr("id");
var embedAudio = "<iframe width=\"100%\" height=\"166\" scrolling=\"no\" frameborder=\"no\" src=\"https://w.soundcloud.com/player/?url="+scURL+"&color=ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false\"></iframe>";
$("#sc-"+scID).html(embedAudio);
return false;
});
}
Ok so now your AJAX call becomes
$.ajax({
type: "POST",
url: "fetch.php",
data: str,
cache: false,
success: function(htmlresp)
{
$('#results').html(htmlresp);
gotAJAXResults();
$(".ajax_indi").hide();
}
});
This method will then force it to bind the event when ajax receives and has inserted them into the page. (DOM scope)

ajax php GET/POST without refresh

I need to execute the following code, without refreshing the page... this code already includes ajax but where am I going wrong with getting it to execute without refreshing the page....? the .vote class is attatched to an anchor in my index.php file, and I need this all to still work when the anchor is clicked if possible. Re-coding this to perform on a button click would not be ideal.
$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var eData = $(this).attr("data-options");
var dataString = 'id='+ id + '&' + eData ;
var parent = $(this);
if(name=='up')
{
$(this).fadeIn(200).html('');
$.ajax({
type: "POST",
url: "up.php",
data: dataString,
cache: false,
success: function(html){
parent.html(html);
}
});
}
else
{
$(this).fadeIn(200).html('');
$.ajax({
type: "POST",
url: "down.php",
data: dataString,
cache: false,
success: function(html){
parent.html(html);
}
});
}
});
here is the html from my index.php
<div id="main">
<div id="left">
<span class='up'><img src="up.png" alt="Down" /></span><br />
<?php echo $totalvotes1; ?><br />
</div>
<div id="message">
<?php echo $message1; ?>
</div>
<div class="clearfix"></div>
</div>
<div id="main">
<div id="right">
<br />
<?php echo $totalvotes2; ?><br />
<span class='down'><img src="down.png" alt="Down" /></span>
</div>
<div id="message">
<?php echo $message2; ?>
</div>
<div class="clearfix"></div>
</div>
You need to either enclose your code with $(document).ready(function() {});, or stick your code at the end of the <body> tag. Personally, instead of making the browser parse synchronous javascript before the DOM has loaded (in the <head> section), I stick it near the end. This is also what Bootstrap recommends.
Without a DOM loaded, there are no elements created for jQuery to register Events with, and so your code literally sits there doing nothing after being parsed.
Aside from that, the .click() function is executed on click. It doesn't matter what element it's bound to. If it's clickable, it's executable.
Also to answer your question properly: <a href=""> will refresh the page. You want to use
<a href="#">. This, however, will make you jump to the top of the page. You could also define a <label> and use #labelname instead to avoid this. Or just don't use href at all. It's not needed.
Also, a little trick for echoing variables into HTML is to use <?= $var ?>

Jquery AJAX custom form not returning results from PHP

I don't like the look of normal dropdown selectors in forms, so I've decided to create my own version of them with some Jquery as a little learning project for myself.
The objective of the following code is to be able to submit the text inside the various "select" boxes, i.e. #cuisineSelect, #locationSelect and #priceSelect to "ajax.php" so that I can manipulate those variables further.
My problem is that for some strange reason ajax.php will not register the $_POST variable and it's telling me that I've got an "undefined index".
I did some debugging in IE9 with some developer tools and they show (at least I think so) that the variables are getting sent through to ajax.php, and ajax.php is returning a variable. Here are the screenshots.
On the real project, the user can click on the <li> options item and the text will transfer onto the selector - just like a dropdown selector.
Here is my code:
The HTML:
<div id="parentContainer" style="width:100%;">
<div class="container">
<div class="select" id="cuisineSelect">
Cuisine
</div>
<div class="option" id="cuisineOption">
<ul id="cuisineul">
<li>Asian</li>
<li>American</li>
<li>Indian</li>
<li>Fusion</li>
</ul>
</div>
</div>
<div class="container">
<div class="select" id="locationSelect">
Location
</div>
<div class="option" id="locationOption">
<ul id="locationul">
<li>Asian</li>
<li>American</li>
<li>Indian</li>
<li>Fusion</li>
</ul>
</div>
</div>
<div class="container">
<div class="select" id="priceSelect">
Price
</div>
<div class="option" id="priceOption">
<ul id="priceul">
<li>Price Range</li>
<li>Cheap ($5-$15)</li>
<li>Medium ($16 - $20)</li>
<li>Pricey ($21 - $35)</li>
<li>Fine Dining ($35+)</li>
</ul>
</div>
</div>
<div class="container">
<div class="select" id="searchButton" style="width:25px; height:20px;">
<center><img align="center" src="images/sml_search.png" width="17" height="18" /></center>
</div>
</div>
</div>
<div id="result" style="z-index:10;">
result=show;
<?php include "ajax.php"; ?>
</div>
The Jquery code (this has already been placed inside a $(document).ready function.)
$("#searchButton").click(function() {
/*var cuisine = $("#cuisineSelect").html();
var location = $("#locationSelect").attr('value');
var price = $("#priceSelect").attr('value');
$.ajax({
type: "POST",
url: "ajax.php",
data: "cuisine="+ cuisine +"& location="+ location +"& price="+ price,
success: function(){
$('#result').show();
}
});
return false; */
$.post('ajax.php', 'cuisine=' + $("#cuisineSelect").text(), function () {
$("#result").show();
});
});
The PHP page "ajax.php"
<?php
//Search information
//$cuisine = htmlspecialchars(trim($_GET['cuisine']));
//$location = htmlspecialchars(trim($_POST['location']));
//$price = htmlspecialchars(trim($_POST['price']));
//echo $location;
//echo $price;
//$addClient = "INSERT INTO clients (fname,lname) VALUES ('$fname','$lname')";
//mysql_query($addClient) or die(mysql_error());
//$value = $_POST['cuisine'];
//$value2 = $_POST['val'];
//echo "$value2";
$cuisine = $_POST['cuisine'];
echo $cuisine;
?>
Thanks very much for your help.
There is no need to write include the ajax.php file in #result div. Keep #result div empty and hidden.
Modify your ajax call as below:
$.post('ajax.php', 'cuisine=' + $("#cuisineSelect").html(), function (data) {
$("#result").html(data);
$("#result").show();
});
This will show the clicked text in #result 'div'. variable data is passed to callback function for further utilization.
To convert the < li > to a select box, you have to pass the values present in the div #cuisineOption to ajax.php so your PHP script can create the select box from these values.

Categories