I am using OO php and have the front end page generated through this class, I am trying to reload a button so that once it is pressed it changes class and button all together. Below is the function in which generates the buttons:
public static function printStartStopAll($enabled = 'false')
{
syslog(LOG_INFO, "HELLO");
?>
<div class="big-button-wrapper">
<?
if ( is_combined_server() ) {
// print start all button
$title_text = dgettext('triplecast', "Start All Transfers");
$btn_text = dgettext('triplecast', "Start All");
if ( !Transfer::CanTransferNow() || count(self::getPendingTransfers()) == 0 ) {
$class = "big-green-button-off";
$onclick='';
} else {
$class = "big-green-button";
$onclick = 'onclick=\'startAllTransfers("'.str_replace('"', '\"', self::$txtOpts).'");\'';
}
?>
<div id='start-all' class='<?=$class?>' title='<?=$title_text?>' <?=$onclick?>><?=$btn_text?></div>
<?
}
//Separate out the text for readability.
$title_text = dgettext('triplecast', "Stop Transfers and disable the system till you re-enable it in the configuration menu");
$btn_text = dgettext('triplecast', "Stop All");
$confirm_msg= dgettext('triplecast', 'If you continue all current transfers will be stopped and the system disabled till you re-enable it.');
$confirm = dgettext('triplecast', 'Do you want to stop all transfers?');
?>
<div id='stop-all' class='big-red-button' title='<?=$title_text?>' onclick='stopAllTransfers("<?=$confirm_msg.'\n\n'.$confirm?>", "<?=str_replace('"', '\"', self::$txtOpts)?>");'><?=$btn_text?></div>
<?
syslog(LOG_INFO, "===>".$enabled);
if($enabled != "true") {
$title_text = dgettext('triplecast', "Enable Select");
$btn_text = dgettext('triplecast', "Select");
$class = "big-green-button";
$onclick='onclick=\'enableSelect(true);\'';
?>
<div id='enable_select' class='<?=$class?>' title='<?=$title_text?>' <?=$onclick?>><?=$btn_text?></div>
<?
}
else {
$title_text = dgettext('triplecast', "Stop selected Transfers");
$btn_text = dgettext('triplecast', "Stop Selected");
?>
<div id='stop-select' class='big-red-button' title='<?=$title_text?>' onclick=''><?=$btn_text?></div>
<?
}
?>
</div>
<?
}
Please ignore any syslog :) thats me testing ...
I use ajax to push a variable back to the page and reload this function.
function enableSelect(value)
{
$.getJSON("ajax_requests/enableSelect.php", { enabled: value },
function(data){
});
}
<?php
$requireAuthentication = false;
$requireLicensing = false;
$minimalIncludes = true;
require_once('../Library.php');
header('content-type: application/json');
$enabled = getParameter('enabled');
$dist_server = TriplecastConfig::get('distribution_server');
$resp = new TriplecastMsg();
try {
TransferController::setSelectEnabled($enabled);
TransferController::printStartStopAll($enabled);
} catch (Exception $e) {
$resp->setCode(STATUS_ERROR);
$resp->setMessage($e->getMessage());
}
$json = new JSON();
echo $json->encode( array("code" => $resp->getCode(), "message" => $resp->getMessage())
);
?>
I understand that the code is messy, im just trying to figure out how to do this properly.
The aim of this is to enable the user to press this button and for it to reload the button with the stop-selected class (big-red-button)
Any help will be gratefully appreciated
Related
I'm new to coding and I'm trying to create a simple project which is a BMI calculator. Every time I hit the 'calculate' button the page posts the data with the DIV element for a second then the page refreshes.
Here's my code from controller:
<?php
class Cal extends BaseController
{
protected $helpers = ['url', 'form', 'text', 'html'];
public function calc(){
return view('calc');
}
public function calculator(){
$bmi = new BMI();
$height = $this->request->getPost('height');
$weight = $this->request->getPost('weight');
$bmicalc = $weight/($height*$height);
$result;
if($bmicalc <= 18.5){
$result = "Underweight";
}elseif($bmicalc > 18.5 AND $bmicalc<=24.9){
$result = "Normal weight";
}elseif($bmicalc > 24.9 AND $bmicalc<=29.9){
$result = "Overweight";
}elseif($bmicalc > 30.0){
$result = "OBESE";
}elseif($bmicalc > 31.0){
$result = "OBESE 2";
}
$bmiInsert = array(
'weight' => $this->request->getPost('weight'),
'height' => $this->request->getPost('height'),
'res' => $result,
);
$data = [
'res' => $result,
];
$bmi->insert($bmiInsert);
return view('calc', $data);
}
}
Here's my code for my view page:
<div class="try">
<?php
if(isset($res[0]))
echo "Your BMI is ", "$res";
?>
</div>
Now here's the script that I've tried already:
$(".btn-check").click(function() {
$('form').submit(function() {
$(".try").css('display', 'block');
event.preventDefault();
});
});
I've also tried changing the button type into "button" instead of "submit" but still no avail.
You need to pass event as an function parameter to submit to prevent default behaviour
$(".btn-check").click(function() {
$('form').submit(function(event) {
$(".try").css('display', 'block');
event.preventDefault();
});
});
I'm trying to make a notification to my simple php/js chat:
First, I'm trying to compare my log.html (which containing the messages):
my original post.php ( //jQuery request. It posts the client's input and data being sent to the post.php file each time the user submits the form and sends a new message.) The. post.php is saving the messages into log.html file.
<?php
session_start();
if(isset($_SESSION['name'])){
$text = $_POST['text'];
$text_message = "<div class='msgln'><span class='chat-time'>".date("F j, g:i A")."</span> <b class='user-name'>".$_SESSION['name']."</b> ".stripslashes(htmlspecialchars($text))."<br></div>";
file_put_contents("log.html", $text_message, FILE_APPEND | LOCK_EX);
}
?>
my edited post.php (trying to set up a function, which is checking the "new" message - comparing with old ones).
<?php
session_start();
if(isset($_SESSION['name'])){
$text = $_POST['text'];
$text_message = "<div class='msgln'><span class='chat-time'>".date("F j, g:i A")."</span> <b class='user-name'>".$_SESSION['name']."</b> ".stripslashes(htmlspecialchars($text))."<br></div>";
// Check if content is different
function text_check(){
$ah = fopen("log.html", 'rb');
$aha = preg_match(fread($ah, 8192), $text_message);
$result = true;
while(!feof($ah)) {
if( $aha === false){
$result = false;
break;
}
}
fclose($ah);
return $result;
}
file_put_contents("log.html", $text_message, FILE_APPEND | LOCK_EX);
}
?>
If post.php function "text_check()" return true in my index.php:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
function checkUpdate()
{
$.post("post.php", function(text_check){
if (text_check.toString()=="true") {
playSound();
}
});
}
function playSound()
{
var audio = new Audio('my_audio');
audio.play();
}
Is it a OK conception?
And how can I make an "orang-red blinking" notification, when browser is minimized?
I read something about title - have to change it. Will it work, if I change it every second with JS?
this is probably very simple but im really new to php and js
i made a comment system for my site but i have an issue that i cant figure out
//comment section
$commentsArray = array();
$commentQuery_run = mysqli_query($con, "SELECT * FROM comments WHERE PostID='$userPostId'");
if (mysqli_num_rows($commentQuery_run) > 0) {
echo "<b id='commcount'>Comments:".mysqli_num_rows($commentQuery_run).
"</b>";
while ($commentRow = mysqli_fetch_assoc($commentQuery_run)) {
$commentID = $commentRow['id'];
$commentUsername = $commentRow['username'];
$commentUserPfpPath = $commentRow['path'];
$commentContent = $commentRow['text'];
$commentDate = $commentRow['date'];
$commentsArray[] = $commentContent;
echo "html for displaying the comments";
}
} else {
echo "<b id='commcount'>No comments! Be the first one to comment!</b>";
}
if ($isLoggedIn === true) {
echo "<form id='commForm' method='POST' action=''> <
input id = 'commTextInp'
type = 'text'
placeholder = 'Your comment...'
name = 'commentText' > < br >
<
input id = 'commSubmInp'
type = 'submit'
name = 'commentSubmit'
value = 'Post Comment' >
<
/form>";
} else {
echo "<b id='commcount'>Please Login In to comment!</b>";
}
//comment section
//coment process
if (isset($_POST['commentSubmit'])) {
if (isset($_POST['commentText']) && !empty($_POST['commentText'])) {
$postCommentUsername = $_SESSION['username'];
$postCommentPfpImg = $_SESSION['pfpimg'];
$postCommentContents = mysqli_real_escape_string($con, htmlentities($_POST['commentText'], ENT_QUOTES));
$postCommentDate = date("d/m/Y H:i");
if (!in_array($postCommentContents, $commentsArray)) {
$postCommentQuery_run = mysqli_query($con, "INSERT INTO comments VALUES('','$userPostId','$postCommentUsername','$postCommentPfpImg','$postCommentContents','$postCommentDate')");
if ($postCommentQuery_run === true) {
echo "<script> window.location.reload() </script>";
} else {
echo "<b style='color:red;'>Error while submitting comment!</b>";
}
} else {
echo "<b style='color:red;'>Please don't repeat yourself/other users!</b>";
}
} else {
echo "<b style='color:red;'>Please write something in your comment and try again</b>";
}
}
echo "</center>";
//comment process
every time i submit the form i get the "please dont repeat yourself/other users" error. why? does the window.location.reload() function also re-submit the form? or im I doing something completely wrong? and is there any better method for reloading the site? as it might be obvious i need to reload the page so that the new comment shows up. again, im really new to php/js/html so please explain why my code isnt working the way its supposed to. my guess is that the reload() method resubmits the form (excuse my bad english)
You better should place your POST-processing code in header of file, and you will be able to use header() redirect. To show error, you can use some flag; see:
// here we store all our comments
$commentsArray = [];
$commentQuery_run = mysqli_query($con,"SELECT * FROM comments WHERE PostID='$userPostId'");
while($commentRow = mysqli_fetch_assoc($commentQuery_run)){
$commentsArray[] = $commentRow;
}
//coment process
if(isset($_POST['commentSubmit'])){
if(isset($_POST['commentText']) && !empty($_POST['commentText'])){
$postCommentUsername = $_SESSION['username'];
$postCommentPfpImg = $_SESSION['pfpimg'];
$postCommentContents = mysqli_real_escape_string($con, htmlentities($_POST['commentText'], ENT_QUOTES));
$postCommentDate = date("d/m/Y H:i");
if(! array_search($postCommentContents, array_column($commentsArray, 'text')) ){
$postCommentQuery_run = mysqli_query($con,"INSERT INTO comments VALUES('','$userPostId','$postCommentUsername','$postCommentPfpImg','$postCommentContents','$postCommentDate')");
if($postCommentQuery_run === true){
header("Location: " . $_SERVER['PHP_SELF']);
}
else {
$is_error = 'ERROR';
}
}
else{
$is_error = 'DUPLICATE';
}
}
else{
$is_error = 'NO_DATA';
}
}
and next, in the old place (in the middle of page) you can show error:
if(isset($is_error)) {
switch($is_error) {
case 'DUPLICATE':
echo "<b style='color:red;'>Please don't repeat yourself/other users!</b>";
break;
case 'NO_DATA':
echo "<b style='color:red;'>Please write something in your comment and try again</b>";
break;
default:
echo "<b style='color:red;'>Error while submitting comment!</b>";
}
}
// ...........
// PRINT ALL COMMENTS HERE
if(count($commentsArray)>0){
echo "<b id='commcount'>Comments:" . count($commentsArray) . "</b>";
foreach($commentsArray as $comment){
// $comment contains all your db-fields
echo "html for displaying the comments";
}
}
else{
echo "<b id='commcount'>No comments! Be the first one to comment!</b>";
}
every time i submit the form i get the "please dont repeat yourself/other users" error. why?
if(! in_array($postCommentContents, $commentsArray))
for first comment is true because:
if(mysqli_num_rows($commentQuery_run) > 0)
for first comment is false and commentsArray is empty.
i have a small doubt.. i posted my delete.php page coding here.
if(isset($_GET["id"]))
{
$meal_query = mysql_query("DELETE FROM ebmealplans WHERE MealPlanID = '$id'");
echo mysql_error();
$room_query = mysql_query("DELETE FROM ebroomtypes WHERE RoomTypeID = '$id'");
echo mysql_error();
$tariff_query = mysql_query("DELETE FROM ebvouchertariffs WHERE VoucherID_Fk = '$id'");
echo mysql_error();
$query = mysql_query("DELETE FROM ebvouchers WHERE VoucherID = '$id'");
echo mysql_error();
if($query)
{
echo "<script> alert('Voucher deleted successfully'); </script>";
}
else
{
echo "<script> alert('Failed to delete this voucher'); </script>";
}
mysql_close($link);
echo "<script> location.href='managevouchers.php'; </script>";
}
here i am delete some user datas using this php coding. it worked perfectly. i created four separate tables for store the records. if deletion function was successfully completed i want to show the alert message to users "Deleted Successfully". you can see in my coding i'm just show the alert message for only one $query. i tried another method..
if($query)
{
alert function
}
else
{
alert function
}
if($meal_query)
{
alert function
}
else
{
alert function
}
if($room_query)
{
alert function
}
else
{
alert function
}
if($tariff_query)
{
alert function
}
else
{
alert function
}
it show the alert message four times. i know multiple alert functions annoying the users. my question is how to show the single alert message for mysql multiple queries?
Just store the msg pieces in some variable, and alert them all finally.
$msgs = array ();
if ($query) {
$msgs [] = '.....';
} else {
$msgs [] = '...';
}
if ($meal_query) {
$msgs [] = '....';
} else {
$msgs [] = '...';
}
//....
if ($msgs) {
//join the msgs with line break
$alert = join ( "\n", $msgs );
//json encode will make sure it's like "..string..", no quotes problem
echo '<script> alert(', json_encode ( $alert ), '); </script>';
}
I am a beginner in Yii framework. I wanted to have a popup in my createform that links from my other table. The purpose of this is I have a dropbox, If there is no data that is I wanted to pick. I will create first. I want to have a popupbox in my table 1 create.php that will get the create form in my table 2. here is what I started. what seems to be the problem here?
here is my codes for table1 create.php
<?php echo CHtml::link('New Day',"",
array(
'style'=>'cursor:pointer; text-decoration:underline;',
'onClick'=>"{doDay(); $('#dialogDay).dialog('open');}"));?>
<?php
$this->beginWidget('zii.Widgets.jui.CJuiDialog',array(
'id'=>'dialogDay',
'options'=>array(
'title'=>'Add New Day',
'autoOpen'=>false,
'modal'=>true,
'width'=>550,
'height'=>470,
),
));
?>
<div class="divForForm"></div>
<?php $this->endWidget();?>
<script type="text/javascript">
function doDay()
{
<?php echo CHtml::ajax(array(
'url'=>array('day/NewDay'),
'data'=>"js:$(this).serialize()",
'type'=>'post',
'dataType'=>'json',
'success'=>"function(data)
{
if(data.status == 'failure')
{
$('#dialogDay div.divForForm').html(data.div);
$('#dialogDay div.divForForm form').submit(doDay);
}
else
{
window.location.href = ".Yii::app()->getBaseUrl().";
}
}",
))?>
return false;
}
</script>
in my table 2 controller
public function actionNewDay()
{
$model= new Day;
if(isset($_POST['ajax']) && $_POST['ajax']=='day-form')
{
$model->attributes=$_POST['Day'];
echo CActiveForm::validate($model);
Yii::app()->end();
}
if(isset($_POST['Day']))
{
$model->attributes=$_POST['Day'];
$name=$model->name;
$mon=$model->mon;
$tue=$model->tue;
$wed=$model->wed;
$thurs=$model->thurs;
$fri=$model->fri;
$sat=$model->sat;
$sun=$model->sun;
$dayassign = new DayAssign();
if($model->save())
{
$dayassign->varName = $name;
$dayassign->varMon = $mon;
$dayassign->varTue = $tue;
$dayassign->varWed = $wed;
$dayassign->varThurs = $thurs;
$dayassign->varFri = $fri;
$dayassign->varSat = $sat;
$dayassign->varSun = $sun;
if($dayassign->save())
{
if(Yii::app()->request->isAjaxRequest)
{
echo CJSON::encode(array(
'status'=>'success',
));
}
else{
$url = Yii::app()->getBaseUrl();
Yii::app()->getRequest()->redirect($url);
}
}
}
if(Yii::app()->request->isAjaxRequest)
{
echo CJSON::encode(array(
'status'=>'failure',
'div'=>$this->renderPartial('day',array('model'=>$model),true)));
exit;
}
else
$this->render('day',array('model'=>$model,));
}
}
Did it by myself. here is the codes.
Scenario
I have a day model which contains shift eg. Night,Morning that is selected by my EmpSched model. Lets assume that the EmpSched wants to choose the Afternoon Shift but the day model doesnt have afternoon model yet, He will have to create a day first and lose the already inserted input.
We want to allow the user to create the day from the form of the empsche, without changing pages
This is what I done.
in my Day Controller:
public function actionCreate()
{
$model=new Day;
// Uncomment the following line if AJAX validation is needed
//$this->performAjaxValidation($model);
if(isset($_POST['Day']))
{
$model->attributes=$_POST['Day'];
if($model->save())
{
if(Yii::app()->request->isAjaxRequest)
{
echo CJSON::encode(array(
'status'=>'success',
'div'=>"Day successfully added"
));
exit;
}
else
$this->redirect(array('view','id'=>$model->id_day));
}
}
if(Yii::app()->request->isAjaxRequest)
{
echo CJSON::encode(array(
'status'=>'failure',
'div'=>$this->renderPartial('_form',array('model'=>$model),true)));
exit;
}
$this->render('create',array(
'model'=>$model,
));
}
and in my EmpSched _form.php:
</div>
<?php echo CHtml::link('Create day', "", // the link for open the dialog
array(
'style'=>'cursor: pointer; text-decoration: underline;',
'onclick'=>"{addDay(); $('#dialogDay').dialog('open');}"));?>
<?php
$this->beginWidget('zii.widgets.jui.CJuiDialog', array( // the dialog
'id'=>'dialogDay',
'options'=>array(
'title'=>'Create Day',
'autoOpen'=>false,
'modal'=>true,
'width'=>550,
'height'=>470,
),
));?>
<div class="divForForm"></div>
<?php $this->endWidget();?>
<script type="text/javascript">
// here is the magic
function addDay()
{
<?php echo CHtml::ajax(array(
'url'=>array('day/create'),
'data'=> "js:$(this).serialize()",
'type'=>'post',
'dataType'=>'json',
'success'=>"function(data)
{
if (data.status == 'failure')
{
$('#dialogDay div.divForForm').html(data.div);
// Here is the trick: on submit-> once again this function!
$('#dialogDay div.divForForm form').submit(addDay);
}
else
{
$('#dialogDay div.divForForm').html(data.div);
setTimeout(\"$('#dialogDay').dialog('close') \",3000);
}
} ",
))?>
return false;
}
</script>
I hope ill help someone who is on my own boat.