How to fix jquery ajax not sending data to PHP file - php

I'm trying to make a system similar to a like/dislike system. I have it all setup, but my jquery.ajax function is not sending the data I need it to. The function is being called, but the data is not being set.
I've added a function to check for if the isset if statement is being called, but that function isn't being called, so I know it's something wrong with the ajax function. I've tried looking over other posts of similar problems, but none of those solutions worked. Sorry if this is just me being stupid, and the solution is easy.
PHP - community.php - The main webpage
<div id="entries">
<?php foreach($posts as $post): ?>
<div class="entry">
<div class="entryInfo">
<img src="IMAGES/PlaceholderAlbumCover.jpg" alt="Album Cover" class="center" height="200" width="200">
<div class="artistInfo">
<h4><?php echo $post['name'] ?></h4>
<p> <?php echo $post['artist'] ?> </p>
</div>
<div class="votes">
<i <?php if(userVoted($post['id'])): ?>
class="fas fa-heart vote-btn"
<?php else: ?>
class="far fa-heart vote-btn"
<?php endif ?>
data-id="<?php echo $post['id'] ?>" style="color:#f44242">
</i>
<span class="voteCount"><?php echo getVotes($post['id']); ?></span>
</div>
</div>
</div>
<?php endforeach ?>
</div>
Javascript - vote.js - Handles click detection and sending the response to vote.php
$.ajax({
url: 'index.php?page=community',
method:'post',
data: {
'action':action,
'post_id':post_id
},
success: function(data) {
if(action == 'unvote') {
$click_btn.toggleClass('far fas');
} else if(action == 'vote') {
$click_btn.toggleClass('far fas');
}
}
});
PHP - vote.php - Handles the server side of the system
if(isset($_POST['action'])) {
consoleLog();
$post_id = $_POST['id'];
$action = $_POST['action'];
switch($action) {
case 'vote':
$query="INSERT INTO rating_info (user_id, post_id, rating_action)
VALUES ($user_id, $post_id, 'vote')
ON DUPLICATE KEY UPDATE rating_action='vote'";
break;
case 'unvote':
$query="DELETE FROM rating_info WHERE user_id=$user_id AND post_id=$post_id";
break;
default:
break;
}
mysqli_query($dbconnect, $query);
echo getRating($post_id);
exit(0);
}
What it's supposed to do is increment or decrement the vote count in the mysql database by setting the action to vote or unvote, but the js file just never sets the action data, or the PHP script is never able to catch it.

You are passing the post data in the javascript as post_id but trying to retrieve it in the php script as $_POST['id']
Do this instead: $_POST['post_id']

Related

How to make ajax load more content, using button pagination work

