I've read through a number of similar questions and tried my hand at putting it to work on my website, but it is not working (when you click the link there is no response on the console and the database is not updated).
Here's what I want to do: I want users to rate a comment +1 by clicking an icon next to the comment. I want that to update my mysql comment_table column called rating with rating+1. When I do it without AJAX (ie, just set the form action to a php page?id=10) it works fine. I can't get the AJAX to update the database though.
My main page with the comment:
<span class="glyphicon glyphicon-chevron-up"></span>
The javascript below that link:
<script type="text/javascript">
function updateRating(rating, id){
$.ajax({
type: "GET",
url: "rating.php",
mode: "vote",
rating: rating,
id: <?php echo $thisperspective_row['id']; ?>,
success: function(response) {
console.log(response);
}
});
return false; // Prevent the browser from navigating to the-script.php
};
</script>
and my rating.php file is
<?php
require_once('connectiontodatabase.php');
/* simple comment up and down voting script */
$mode = $_GET['mode'];
$rating = $_GET['rating'];
$id = $_GET['id'];
if ($mode=="vote")
{
// The name of the
$cookie = "nameofmycookie".$id;
if(isset($_COOKIE[$cookie]))
{
echo '<div class="alert alert-warning"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> Sorry You have already rated this comment within the last 14 days.</div>';
}
else
{
$expiry = 1209600 + time(); // 14 day expiry
setcookie ($cookie, "voted", $expiry);
mysql_query ("UPDATE comment_table SET rating = rating+$rating WHERE id=$id", $connection);
}
}
?>
The php runs fine and all the variables are listed properly when I view the source. However, when I click the link, there is no response at all and the console does not output the response. What am I doing wrong? Thanks in advance!
Firstly you should change the way you are detecting the click event. Check out this fiddle. Then secondly you need to pass all the variables through in one JSON string using the data option. Your code should look something like this:
<span class="glyphicon glyphicon-chevron-up clickable"
data-rating="1"
data-id="<?php echo $thisperspective_row['id']; ?>"></span>
<script type="text/javascript">
$('.clickable').on('click', function() {
var data = {
mode: "vote",
rating: $(this).data('rating'),
id: $(this).data('id')
};
$.ajax({
type: 'GET',
url: 'rating.php',
data: data,
success: function(response) {
console.log(response);
}
});
});
</script>
First off all, check that you are loading jQuery, then use this code
function updateRating(rating, id){
$.ajax({
type: "GET",
url: "rating.php",
mode: "vote",
data: { rating: rating, id: id },
success: function(response) {
console.log(response);
}
});
return false; // Prevent the browser from navigating to the-script.php
};
is working for me.
note that I removed ` inside Ajax, since you are already sending the params in the function, also to send params you have to use data:, you can see more examples here Ajax jQuery
Related
I'm trying to POST some data to another page with AJAX but no info is going, i'm trying to pass the values of two SELECT (Dropdown menus).
My AJAX code is the following:
$('#CreateHTMLReport').click(function()
{
var DeLista = document.getElementById('ClienteDeLista').value;
var AteLista = document.getElementById('ClienteParaLista').value;
$.ajax(
{
url: "main.php",
type: "POST",
data:{ DeLista : DeLista , AteLista : AteLista },
success: function(data)
{
window.location = 'phppage.php';
}
});
});
Once I click the button with ID CreateHTMLReport it runs the code above, but it's not sending the variables to my phppage.php
I'm getting the variables like this:
$t1 = $_POST['DeLista'];
$t2 = $_POST['ParaLista'];
echo $t1;
echo $t2;
And got this error: Notice: Undefined index: DeLista in...
Can someone help me passing the values, I really need to be made like this because I have two buttons, they are not inside one form, and when I click one of them it should redirect to one page and the other one to another page, that's why I can't use the same form to both, I think. I would be great if someone can help me with this, on how to POST those two values DeLista and ParaLista.
EDIT
This is my main.php
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "main.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// Use this to redirect on success, this won't get your post
// because you are sending the post to "main.php"
window.location = 'phppage.php';
// This should write whatever you have sent to "main.php"
//alert(data);
}
});
});
And my phppage.php
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
echo "Nothing sent!";
And I'm still getting "Nothing Sent".
I think you have a destination confusion and you are not retrieving what you are sending in terms of keys. You have two different destinations in your script. You have main.php which is where the Ajax is sending the post/data to, then you have phppage.php where your success is redirecting to but this is where you are seemingly trying to get the post values from.
/main.php
// I would use the .on() instead of .click()
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "phppage.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// This should write whatever you have sent to "main.php"
alert(data);
}
});
});
/phppage.php
<?php
# It is prudent to at least check here
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
# Write a default message for testing
echo "Nothing sent!";
You have to urlencode the data and send it as application/x-www-form-urlencoded.
i want to post data to current page with ajax.But i couldnt do that.
I have doctor panel and i wanna get patient's data from 'hastalar' table in my db by using patient's national id:'tc'.Session is using by doctor so i guess i cant use $_SESSION for patient at same time.And i wanna use only one php page.So i cant see my patient's datas in current page.Pls help me guys.
dokyon.php
textbox
<a href="#" id="ara" class="ara" ><br/>SEARCH PATIENT</a>
<input type ="text" id="tc" name="tc" />
JQUERY
<script type="text/javascript" >
$(function() {
$(".ara").click(function(){
var tc = $('#tc').val();
$.ajax({
url:'dokyon.php'//current page
type: 'POST',
data:{tc:tc},
success: function(){
alert(data);
}
});
});
});
</script>
php codes
<?php
$tc=$_POST['tc'];
echo $tc;
$query = mysqli_query($connection,"select * from hastalar where tc_no=$tc");
while($hasta = mysqli_fetch_array($query)){
echo $hasta['name'];}
?>
For your ajax code, you need to add dataType parameter and add the parameter of success: function(data), so like this:
$.ajax({
url:'dokyon.php'//current page
type: 'POST',
data:{tc:tc},
dataType:"html",
success: function(data){
alert(data);
}
});
For additional: always do debuging for sending data with inspect element of browser.
Hopefully it will be success for you :)
I am trying to make a like/dislike system on the posts of my social networking website with each post having an pid(auto-increment). I run a while loop that fetches the post from database and show it and also give an option to like/dislike below each post. I am not using any input radio or checkbox button, instead I have used an icon for which the colour should change when clicked and also an AJAX function is called using onclick event on the same icon.
The AJAX function should go to a file likes.php where the a search is done for the row having that post id and the likes column of that row is updated or incremented by 1 and then the result is returned by echo. All this should work but not working.
The AJAX function takes post id (pid) as a parameter and pass it to likes.php where likes field corresponding to that post id is incremented. The like icon for each post has been assigned an id = post id so as to select that like button which is clicked and for which the post id is passed in AJAX function. The result is returned to a span element having an id = "like"+ post pid.
My code
index.php - to show posts and like button
$q = $conn->prepare("SELECT * FROM posts ORDER BY pid DESC");
$q->execute();
while($row = $q->fetch(PDO::FETCH_ASSOC)) {
#my post representation using div and all...
#like/dislike button
<span class=\"right floated\" id=\"like".$row['pid']."\" >
<i id=\"".$row['pid']."\" class=\"heart icon\" onclick=\"like(".$row['pid'].")\"></i>
</span>
}
ajax-function
'a' is a parameter-local variable
<script>
$(document).ready(function(){
function like(a) {
$("#"+a).css('color','red');
$.ajax({
url: "likes.php",
data: ({pid: a}),
type: "POST",
success:function(data){
$("#like"+a).html(data);
},
error:function (){}
});
}
});
}
</script>
likes.php file
<?php
session_start();
include 'db.php';
$j =$_POST['pid'];
$sql = "UPDATE posts SET likes = likes +1 WHERE pid ='" . $j . "'";
$r = $conn->prepare($sql);
$r->execute();
$sql = "SELECT * FROM posts WHERE pid ='" . $j . "'";
$r = $conn->prepare($sql);
$r->execute();
$ry=$r->fetch();
if($r)
{
echo $ry['likes'];
}
?>
Please tell me why doesn't it work; at least it should detect the icon click using onclick but I think even that's not working. The AJAX function is not getting executed as nothing happens on clicking.
The problem here, that you declare the like function inside the document ready so outside of that scope your function is not defined.
Posible solutions:
Declare your function before the document ready scope
Create a var outside of document ready
Use jQuery .click (or .on('click',) instead of the onClick html property to call your function
Declare your function before the document ready scope
script:
function like(a) {
$("#" + a).css('color','red');
$.ajax({
url: "likes.php",
data: {pid: a},
type: "POST",
success:function(data){
$("#like" + a).html(data);
},
error:function (){}
});
}
Create a var outside of document ready
var like;
$(document).ready(function(){
like = function(a) {
$("#" + a).css('color','red');
$.ajax({
url: "likes.php",
data: {pid: a},
type: "POST",
success:function(data){
$("#like"+a).html(data);
},
error:function (){}
});
}
});
(This can cause some problem, because until the document is not ready this function not gonna work)
Use jQuery .click (or .on('click',) instead of the onClick html property to call your function
index.php
<span class=\"right floated\" id=\"like".$row['pid']."\" >
<i id=\"".$row['pid']."\" class=\"heart icon action-like\"></i>
</span>
script
$('.action-like').on('click', function(){
var pid = $(this).attr('id');
$("#" + pid).css('color','red');
$.ajax({
url: "likes.php",
data: {pid: pid},
type: "POST",
success:function(data){
$("#like" + a).html(data);
},
error:function (){}
});
});
This should work. But use mysqli instead mysql and do not pass parameters to a query like you do (read about sql injection). And do not echo long static strings instead close php tag and open when needed to echo out a dynamic data.
Okay so am using Ajax to send a JS variable from index.php to page2.php . Once it is set to page2.php, the database is edited while the user has been on index.php the entire time. However, I need the index.php to reload or refresh once page2.php has finished updating the database in the background. To give you a better clue, I will include some of my code.
On Index.PHP is :
<a href='#' class='dbchange' onclick='dbchange(this)' id='".$ID'>Update</a>
and
function dbchange(obj) {
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: 'page2.php',
data: "NewID=" + id,
});
}
So basically when they click the button that says "Update" it sends the ID of the button the page2.php and page2.php from there updates the changes the database using that info. However, the URL the user is on is:
http://website.com/index.php#
and the database has not updated for them and they have to see the annoying hash symbol in the URL. I have googled how to refresh the page in JS, and found things that either do not work or do work , but result in the variables not being sent to the PHP file. I just need it so that after it is sent to the php file, and preferably after the php file is finished, the index.php page refreshes and without the # at the end.
e.preventDefault() is the answer but if I may suggest:
Get rid of that inline function and add the event handler with jQuery.
$(function () {
$('.dbchange').click (function (e) {
e.preventDefault();
var id = this.id;
$.ajax({
type: "POST",
url: 'page2.php',
data: {NewID: id},
success: function(data) {
window.location.reload();
}
});
});
});
Remove # then replace with javascript:void(0):
<a href='javascript:void(0)' class='dbchange' onclick='dbchange(this)' id='".$ID'>Update</a>
JS:
function dbchange(obj) {
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: 'page2.php',
data: "NewID=" + id,
success: function() {
window.location.reload();
}
});
}
You can see my code below. I face a challenge that I don't know how to use one button to correspond different click. On the php, if I put the button inside the foreach loop, it will create a lot of button, that's not what I want. In the js, if I put the on.click button inside the foreach elements loop, it will also create a lot of on.click button, so I click one button, it will run many times depends on the number of label_name. I think about addClass, if I clicked the heart div, I use js to add a class, and then get the attr('id') inside button.on.(click), so I can differentiate them in my server php and mysql can request the correspond data. But the problem is that if a user click every div, then every div add classes, then problem again.
var current_page = 1;
var elements_body = {
"heart": "1",
"eye": "2",
"ear_nose_throat": "3",
"hand_foot_mouth": "4"
};
jQuery.each(elements_body, function (label_name, label_num) {
var disease_label = $('#' + label_name + '_d');
disease_label.on('click', function () {
var data = {
action: 'body_part_keyword', //wordpress loading url
postSearchNonce: MyAjaxSearch.postSearchNonce,
current_page: current_page,
label_name: label_name //this label_name will differentiate data that need to request from mysql in the action.php
};
$.ajax({
url: MyAjaxSearch.ajaxurl,
type: 'POST',
cache: false,
data: data,
success: function (data) {
disease_menu_result.append(data);
current_page++
}
}); //ajax
});
}); //jQuery.each
$('#loadmorebutton_body').on('click', function () {
//I dont know how can I make this button to correspond above code
});
<div id="disease_menu">
<?php
$arr = Array(
'heart'=>'heart',
'eye'=>'eye',
'ear_nose_throat'=>'ear nose throat',
'hand_foot_mouth'=>'hand foot mouth'
);
foreach ($arr as $key=>$value) {
?>
<div class="disease_li" id="disease_li_<?php echo $key;?>">
<span class="disease_span" id="<?php echo $key;?>_d"><label>(<?php echo $value;?>)</label>diseases</span>
</div>
<!--disease_li-->
<?php }?>
</div>
<!--disease_menu-->
<button id="loadmorebutton_body">Load More</button>
Use javascript functions :
function MyFunction() {
jQuery.each( elements_body, function( label_name, label_num) {
var disease_label= $('#'+ label_name + '_d');
disease_label.on('click',function(){
var data={
action: 'body_part_keyword',//wordpress loading url
postSearchNonce : MyAjaxSearch.postSearchNonce,
current_page:current_page,
label_name:label_name//this label_name will differentiate data that need to request from mysql in the action.php
};
$.ajax({
url: MyAjaxSearch.ajaxurl,
type:'POST',
cache: false,
data: data,
success: function(data){
disease_menu_result.append(data);
current_page++
}
});//ajax
});
});
}
$('#loadmorebutton_body').on('click',function(){
MyFunction();
}