New to php and mysqli. I have a working php / mysqli search page with ajax for a table containing part number, description, price and quantity-in-stock. I can write an alternate SELECT query that limits the results to items with stock > 0.
What I want is to add a checkbox on the form that allows the user to choose between all results, or just results of items in stock (greater than zero).
I have tried to test for stocked using if(isset($_GET['stocked'])) but have no success. What am I missing? Any help is appreciated.
<script type="text/javascript">
$(function() {
$(".search_button").click(function() {
var search_word = $("#search_box").val();
var dataString = 'search_word=' + search_word;
if (search_word == '') {
} else {
$.ajax({
type: "GET",
url: "searchdata.php",
data: dataString,
cache: false,
beforeSend: function(html) {
document.getElementById("insert_search").innerHTML = '';
$("#flash").show();
$("#searchword").show();
$(".searchword").html(search_word);
$("#flash").html('<img src="ajax-loader_2.gif" /> Loading Results...');
},
success: function(html) {
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
}
});
}
return false;
});
});
</script>
<form method="get" action="">
<input type="checkbox" name="stocked" value="Yes"><label> Display in-stock items only</label>
<input type="text" name="search" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button" />
</form>
<?php
include('dbconnect.php');
if (isset($_GET['search_word'])) {
$search_word = $_GET['search_word']; //get value sent from search form
$min_length = 2; //2 character minimum for search
if (strlen($search_word) >= $min_length) { // if query length is more than or equal to minimum length, then
$search_word = htmlspecialchars($search_word); //change characters used in html to their equivalents
$search_word_new = mysqli_escape_string($conn,$search_word); //prevent SQL injection
$search_word_fix = str_replace(" ","%",$search_word_new);
// $raw_results = mysqli_query($conn,"SELECT * FROM stock WHERE partnumber LIKE '$search_word_fix%' AND availability > 0 ORDER BY partnumber LIMIT 10"); //in stock
$raw_results = mysqli_query($conn,"SELECT * FROM stock WHERE partnumber LIKE '$search_word_fix%' ORDER BY partnumber LIMIT 10"); //all
if(mysqli_num_rows($raw_results) > 0) { //one or more rows are returned
while($row = mysqli_fetch_array($raw_results)) { //put table data into array and loop while valid
echo "<hr class='gryhr'><br>{$row['partnumber']}<br>";
echo "<p>".$row['description']."<br>".
"List price $".$row['listprice']."<br>".
"In stock: ".$row['availability']."</p><br>";
}
echo "<hr>Total Results: " .mysqli_affected_rows($conn);
}
else { //no matching rows found
echo '<div>No Results</div>';
}
}
else { // if query length less than minimum
echo "Enter minimum of ".$min_length." characters";
}
}
mysqli_close($conn);
?>
Looks like your not sending the checkbox value to your PHP code at all ... You could do something like this:
var dataString = $('#myForm').serializeObject();
$('#myForm input[type=checkbox]').each(function() { dataString[this.name] = this.checked; });
You will have to modify yout script a little thought.
add id myForm to your form element and change the name of your search imput to search_word.
in a nutt shell it would look like
-- EDIT -- full code would look like this
<?php
// If form submited
include('dbconnect.php');
if (isset($_POST['search_word'])) {
$search_word = $_POST['search_word']; //get value sent from search form
$min_length = 2; //2 character minimum for search
if (strlen($search_word) >= $min_length) { // if query length is more than or equal to minimum length, then
$search_word = htmlspecialchars($search_word); //change characters used in html to their equivalents
$search_word_new = mysqli_escape_string($conn,$search_word); //prevent SQL injection
$search_word_fix = str_replace(" ","%",$search_word_new);
// $raw_results = mysqli_query($conn,"SELECT * FROM stock WHERE partnumber LIKE '$search_word_fix%' AND availability > 0 ORDER BY partnumber LIMIT 10"); //in stock
if (isset($_POST['stocked'])){ $stocked = " and stocked > 0";}
$raw_results=mysqli_query($conn,"SELECT * FROM stock WHERE partnumber LIKE '$search_word_fix%' $stocked ORDER BY partnumber LIMIT 10"); //all
if(mysqli_num_rows($raw_results) > 0) { //one or more rows are returned
while($row = mysqli_fetch_array($raw_results)) { //put table data into array and loop while valid
echo "<hr class='gryhr'><br>{$row['partnumber']}<br>";
echo "<p>".$row['description']."<br>".
"List price $".$row['listprice']."<br>".
"In stock: ".$row['availability']."</p><br>";
}
echo "<hr>Total Results: " .mysqli_affected_rows($conn);
}
else { //no matching rows found
echo '<div>No Results</div>';
}
}
else { // if query length less than minimum
echo "Enter minimum of ".$min_length." characters";
}
}
mysqli_close($conn);
?>
as for your view part
<script type="text/javascript">
$(document).ready( function() { // Wait until document is fully parsed
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$("#myForm").on('submit', function(e){
e.preventDefault();
var dataString = $('#myForm').serializeObject();
$('#myForm input[type=checkbox]').each(function() { dataString[this.name] = this.checked; });
if (dataString['search_word'] != '') {
$.ajax({
type: "POST",
url: "searchdata.php",
data: dataString,
cache: false,
beforeSend: function(html) {
// ...
},
success: function(html) {
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
}
});
}
return false;
});
});
</script>
<form id="myForm" action="" method="post">
<input type="checkbox" name="stocked" value="Yes"><label> Display in-stock items only</label>
<input type="text" name="search_word" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button" />
</form>
The code you had was not working because you where sending the data using the form and you where also sending the data using ajax. You need to choose one or the other. Not both. In the above, I am sending it by ajax call and preventing the default form submit. I am also sending using POST instead of GET.
Related
I am trying to send an $_GET['CategoryID'] trought ajax to call in the destination file getdata.php and I can't make it work, I don't find the perfect info here. I know that I am really noob, but I am trying really hard to learn.
I been trying a lot of different code and it still not working.
<button type="button" name="btn_more" data-vid="<?php echo $stockID; ?>" id="btn_more" class="btn btn-success form-control">Ver Mais</button>
<input class="form-control" id="PresentCategoryID" name="PresentCategoryID" data-cat="<?php echo $_GET['categoryID']; ?>" value="<?php echo $_GET['categoryID'];
<script>
$(document).ready(function(){
$(document).on('click', '#btn_more', function(){
var last_video_id = $(this).data("vid");
var PresentCategoryID= ('PresentCategoryID');
$('#btn_more').html("<div class=loader></div>");
$.ajax({
url:"getdata.php",
method:"POST",
data:{
last_video_id:last_video_id,
PresentCategoryID:PresentCategoryID},
dataType:"text",
success:function(data)
{
if(data != '')
{
$('#remove_row').remove();
$('#result').append(data);
}
else
{
$('#btn_more').html("No Data");
}
}
});
});
});
</script>
My objective it's to call the categoryID in the getdata.php, like this,
<?php
$output = '';
$stockID = '';
$PresentCategoryID = '';
sleep(1);
include 'includes/dbh.inc.php';
include 'includes/rating.inc.php';
$sql = "SELECT stock.stockID, stock.name, stock.marca, stock.origem, stock.categoryID, stock.thumbnail, category.name AS catname FROM stock JOIN category ON stock.categoryID=category.categoryID WHERE stock.categoryID='$PresentCategoryID' AND stockID > ".$_POST['last_video_id']." LIMIT 4";
?>
var PresentCategoryID= ('PresentCategoryID')
should be
var PresentCategoryID= $('#PresentCategoryID').val();
You need to use $ to select the element, add the # prefix to use it as an ID, and .val() to get the value of the input.
hey check this answer which will help your problem
$(document).ready(function() {
$(document).on('click', '#btn_more', function() {
var last_video_id = $(this).data("vid");
var PresentCategoryID = ('#PresentCategoryID').val();
$('#btn_more').html("<div class=loader></div>");
var data = {
last_video_id,
PresentCategoryID
};
$.get('getdata.php', JSON.stringify(data)).done(response => {
console.log(response);
if (response != '') {
$('#remove_row').remove();
$('#result').append(response);
} else {
$('#btn_more').html("No Data");
}
}).fail(() => {
console.log("Something went wrong");
});
});
});
PHP SCRIPT
<? php
include 'includes/dbh.inc.php';
include 'includes/rating.inc.php';
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
//if you using get request
//recommended way to get the data use the mysqlconn->real_escape_string($_GET['last_video_id']);
$last_video_id = $_GET['last_video_id'];
$PresentCategoryID = $_GET['PresentCategoryID'];
sleep(1);
$sql = "SELECT stock.stockID, stock.name, stock.marca, stock.origem, stock.categoryID, stock.thumbnail, category.name AS catname FROM stock JOIN category ON stock.categoryID=category.categoryID WHERE stock.categoryID='$PresentCategoryID' AND stockID='$$last_video_id'";
" LIMIT 4";
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//if you using post request then in jquery remove $.get to just $.post
$data = json_decode(file_get_contents('php://input'),true);
$last_video_id = $data['last_video_id'];
$PresentCategoryID = $data['PresentCategoryID'];
}
you want to send via 'GET' but you use the method 'POST'.
Best regards
MrKampf
I want to update the database columns "rate_score" and "rate_number" if the user rate it. "rate_score" shows the whole number of rates that all users are rated. "rate_number" shows the whole number of users who rate it. If the user does not rate the product, he can see the average rating value. But my code is not working.
Here is my PHP code.
$jsqla = mysql_query("select id,name,rate_score,rate_number,video_image from products where genre='$genre' limit 0,5");
if($jrowa['rate_number'] > 0){
$ratea = $jrowa['rate_score'] / $jrowa['rate_number'];
}else{
$ratea = 0;
}
Here is my HTML code.
<input class="rating form-control input-star-rate" name="rating" value="<?php echo $ratea; ?>" data-min="0" data-max="5" data-step="0.3" data-size="xs" style="display: none; text-align: center;"/>
Here is my jQuery code.
$(function(){
$(document).ready(function(e) {
var $stars = $('.input-star-rate');
$stars.bind('change', function() {
var $this = $(this);
var ratingValue = $this.val();
var id = $this.attr("id");
var num = parseInt("$this.attr("rate_number")")+1;
$.ajax({
type : "POST",
url : "update_star_rate.php",
data : {product_id: id, rate_score: ratingValue, rate_number: num},
success : function() {
alert(ratingValue);
}
});
});
});
});
Here is the content of "update_star_rate.php"
<?php
require_once("scripts/dcon.php");
$rate_score=$_POST['rate_score'];
$product_id=$_POST['id'];
$rate_number=$_POST['rate_number'];
$rate = "UPDATE products SET rate_score=$rate_score, rate_number=$rate_number WHERE id=$product_id" ;
$result = mysql_query($rate) or die(mysql_error());
?>
require_once("scripts/dcon.php");
if (isset($_POST['rate_score']) && !empty($_POST['rate_score'])){
$rate_score=$_POST['rate_score'];
} //this will set only when data comes
if (isset($_POST['rate_id']) && !empty($_POST['rate_id'])){
$product_id=$_POST['id'];
} //this will set only when data comes
if (isset($_POST['rate_number']) && !empty($_POST['rate_number'])){
$rate_number=$_POST['rate_number'];
} //this will set only when data comes
$rate = "UPDATE products SET rate_score=$rate_score, rate_number=$rate_number WHERE id=$product_id" ;
$result = mysql_query($rate) or die(mysql_error());
if your ajax data come correctly then you will update data
Use this
data : 'product_id='+id+'&rate_score='+ratingValue+'&rate_number='+num,
Instead of
data : {product_id: id, rate_score: ratingValue, rate_number: num},
before inserting, check all variable are working. (use alert).
I have see the example about search box using JQuery and mysql, But the view more function no work. how to improve the program. When i click the view more i can see the next 10 record. Thanks
<script type="text/javascript">
$(document).ready(function()
{
$("#keywords").keyup(function()
{
var kw = $("#keywords").val();
if(kw != '')
{
$.ajax
({
type: "POST",
url: "search.php",
data: "kw="+ kw,
success: function(option)
{
$("#results").html(option);
}
});
}
else
{
$("#results").html("");
}
return false;
});
$(".overlay").click(function()
{
$(".overlay").css('display','none');
$("#results").css('display','none');
});
$("#keywords").focus(function()
{
$(".overlay").css('display','block');
$("#results").css('display','block');
});
});
</script>
<div id="inputbox">
<input type="text" id="keywords" name="keywords" value="" placeholder="Type Your Query..."/>
</div>
</div>
<div id="results"></div>
<div class="overlay"></div>
we extract the value of that key and send it to the search.php
<?php
include('db.php');
//file which contains the database details.
?>
<?php
if(isset($_POST['kw']) && $_POST['kw'] != '')
{
$kws = $_POST['kw'];
$kws = mysql_real_escape_string($kws);
$query = "select * from wp_posts where post_name like '%".$kws."%' and (post_type='post' and post_status='publish') limit 10" ;
$res = mysql_query($query);
$count = mysql_num_rows($res);
$i = 0;
if($count > 0)
{
echo "<ul>";
while($row = mysql_fetch_array($res))
{
echo "<a href='$row[guid]'><li>";
echo "<div id='rest'>";
echo $row['post_name'];
echo "<br />";
echo "<div id='auth_dat'>".$row['post_date']."</div>";
echo "</div>";
echo "<div style='clear:both;'></div></li></a>";
$i++;
if($i == 5) break;
}
echo "</ul>";
if($count > 5)
{
echo "<div id='view_more'><a href='#'>View more results</a></div>";
}
}
else
{
echo "<div id='no_result'>No result found !</div>";
}
}
?>
press the view more result will not show more result.
If I'm not mistaken, you want to bring next 10 with ajax ?
This situation behaves as a pagination,
You have to store the current click count in javascript . WÄ°thout clicking more button, the variable of clickCount is 0, when you click more ,then your variable clickCount=1 ,
while sending ajax , send clickCount to the php.
$.ajax
({
type: "POST",
url: "search.php",
data: "kw="+ kw+"&clickCount="+clickCount,
success: function(option)
{
$("#results").html(option);
}
});
You can query with limit&offset (clickCount )*10, itemCountForEachMoreClick = limit 0,10
when click more
limit 10,10
when click one more
limit 20,10. Do not forget to reset clickCount on keyPress !
php Side
$count = isset($_REQUEST["clickCount"])? $_REQUEST["clickCount"]:0;
$limitAndOffset = $count*10.",10";
$query = "select * from wp_posts where post_name like '%".$kws."%'
and (post_type='post' and post_status='publish') limit ".$limitAndOffset ;
I have a form with a text input and select option box. The text field uses an autosuggest to allow users to pick options from a list. Once a a value is selected from the autosuggest, the select option box is populated with options dependent on the selection.
I am working to change the code over so that the second box is a text input as well, so as not to limit the users choices (i.e. both fields should allow free text entries if the user does not want to select from the available choices).
I think I've stared at this code too long, and would love some help. Clearly the changes need to come in the loadCountry, populateSelect and loadcountrySelect functions.
I am using PHP, jQuery and jQuery UI Autocomplete.
Any help you could provide would be very much appreciated!
Scripts:
<script src="../../scripts/jquery-1.6.4.js"></script>
<script src="../../scripts/jqueryui/ui/jquery.ui.core.js"></script>
<script src="../../scripts/jquery.ui.widget.js"></script>
<script src="../../scripts/jquery.ui.position.js"></script>
<script src="../../scripts/jquery.ui.autocomplete.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function ord(chr) {
return chr.charCodeAt(0);
}
function chr(num) {
return String.fromCharCode(num);
}
function quote(str) {
return '"' + escape(str.replace('"', "'")) + '"';
}
String.prototype.titleCase = function () {
var chars = [" ", "-"];
var ths = String(this).toLowerCase();
for (j in chars){
var car = chars[j];
var str = "";
var words = ths.split(car);
for(i in words){
str += car + words[i].substr(0,1).toUpperCase() + words[i].substr(1);
}
ths = str.substr(1);
}
return ths;
}
function incrementTerm(term) {
for (var i = term.length - 1; i >= 0; i--){
var code = term.charCodeAt(i);
if (code < ord('Z'))
return term.substring(0, i) + chr(code + 1);
}
return '{}'
}
function parseLineSeperated(data){
data = data.split("\n");
data.pop(); // Trim blank element after ending newline
var out = []
for (i in data){
out.push(data[i].titleCase());
}
return out;
}
function guess(value){
var oldValue = $('.continent_autocomplete').val();
if (oldValue == value)
return;
$('.continent_autocomplete').val(value);
$('.continent_autocomplete').caret(oldValue.length, value.length);
}
function clearGuess(){
var field = $('.continent_autocomplete');
field.val(field.val().substring(0, field.caret().start));
}
function loadcontinent(request, response) {
var startTerm = request.term.toUpperCase();
var endTerm = incrementTerm(startTerm);
$.ajax({
url: '/db/continent.php?startkey='+startTerm+'&endkey='+endTerm,
success: function(data) {
var items = parseLineSeperated(data);
response(items);
},
error: function(req, str, exc) {
alert(str);
}
});
}
function loadcountry(handler) {
var continent = $('.continent_autocomplete').val().toUpperCase();
$.ajax({
url: '/db/country.php?key=' + continent,
success: function(data) {
handler(parseLineSeperated(data));
},
error: function(req, str, exc) {
alert(str);
}
});
}
function populateSelect(select, options) {
select.html('');
if (options.length) {
enableSelect();
for (i in options){
var option = options[i];
select.append($('<option></option>').val(option).html(option));
}
} else {
disableSelect('Country');
}
}
function loadcountrySelect(continentObj){
disableSelect('Loading...');
loadcountry(function(options){
populateSelect($('.country_autocomplete'), options);
});
}
function disableSelect(message){
var select = $('.country_autocomplete');
select.html("<option>" + message + "</option>");
select.attr('disabled', true);
}
function enableSelect(){
var select = $('.country_autocomplete');
select.attr('disabled', false);
}
populateSelect($(".country_autocomplete"), []);
$("input.continent_autocomplete").autocomplete({
source: loadcontinent,
select: function(event, ui){
$("input.continent_autocomplete").val(ui.item.value);
loadcountrySelect(event.target);
}
});
$("input.continent_autocomplete").keyup(function (event){
var code = (event.keyCode ? event.keyCode : event.which);
if (code == 8) { // Backspace
clearGuess();
}
event.target.value = event.target.value.titleCase();
loadcountrySelect(event.target);
});
});
</script>
HTML:
<div id="continent_name">
<label> Continent Name:</label>
<input type="text" id="continent_name" name="continent_name" class="continent_autocomplete" />
</div>
<div id="country">
<label> Country:</label>
<input type="text" id="country_autocomplete" name="country_autocomplete" class="country_autocomplete" />
</div>
continent.php
<?php
$db_host = 'XXX';
$db_user = 'XXX';
$db_password = 'XXX';
$db_name = 'XXX';
$db = new mysqli($db_host , $db_user ,$db_password, $db_name);
if(!$db) {
echo 'There was a problem connecting to the database';
} else {
if(isset($_GET['startkey'])) {
$mysearchString = $db->real_escape_string($_GET['startkey']);
if(strlen($mysearchString) >0) {
$query = $db->query("SELECT DISTINCTROW Continent
FROM locations
WHERE Continent
LIKE '$mysearchString%'
LIMIT 10");
if($query) {
while ($result = $query ->fetch_object()) {
print ucwords(strtolower($result->Continent))."\n";
}
} else {
echo 'ERROR: There was a problem with the query.';
}
} else {
}
} else {
echo 'Access denied.';
}
}
?>
country.php
<?php
$db_host = 'XXX';
$db_user = 'XXX';
$db_password = 'XXX';
$db_name = 'XXX';
$db = new mysqli($db_host , $db_user ,$db_password, $db_name);
if(!$db) {
echo 'There was a problem connecting to the database';
} else {
if(isset($_GET['key'])) {
$mysearchString = $db->real_escape_string($_GET['key']);
if(strlen($mysearchString) >0) {
$query = $db->query("SELECT Continent,Country,Abbrev
FROM locations
WHERE Continent
LIKE '$mysearchString%'
ORDER BY Country
LIMIT 20");
if($query) {
while ($result = $query ->fetch_object()) {
print ucwords(strtolower($result->Country))."/".
ucwords(strtolower(strtok($result->Abbrev,";")))."\n";
}
} else {
echo 'ERROR: There was a problem with the query.';
}
} else {
}
} else {
echo 'Access denied.';
}
}
?>
You're going to need to modify your PHP to get this to work optimally (filtering occurring on the server). I would update your PHP so that it queries your database with two parameters (one for country, one for continent):
$continent = $db->real_escape_string($_GET['continent']);
$country = $db->real_escape_string($_GET['country']);
$query = $db->query("SELECT Continent,Country,Abbrev
FROM locations
WHERE Continent ='$continent' and Country like '$country%'
ORDER BY Country
LIMIT 20");
(Please take with a grain of salt; I don't know PHP)
Basically, pass a continent (which was selected in the first input) along with the country search string (which was typed in the second input).
Next, you're going to need to apply the autocomplete widget to the second input. Something like:
$("#country_autocomplete").autocomplete({
source: function (request, response) {
var continent = $("#continent_autocomplete").val()
, country = request.term;
$.ajax({
url: '/db/country.php?continent=' + continent + "&country=" + country,
success: function(data) {
response(parseLineSeperated(data));
},
error: function(req, str, exc) {
alert(str);
}
});
}
});
Just for some polish, you'll probably want to clear #country_autocomplete when #continent_autocomplete changes. You can do that by adding an event handler for autocomplete's change event:
$("input.continent_autocomplete").autocomplete({
source: loadcontinent,
change: function () {
$("#country_autocomplete).val('');
}
});
Lastly, you'll want to remove any code that has to do with populating the country select, since you no longer need it.
The jQuery plugin Autocomplete like Google supports such functionality:
autocomplete.php (agly style, the whole logic at one place -- just to show the principle)
if(!empty($_GET['foo_name']) && !empty($_GET['bar_number'])) {
$sql = 'SELECT ... FROM ... WHERE';
$db = new MySQLi(...);
$db->query($sql);
$numbers = [];
while($row = $result->fetch_assoc()){
$numbers[] = $row['bar_number'];
}
}
echo json_encode($numbers);
autocomplete.html
<link href="/components/autocompletelikegoogle/jquery.autocomplete.css" media="screen" rel="stylesheet" type="text/css">
<script type="text/javascript" src="/components/autocompletelikegoogle/jquery.autocomplete.js"></script>
<script type="text/javascript" src="/js/autocomplete.js"></script>
<input type="text" name="foo_name" id="foo-name" value="">
<input type="text" name="bar_number" id="bar-number" value="">
autocomplete.js
$(function() {
$("#foo").autocomplete({
minLength: 3,
limit: 5,
source : [{
url:"/my/ajax/controller/foo?data[foo_name]=%QUERY%",
type:'remote'
}],
});
});
$(function() {
$("#bar").autocomplete({
minLength: 3,
limit: 5,
appendMethod:'replace',
source : [
function(query, add) {
fooName = $('#foo-name').val();
$.getJSON("/my/ajax/controller/bar?data[bar_number]=" + query + "&data[foo_name]=" + fooName, function(response) {
add(response);
})
}],
});
});
I'm making a simple voter that takes either a "like" vote or "dislike" vote. Then, I count the total number of likes and dislikes and output the total numbers. I figured out how to put in the votes using Jquery Ajax, but the number of votes do not update after I put in a vote. I would like to update the $numlike and $numdislike variables using Jquery Ajax.
Here is the PHP script pertaining to the output:
$like = mysql_query("SELECT * FROM voter WHERE likes = 1 ");
$numlike = 0;
while($row = mysql_fetch_assoc($like)){
$numlike++;
}
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo "$numlike like";
echo "<br>";
echo "$numdislike dislike";
UPDATE:
Jquery Ajax for uploading vote
<script>
$(document).ready(function(){
$("#voter").submit(function() {
var like = $('#like').attr('value');
var dislike = $('#dislike').attr('value');
$.ajax({
type: "POST",
url: "vote.php",
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished
});
function submitFinished( response ) {
response = $.trim( response );
if ( response == "success" ) {
jAlert("Thanks for voting!", "Thank you!");
}
return false;
});
});
</script>
<form id="voter" method="post">
<input type='image' name='like' id='like' value='like' src='like.png'/>
<input type='image' name='dislike' id='dislike' value='dislike' src='dislike.png'/>
</form>
vote.php:
if ($_POST['like'])
{
$likeqry = "INSERT INTO test VALUES('','1')";
mysql_query($likeqry) or die(mysql_error());
echo "success";
}
if ($_POST['dislike'])
{
$dislikeqry = "INSERT INTO test VALUES('','0')";
mysql_query($dislikeqry) or die(mysql_error());
echo "success";
}
If you want to change current like or dislike number after clicking it you must return result instead of printing it ! return json result and echo this and change div innerHTML to see new result !
............
............
............
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo json_encode( array( $numlike, $numdislike ) ) ;
exit();
Now in your html code :
$.ajax({
type: "POST",
url: "vote.php",
context:$(this)
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished(data)
});
function submitFinished( response ) {
response = $.parseJSON( response );
//Now change number of like and dilike but i don't know where are shown in your html
$('#like').attr('value',response[0]);
$('#dislike').attr('value',response[1]);
return false;
});
You can send a $_GET or $_POST variable to the file that you are calling with AJAX.
.load("google.com", "foo=bar", function(){
});