I intend to load more videos into a div/page using load more button pagination with ajax, xhr status shows status as ok(200) but no video content is loaded.
videos.php:
<div id="videosline " class="col-md-3 content-grid ">
<?php //code to get first 3 videos working ?>
</div>
<button id="loadvideos" class="btn ">Load More</button>
//ajax jquery code to load in more three videos at every button click
$(document).ready(function(){
var videoscount = 3;
$("#loadvideos").click(function(){
videoscount = videoscount + 3;
$.ajax({
type:"GET",
url:"loadmore.php",
data:{
'videosnewcount':videoscount
},
sucess: function(data){
$('videosline').append(data);
}
});
loadmore.php:
<?php
include 'master.php';//some php config and db config
$videosnewcount = 3;
$condition = [];
array_push($condition,['mediatype = ' => ['video/mp4','AND']]);
$data = find('files',$condition,["ORDER BY " => "id DESC","LIMIT" => $videosnewcount ]); //php function for mysql query
foreach($data as $video) { ?>
<?php if($video['mediatype'] == 'video/mp4') { ?>
<?php include('cards/video.php'); ?>
}
}
?>
cards/video.php:
<?php if(explode('/',$video['mediatype'])[0] == 'video') { ?>
<a href="mediafile.php?id=<?= $video['id']?>&medianame=<?= $video['filename']?>"><div style=" height:;">
<video controlslist="nodownload" oncontextmenu="return false;" poster="member/<?= $video['poster'] ?>" style="height:250px; width:100%; " type="video/mp4" class="pr100" src="member/<?= $video['path'] ?>" > </video</div></a><?php } ?>
I don't know if it matters but in loadmore.php, you are not getting the GET parameter from the Ajax call so I don't know why you are sending it.
What do matters, is that loadmore.php is not echoing any data so your Ajax response should be empty. Also, I can't see that your sending any query to your database. Where is the "SELECT from table WHERE..."?

Yii: run a function when a submitButton is pressed

I'm very new to Yii, and trying to understand an existing web app, so please bear with me.
I've been having issues with a certain function, that seems to fail retaining data whenever actionView is calledhere, but I thought perhaps I was going about this problem all wrong.
Instead, I thought perhaps the button could directly run the function from the controller, instead of... whatever it was doing prior.
I looked at a sample here that had this:
<?php echo CHtml::submitButton('CSV Report', array('submit'=>'getReport')); ?>
Where getReport is the function in my controller (actionGetReport).
Unfortunately, it's not working. Here's the code of my _commentform.php:
<?php $post = $forum; ?>
<?php $comment = $model; ?>
<div id="comment_form<?=$post->id?>" class="other-member-comment-box">
<?php
$user=Persons::model()->findByAttributes(array('party_id'=>Yii::app()->user->id));
$country=Lookup_codes::model()->findByAttributes(array('id'=>$user->country));
$location = empty($country) ? '' : 'from '.$country->name;
?>
<div class="user-profilepic">
<a href="<?php echo Yii::app()->createUrl('persons/view/id/'.$user->showViewLinkId())?>"><img src="<?php
if(!empty($user->image) AND file_exists( Yii::getPathOfAlias('webroot').'/images/profile_picture/'.$user->party_id . $user->image)){
echo Yii::app()->request->baseUrl.'/images/profile_picture/'.$user->party_id . $user->image;
} else echo Yii::app()->request->baseUrl.'/images/profile_picture/NA.jpg';
?>"></a>
</div>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'comment-form',
'action'=>Yii::app()->createUrl('forum/view/id/'.$forum->id),
'enableAjaxValidation'=>false,
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->hiddenField($model,'node_type_id',array('value'=>'7')); ?>
<?php echo $form->error($model,'node_type'); ?>
</div>
<div class="row">
<?php echo $form->hiddenField($model,'content_id',array('value'=>$forum->id)); ?>
<?php echo $form->error($model,'content_id'); ?>
</div>
<div class="row">
<?php echo $form->hiddenField($model,'category',array('value'=>$forum->category)); ?>
<?php echo $form->error($model,'category'); ?>
</div>
<div class="row">
<?php echo $form->textArea($model,'content',array('rows'=>6, 'cols'=>90),array('id'=>'sample')); ?>
<?php echo $form->error($model,'content'); ?>
</div>
<input type="hidden" value="<?php echo $view; ?>" id="view" name="view"/>
<div class="row buttons">
<?php
if ($view == 'view'){
if ($model->isNewRecord) {
echo CHtml::submitButton('Reply', array('id'=>'comment'.$comment->id));
} else {
echo CHtml::button('Save', array('submit'=>'updatecomment'));
}
}?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
</div>
And here's the UpdateComment function from my controller:
public function actionUpdateComment()
{
Yii::log(CVarDumper::dumpAsString("ForumController: Update COMMENT!"));
Yii::log(CVarDumper::dumpAsString($_POST['Comment']));
exit();
}
I'm not exactly sure what I'll get by the $_POST['Comment'], but if the code worked, I'd very least expect it to log out the "ForumController: Update COMMENT!". It doesn't.
I tried changing the submitButton to button, but that just kills the button function entirely.
Next, I tried this answer here.
So I changed the submitButton code to this:
echo CHtml::submitButton($model->isNewRecord ? 'Reply' : 'Save',array('id'=>'comment'.$comment->id));
And added this to the end:
<script>
$(document).ready(function() {
$('#text_form_submit').click(function(ev) {
ev.preventDefault();
$.ajax({ type: 'POST', dataType: 'JSON',
url: '<?php echo Yii::app()->createUrl("forum/UpdateComment"); ?>',
success:function(data){
if(data !== null) {
$('#Text_group').val(data);
$('#text-form').submit();
}
},
error: function() {
alert("Error occured!!!.");
},
});
return false;
});
});
</script>
Not exactly sure what the code does, other than call a function as well, but as well, it doesn't work (I also changed POST from GET and back).
Any suggestions? I feel like CActiveForm is to blame here, but even modifying that causes the site to fail in loading pages.
You have a long question and could be you should split your question in more question with simple question each ..
A firts answer the submit button don't contain the target function see this doc
http://www.yiiframework.com/doc/api/1.1/CHtml#submitButton-detail
the target function (php controller/action) is defined in form .. this is from html .. is the form definition that define the target for the submitted data ..
if you want execute the actionGetReport you should define the target in form action
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'comment-form',
'action'=>Yii::app()->createUrl('yourController/actionGetReport'),
'enableAjaxValidation'=>false,
)); ?>

Ajax how to disable div or item

I am new to ajax, is there a way you can help me, how to disable all items once click is successful:
Here is my code for ajax:
if (!parent.hasClass('.disabled')) {
// vote up action
if (action == 'click') {
alert("test");
};
//how do i add disabled function on a particular div
// add disabled class with .item
parent.addClass('.disabled');
};
here is my index:
<?php while($row = mysql_fetch_array($query)): ?>
<div class="item" data-postid="<?php echo $row['recipe_id'] ?>" data-score="<?php echo $row['vote'] ?>">
<div class="vote-span"><!-- voting-->
<div class="vote" data-action="up" title="Vote up">
<i class="icon-chevron-up"></i>
</div><!--vote up-->
<div class="vote-score"><?php echo $row['vote'] ?></div>
</div>
<div class="post"><!-- post data -->
<p><?php echo $row['recipe_title'] ?></p>
</div>
</div><!--item-->
i jst want to disable the loop icon-chevron-up class.not just one but all.
Actually no ajax call needed here. I will only be done by using jquery. See the code
$(document).ready(function(){
$('.item').click(function(){
if (!parent.hasClass('.disabled')) {
parent.addClass('.disabled');
}
});
});
Here you have not mentioned, on what click you need the action, so i consider that on the div contains class='item', the action will be performed. I hope it will help.

Output Text Doesn't Show in Correct Format

Here is the JavaScript I use to animate slider (fade effect) of the content I read from database:
<script language="javascript">
jQuery(document).ready(function ()
{
var terms = ["span_1","span_2"];
var i = 0;
function rotateTerm() {
jQuery("#text-content").fadeOut(200, function() {
jQuery(this).text(jQuery('#text-slider .'+terms[i]).html()+i).fadeIn(200);
});
jQuery("#title-content").fadeOut(200, function() {
jQuery(this).text(jQuery('#title-slider .'+terms[i]).html()+i).fadeIn(200);
i == terms.length - 1 ? i=0 : i++;
});
}
rotateTerm();
setInterval(rotateTerm, 1000);
});
</script>
And here is the PHP code I use:
<?php
if (!empty($testLst)) :
$num=1;
foreach($testLst as $key=>$item):
$item->slug = $item->id;
$item->catslug = $item->catid ;
?><div id="hidden-content" style="display:none;">
<div id="title-slider">
<span class="<?php echo 'span_'.$num; ?>">
<h4><a href="<?php echo JRoute::_(ContentHelperRoute::getArticleRoute($item->id, $item->catid)); ?>">
<?php echo $item->title; ?></a>
</h4>
</span>
</div>
<div id="text-slider">
<span class="<?php echo 'span_'.$num; ?>">
<p>
<?php
$concat=array_slice(explode(' ',$item->introtext),0,20);
$concat=implode(' ',$concat);
echo $concat."...";
?>
</p>
</span>
</div></div>
Learn more >></p>
<?php
$num++;
endforeach;
endif;
?>
<div id="title-content">
</div>
<div id="text-content">
</div>
And here is a JSFiddle page reproducing what I would like to do.
My problem is that I am getting data that still has HTML tags, however I would like the output to have my CSS styles.
You could clone the node, and set that to be the new content of the target elements, to keep everything in jQuery objects, but personally, I'd use the .outerHTML property.
I've updated your fiddle to show you what I mean: I've changed the .text(...set content here) to .html(), because we're injecting HTML content. Then, I added [0] at the end of your selector, to return the raw element reference, which gives access to all standard JS properties and methods an element has, and just went ahead and fetched the outerHTML... easy-peasy

jquery update div background element

Alright not sure what to do and i am honestly bit lost. What I am trying to do is upload a file to site via jQuery and push it to PHP which then deletes original image file and makes a a copy of it called header.jpg and pushes it where it needs to go. That part works with no problem. The problem here is how would I go about updating the div element if the header.jpg image is the background?
Note: no matter what the img will always be header.jpg but it needs to be re-cached by browser and outputed to user without page refresh
Here is how the header div is layed out
<div id="headerEmpty"></div>
<div id="pageName">
<h2><?php echo $pageName; ?></h2>
</div>
<?php if ( $_SESSION['signed_in'] == true ) { ?>
<div id="header" style="background-image:url(uploads/header.jpg);">
<span class="edit" fn="header">
<img src="uploads/icon/16/018.png" />
</span>
<div class="fn_menu" style="display:none;"></div>
</div>
<?php } else { ?>
<div id="header"></div>
<?php } ?>
and here is the jquery bit which displays loader and auto-starts the upload process
$('#photoimg').live('change', function() {
$("#preview").html('');
$("#preview").html('<img src="uploads/icon/16/ajax-loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm(
{
target: '#header',
success : function(data) {
$("#header").html(data).fadeIn('fast');
}
}).submit();
});
When you want to update the image, change it's source. You can append a time-stamp to the source so it will not come from the browser's cache. In PHP that would be something like:
<div id="headerEmpty"></div>
<div id="pageName">
<h2><?php echo $pageName; ?></h2>
</div>
<?php if ( $_SESSION['signed_in'] == true ) { ?>
<div id="header" style="background-image:url(uploads/header.jpg?_=<?php echo time(); ?>);">
<span class="edit" fn="header">
<img src="uploads/icon/16/018.png" />
</span>
<div class="fn_menu" style="display:none;"></div>
</div>
<?php } else { ?>
<div id="header"></div>
<?php } ?>
The time-stamp should just be ignored and the image will be downloaded each update.
Update
Ok, I see now that the background image is on the element you are replacing the HTML of. You could use jQuery to update the url() of the image:
success : function(data) {
var theDate = new Date();
$("#header").css('background-image', 'uploads/header.jpg?_=' + theDate.getTime()).html(data).fadeIn('fast');
}
You could also use PHP to output the #header element and use replaceWith() instead of .html():
success : function(data) {
$("#header").replaceWith(data).fadeIn('fast');
}
This assumes that your PHP output now looks like this:
<div id="header" style="background-image:url(uploads/header.jpg?_=1234567890);">
<span class="edit" fn="header">
<img src="uploads/icon/16/018.png" />
</span>
<div class="fn_menu" style="display:none;"></div>
</div>

Categories