Yii: run a function when a submitButton is pressed - php

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,
)); ?>

Related

How to fix jquery ajax not sending data to PHP file

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']

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.

How to get name of selected option and sent it to other php script?

This is my jQuery code
<script>
$(document).ready(function() {
$('#countries').change(function(){
$('#countriesForm').submit();
});
});
</script>
and my php code looks like this
<form action="<?php echo $this->createUrl($this->id."/".$this->action->id); ?>" id="countriesForm" method='POST'>
<?php echo CHtml::dropDownList('countries', $select = array(),
CHtml::listData($countries, 'code', 'name'));
?>
<form>
<div class='description'></div>
Can someone pls help me how to get echo/print name or code of the selected country into the div .description.
And how to send the selected code to other php script.
It can be like
<div class='description'><?php
if( isset($_POST['countries']) ) {
echo CHtml::encode($_POST['countries']);
}
?></div>
<?php
$controller = Yii::app()->controller->id;
$action = Yii::app()->controller->action->id;
?>
Using this, you get the controller and action performed.
<li <?php
if ($controller=="site"&&$action=="index"){
echo 'class="active"'; } ?> >
<?php echo CHtml::link('Home',array('site/index')); ?>
</li>

Confirm box in CodeIgniter anchor link to delete record

I am using the following code to delete a record from a database. But I am facing a problem: when I click on "cancel" in the confirm box then it deletes the record. If I click cancel it returns false but how does it delete the record?
What am doing wrong?
Javascript code:
function ConfirmDialog() {
var x=confirm("Are you sure to delete record?")
if (x) {
return true;
} else {
return false;
}
}
PHP code in view:
<?php
echo anchor('user/deleteuser/'.$row->id, 'Delete', array('class'=>'delete', 'onclick'=>"return ConfirmDialog();"));
?>
Everything in one line
<?=anchor("user/deleteuser/".$row->id,"Delete",array('onclick' => "return confirm('Do you want delete this record')"))?>
Try This:
Delete
and use this in your script:
<script type="text/javascript">
var url="<?php echo base_url();?>";
function delete(id){
var r=confirm("Do you want to delete this?")
if (r==true)
window.location = url+"user/deleteuser/"+id;
else
return false;
}
</script>
Are you getting any Javascript errors in the console? I suspect that some other Javascript may be interfering. This simple test page works fine:
<?php echo anchor('user/deleteuser/'.$row->id, 'Delete', array('class'=>'delete', 'onclick'=>"return confirmDialog();")); ?>
<script>
function confirmDialog() {
return confirm("Are you sure you want to delete this record?")
}
</script>
In your View:
<?= anchor("admin/delete_article/{$article->id}", 'Test', ['name'=>'submit', 'value'=>'Delete', 'class'=>'btn btn-danger', 'onclick'=>'return confirm()']);
?>
OR
<?=
form_open('admin/delete_article'),
form_hidden('article_id', $article->id),
form_submit(['name'=>'submit', 'value'=>'Delete', 'class'=>'btn btn-danger', 'onclick'=>'return confirm()']),
form_close();
?>
JavaScript in your View:
<script>
function confirm(){
job=confirm("Are you sure to delete permanently?");
if(job!=true){
return false;
}
}
</script>
See webGautam answer Here
I use This in my code
<a href='<?php site_url('controler/function/$id');?>' onClick='javascript:return confirm(\"Are you sure to Delete?\")'>Delete</a>
Try this
Delete
Then your function will be like:
function isconfirm(url_val){
alert(url_val);
if(confirm('Are you sure you wanna delete this ?') == false)
{
return false;
}
else
{
location.href=url_val;
}
<?=
form_open('admin/delete_noti'),
form_hidden('noti_id',$notification->id),
form_submit('submit','Delete',array('onclick' => "return confirm('Do you want delete this record')",'class'=>'btn btn-danger float-center')),
form_close();
?>
This is the deletion code. first of all we open form admin is our controller name and delete_noti is the function inside admin controller. We are sending id as hidden form. Here $notification is the variable which is passed through method which is available in controller.
Finally, if you want javascript confirm: so when the user clicks, it asks to confirm and then goes to delete if the user clicks okay. You're asking confirmation when the row has already been deleted.
In View Page :-
<td>DELETE</td>
Controller Code:-
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class user extends CI_Controller {
public function deleteuser($userid)
{
$this->db->delete('user', array('user_id'=>$userid));
$this->session->set_flashdata('success','User deleted Successfully!!!');
redirect(base_url().'admin/user');
}
}
?>
Then Show Success Message on View:-
<div class="row col-md-12">
<?php
if($this->session->flashdata('success')){
?>
<div class="alert alert-success " style="display:none;">
<?php echo $this->session->flashdata('success'); ?>
<?php
} else if($this->session->flashdata('error')){
?>
<div class = "alert alert-danger" style="display:none;">
<?php echo $this->session->flashdata('error'); ?>
</div>
<?php } ?>
</div></div>

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

Categories