Working on a like/dislike function for my blogpost site, and the variables won't flow through. I've stared at this for days, and cannot find the break as all of the code looks fine and I've included all the necessary pages containing varibales. Any insights?
This is the "button" I'm using for a "like" button:
Like <span id="likes" class="likereadout">' . $likes . '</span>
The id variable shows up correctly when I "inspect element", but won't pass through to the following Javafunction:
function like_add(postid) {
$.post('like_add.php', {postid:postid}, function(data) {
if (data == 'success') {
alert('Woohoo');
} else {
alert('I need sleep.');
}
});
}
The Javascript is supposed to pass the variable to like_add.php, which reads:
<?php
include 'init.php';
if (isset($_POST['postid']) && article_exists($_POST['postid'])) {
$postid = $_POST['postid'];
if (previously_liked($postid) === true) {
echo 'You\'ve already liked this!';
} else {
add_like($postid);
echo 'success';
}
}
?>
Which refs the following php functions included in the init.php file:
function article_exists($postid) {
$postid = (int)$postid;
return (mysql_result(mysql_query("SELECT COUNT('id') FROM 'blabbing' WHERE 'id' = $postid"), 0) == 0) ? false : true;
}
and:
function add_like($postid) {
$postid = (int)$postid;
mysql_query("UPDATE 'blabbing' SET 'likes' = 'likes' + 1 WHERE 'id'= $postid");
mysql_query("INSERT INTO 'likes' ('user_id', 'id') VALUES ($ip, $postid)");
}
Realllll new to all of this, so please go easy on me. Thank you so much for your help!
function article_exists($postid) {
$postid = (int)$postid;
return (mysql_result(mysql_query(
When you send AJAX data throught $.post, it have to be stringified:
$.post('like_add.php', JSON.stringify({postid:postid}), function(data) {
Related
I'm trying to make a likes/claps/heart system on my site and found this site (https://www.techolac.com/wordpress/how-to-add-likes-to-posts-in-wordpress-without-a-plugin/) that taught how to do it. I made some adjustments the problem is that when I do like the page refresh and I just wanted the number to refresh and not the whole page.
I saw what I could do in AJAX but i didnt know how.
Functions.php / Wordpress
// Add buttons to top of post content
function ip_post_likes($content) {
ob_start();
?>
<a href="<?php echo add_query_arg('post_action', 'like'); ?>">
<span class="icon-claps pr-2"><?php echo get_like_count('likes') ?></span>
</a>
<?php
$output = ob_get_clean();
return $output . $content;
}
add_filter('the_content', 'ip_post_likes');
//Get like
function get_like_count($type = 'likes') {
$current_count = get_post_meta(get_the_id(), $type, true);
return ($current_count ? $current_count : '');
}
//Process like
function ip_process_like() {
$processed_like = false;
$redirect = false;
// Check if like
if(is_singular('post')) {
if(isset($_GET['post_action'])) {
if($_GET['post_action'] == 'like') {
// Like
$like_count = get_post_meta(get_the_id(), 'likes', true);
if($like_count) {
$like_count = $like_count + 1;
}else {
$like_count = 0;
}
$processed_like = update_post_meta(get_the_id(), 'likes', $like_count);
}
if($processed_like) {
$redirect = get_the_permalink();
}
}
}
// Redirect
if($redirect) {
wp_redirect($redirect);
die;
}
}
add_action('template_redirect', 'ip_process_like');
The problem is that when I do like the page refresh and I just wanted the number to refresh and not the whole page.
I saw what I could do in AJAX but i didnt know how.
Image:
This is the whole code. I am using wordpres and twig / timber
I am writing some functions for the delete button in my table, and I can't get it right. I don't know where did I go wrong and I hope it makes sense.
Here's my script:
function Delete(str){
if (confirm('Are you sure you want to Delete this Information ?') == 1) {
xhttp.onreadystatechange=function(){
if (xhttp.readyState == 4 && xhttp.status == 200) {
if (xhttp.responseText == 1) {
alert('Information that have you selected has already been Deleted');
}else{
alert('Error: Function');
}
}
}
xhttp.open("POST","DeleteInformation.php",true);
xhttp.send("ID=" + str);
}
}
Here's the php file
DeleteInformation.php
<?php
include_once('config.php');
include_once('mysql.php');
$OpenMysql = new MySqlConnect(Host,User,Pass,Database);
$ID = $OpenMysql->DataFilter(isset($_REQUEST['ID'])?$_REQUEST['ID']:'');
$query = "Delete From items where itemcodes = '$ID'";
$result = $OpenMysql->ExecuteQuery($query);
if (!$result) {
echo "True";
}else{
echo "False";
}
?>
The issue I think was the Delete function was trying to call an undeclared and undefined object xhttp - this should be assigned with a new instance of XMLHttpRequest so your ajax function would never have sent any data. Of course, if you had defined xhttp=new XMLHttpRequest before the code you have shown then that comment would not necessarily hold true.
As you did not show how you call the function I have emulated how it might be called to test the functionality in the demo below.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/* randomly echo 1 or 0 to emulate both states */
echo rand(0,1);
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>ajax php delete</title>
<script>
function Delete(str){
if( confirm('Are you sure you want to Delete this Information ?') == 1 ) {
/* This variable was not defined so you should have had an error, unless it was defined globally elsewhere */
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function(){
if ( this.readyState == 4 && this.status == 200 ) {
if ( this.responseText == 1 ) {
alert('Information that have you selected has already been Deleted');
}else{
console.error('Whoops - an error! %s',this.response);
}
}
}
xhttp.open( "POST", location.href, true );//"DeleteInformation.php"
xhttp.send( "ID=" + str );
}
}
document.addEventListener('DOMContentLoaded',function(){
Array.prototype.slice.call( document.querySelectorAll('input[data-name="delete"]') ).forEach(function(bttn){
bttn.onclick=function(event){
/* call the `delete` function */
Delete.call( this, this.dataset.id );
}.bind( bttn )
})
},false);
</script>
</head>
<body>
<form>
<?php
for( $i=1; $i<=10; $i++ ){
echo "
<input type='button' data-name='delete' data-id='$i' value='Delete'>";
}
?>
</form>
</body>
</html>
With regards to your PHP code - by default the include_path is probably set something like this .;C:\php5\pear which is not obviously useful as such. It is likely that you have set these files below (config,mysql) in the same working directory ( though that is a guess ) so unless you have modified the include path these calls below will fail. Personally I like to use a full path to included files whenever possible ~ such as require __DIR__ . '/somescript.php'
If however you have altered the include_path using set_include_path then ignore previous comment and instead fcus upn the javascript - if you do not see a network(xhr) request in the console then the ajax function is not being called...
<?php
/* this may or may not be correct the files location is unknown */
require __DIR__ . '/config.php';
require __DIR__ .'/mysql.php';
$id=!empty( $_POST['ID'] ) ? filter_input( INPUT_POST, 'ID', FILTER_SANITIZE_NUMBER_INT ) : false;
if( $id ){
/*
Host, User, Pass, Database
Are these defined as constants in config.php or mysql.php??
*/
$OpenMysql = new MySqlConnect( Host, User, Pass, Database );
$ID=$OpenMysql->DataFilter( $id ); //? no idea what this does
$query = "Delete from `items` where `itemcodes` = '$ID'";
$result = $OpenMysql->ExecuteQuery( $query );
echo $result ? 'true' : 'false';
}
?>
Hope you find the above useful in resolving your issue
My server code:
<?php
$temp = $_GET["emailData"];
if($temp != ''){
echo "YEAAAAAAAAAAAA";
}
?>
Javascript:
$('#EMAIL').click(function(){
console.log(sendDATA[0]);
$.post("indexSMS.php", {emailData: sendDATA[0]}, function(response){
if ( response == 'success' ) {
// do something
} else {
// do something else
}
});
});
It's day one for me with php. Nothing seems to be happening in the php file. Where will the echo output be visible. How do I send the response back?
Thanks a lot guys.
You are sending a a post request so you should use $_POST instead of $_GET
$temp = $_POST["emailData"];
if($temp != ''){
echo "YEAAAAAAAAAAAA";
}
Alright I've been trying to find an answer to this for hours already but I couldn't resolve it myself.
I'm trying to call a Javascript parent function from a PHP function, however, it is not getting called.
When using the onclick method onclick='parent.dosomething(); everything seems to work fine but if I try to call the function by echo'ing it out, it would just fail for some reason.
echo "<script>parent.reloadprofmessages();</script>"; //this is what is not getting called
Here's the PHP function:
function checkactivity($username)
{
//These are just queries being executed (irrelevant)
$querystats = "SELECT users.fullname, activity.id, activity.sender, activity.receiver, activity.type, activity.dateposted, activity.seen, activity.related FROM activity, users WHERE activity.receiver = '$username' && activity.seen = '0' ORDER BY id DESC LIMIT 1";
$resultstats = mysql_query($querystats);
$num_stats = mysql_num_rows($resultstats);
$rowactivity = mysql_fetch_assoc($resultstats);
//End of queries
if($num_stats > 0) //If there are registries
{
$user = $_SESSION['Username'];
$activity_date = $rowactivity["dateposted"];
$activity_type = $rowactivity["type"];
$activity_sender = $rowactivity["sender"];
$timeactivity = strtotime( "$activity_date" );
$actualtime = time();
$timetoseconds = $actualtime - $timeposted;
$timetominutes = floor($timepassedtoseconds/60);
if($timetominutes < 2)
{
if($activity_sender != $user)
{
if($activity_type == 1) //Messages
{
echo "<script>parent.reloadprofmessages();</script>"; //this is what is not getting called
}
}
}
}
}
And this is my Javascript function at the parent page:
function reloadprofmessages()
{
$('#friendrequests').load('showprofmessages.php?username=<?php echo $actualuser; ?>').fadeIn("slow");
} //refreshes messages
I pressed CTRL + Shift + I in Google Chrome to get to the developer tools, Network > page that does the request that calls the PHP function > Preview and this was what I received:
<script>parent.reloadprofmessages();</script>
However, the function is not getting called.
Resolving this would solve me a lot of problems, to me it is actually still a mystery to know why it doesn't work since it has worked in other cases.
Thank you for your help in advance.
It's not a good idea to fetch javascript and execute it with AJAX. What I would suggest is to firstly change your PHP to this:
if($activity_type == 1) //Messages
{
echo "1";
}
else {
echo "0";
}
Then change your Javascript to this:
function reloadprofmessages()
{
var can_reload = $.ajax({ url: "showprofmessages.php?username=<?php echo $actualuser; ?>" });
if (can_reload) {
parent.erloadprofmessages();
}
}
Hope that helps
Add the type attribute for script tag
echo "<script type='text/javascript' >parent.reloadprofmessages();</script>";
and remember to define the javascript function before this line
So here is what was wrong: (Showing errors)
function checkactivity($username)
{
//These are just queries being executed (irrelevant)
$querystats = "SELECT users.fullname, activity.id, activity.sender, activity.receiver, activity.type, activity.dateposted, activity.seen, activity.related FROM activity, users WHERE activity.receiver = '$username' && activity.seen = '0' ORDER BY id DESC LIMIT 1";
$resultstats = mysql_query($querystats);
$num_stats = mysql_num_rows($resultstats);
$rowactivity = mysql_fetch_assoc($resultstats);
//End of queries
if($num_stats > 0) //If there are registries
{
$user = $_SESSION['Username'];
$activity_date = $rowactivity["dateposted"];
$activity_type = $rowactivity["type"];
$activity_sender = $rowactivity["sender"];
$timeactivity = strtotime( "$activity_date" ); //$timeactivity was not being used
$actualtime = time();
$timetoseconds = $actualtime - $timeposted; //$timeposted doesn't even exist, in other words I wasn't even converting the $activity_date timestamp to time.
$timetominutes = floor($timepassedtoseconds/60);
if($timetominutes < 2)
{
if($activity_sender != $user)
{
if($activity_type == 1) //Messages
{
echo "<script>parent.reloadprofmessages();</script>"; //this was not the correct way of calling a function from the parent page.
}
}
}
}
}
About the Javascript function:
This is what I ended with:
var auto_refresh = setInterval(
function reloadstring()
{
$.get("checknewactivity.php?vprofile=<?php echo $actualuser; ?>", function(activity){
if (activity == 1)
{
$('#profcommentsdiv').load('showprofmessages.php?vprofile=<?php echo $actualuser; ?>').fadeIn("slow");
}
});
}, 1000); // refresh every 1000 milliseconds
And now it works, thank you for your help, I really appreciate it, and as usual, I always get to a safer solution after asking it here.
I am using a lot of jQuery in a project am working on.
I have a javascript function that makes an ajax request to a controller which returns data in JSON.
I would like to display a user friendly message informing the user that he/she has no information stored yet. But I'm confused as to how to send a response in JSON so my javascript function can determine whether the user has information to be displayed.
Here is my javascript function:
function latest_pheeds() {
var action = url+"pheeds/latest_pheeds";
$('#pheed-stream').html('<div class="loading"></div>');
$('.loading').append('<img src="'+pheed_loader_src+'" />');
$.ajax({
url:action,
type:'GET',
dataType:'json',
error: function () {
},
success:function(data) {
$('.loading').fadeOut('slow');
$.each(data,function(index,item) {
$('#pheed-stream').append
(
'<div class="pheed" id="'+item.pheed_id+'">'+
'<p><a class="user_trigger" href="users/info/'+item.user_id+'">'
+item.user_id+'</a></p>'+
'<p>'+item.pheed+'</p>'+
'<div class="pheed_meta">'+
'<span>'+item.datetime+' Ago</span>'+
'<span class="cm">'+item.comments+
'<img class="comment_trigger" src="/pheedbak/assets/img/comment.png" title="Click to comment on pheed" onclick="retrieve_comments('+item.pheed_id+')">'+
'</span>'+
'<span>'+item.repheeds+
' Repheeds'+
'<img class="repheed_trigger" src="/pheedbak/assets/img/communication.png" title="Click to repheed" onclick="repheed('+item.pheed_id+')">'+
'</span>'+
'<span>'+
'Favourite'+
'<img class="favourite_trigger" src="/pheedbak/assets/img/star.png" title="Click to make this a favourite" onclick="favourite_pheed('+item.pheed_id+')" />'+
'</span>'+
'</div>'+
'</div>'
);
});
}
});
}
And heres the controller function the ajax request is made to
function latest_pheeds() {
//Confirm if a user is logged before allowing access
if($this->isLogged() == true) {
//load the pheed model for database interaction
$this->load->model('pheed_model');
//load user model
$this->load->model('user_model');
//load comment model
$this->load->model('comment_model');
//store the pheeds to a the $data variable
$data = $this->pheed_model->get_latest_pheeds();
//Load the date helper to calculate time difference between post time and current time
$this->load->helper('date');
//Current time(unix timetamp)
$time = time();
//pheeds
$pheeds = array();
if(count($data) > 0 ) {
foreach($data as $pheed) {
$row['pheed_id'] = $pheed->pheed_id;
$row['user_id'] = $this->user_model->return_username($pheed->user_id);
$row['pheed'] = $pheed->pheed;
$row['datetime'] = timespan($pheed->datetime,$time);
$row['comments'] = $this->comment_model->count_comments($pheed->pheed_id);
$row['repheeds'] = $pheed->repheeds;
$pheeds[] = $row;
}
echo json_encode($pheeds);
$response['response'] = "Ok";
$res[] = $response;
echo json_encode($res)."\n";
}
} else {
}
It generates the JSON output,but the syntax is broken so i cant read it with javascript,
but once i get rid of the following code from the above method it works normally
$response['response'] = "Ok";
$res[] = $response;
echo json_encode($res)."\n";
You MUST only use json_encode($data) once in a response, if you want to output more stuff, you need to merge your data into one array and send that.
EDIT: To be clear, one way you could do it is like this:
echo json_encode(array('pheeds' => $pheeds, 'res' => $res));
Then in JS you will get an array with the keys "pheeds" and "res".
Although it may be of little practical significance, I would also recommend doing this before you echo the json encoded string:
header('Content-Type: application/json');