Wondering how to add in js script a three more !== or statements. The following script was provided as a spectacular answer by jsfriend00 but the problem is I made the mistake of not mentioning there's three more textareas unaccounted for. I'm stuck with the javascript on the remaining or !== conditions. In the following script how to take say !== to each of the following var obj?
//VIEW FILE for private networking stream between admin and clientele:
<?php if(!defined('BASEPATH')) exit('No direct script access allowed'); ?>
<html>
<title>Chat</title>
<head>
<?php echo smiley_js(); ?>
</head>
<body>
<?php echo form_open('controller/function');?>
Reload chat<?php echo form_submit('reload','reload chat');?>
<?php echo form_close();?>
<?php if(isset($user_query)): foreach($user_query->result() as $row):?>
<p>Created at: <?php echo $row->created_at; ?> </p>
<p>Updated at: <?php echo $row->updated_at; ?> </p>
<p><label for="update"> <?php echo $username_sess.' said'?>:<span class="optional"></span></label>
<textarea name="update" id="update" rows="7" cols="30"><?php echo $row->clt_rep_stream ?></textarea>
<?php echo form_open('controller/function');?>
<?php echo form_hidden('user_id',$row->user_id) ?>
<p><label for="adm_update">reply to client:<span class="optional"></span></label>
<textarea name="adm_update" id="adm_update" rows="7" cols="30"> </textarea>
<?php echo form_error('adm_update'); ?>
</p>
<?php echo form_submit('submit','reply');?>
<?php echo form_close();?>
<?php echo form_open('controller/function'); ?>
<?php echo form_hidden('user_id',$row->user_id) ?>
<p>Replied at: <?php echo $row->adm_created_at; ?> </p>
<p>Updated at: <?php echo $row->adm_updated_at; ?> </p>
<p><label for="reupdate"> <?php echo $username_adm_sess.' replied:'?><span class="optional"></span></label>
<textarea name="reupdate" id="reupdate" rows="7" cols="30"><?php echo $row->adm_rep_stream ?> </textarea>
<p>
<?php echo form_submit( 'submit', 'update reply'); ?>
</p>
<?php echo form_close(); ?>
<?php endforeach; ?>
<?php endif; ?>
<script>
function autoRefresh(refreshPeriod) {
var obj = document.getElementById("create");
var obj_two = document.getElementById("update");
var obj_three = document.getElementById("delete");
var obj_four = document.getElementById("reload");
function refreshIfSafe() {
if (document.activeElement !== obj) {
window.location.reload();
} else {
setTimeout(refreshIfSafe, refreshPeriod);
}
}
setTimeout(refreshIfSafe, refreshPeriod);
}
autoRefresh(2 * 1000);
</script>
</body>
</html>
I tried the following but didn't work:
if(document.activeElement !==(obj || obj_two))
I tried the following after Brad's post which partially worked but any update or replies after the first two and the following js is rendered null and void which is really confusing:
if(document.activeElement !== obj && document.activeElement !== obj_two)
Each condition is separate. Treat it as such.
(document.activeElement !== obj) && (document.activeElement !== obj_two) && ...
You could also do this in a loop if your elements weren't explicitly called out like they are, but I don't know how this would fit in your code, as I don't know what your actual code looks like.
Untested, but should work:
<script>
function autoRefresh(refreshPeriod) {
var elementArray = [
document.getElementById("create"),
document.getElementById("update"),
document.getElementById("delete"),
document.getElementById("reload")
];
function refreshIfSafe() {
if (elementArray.indexOf(document.activeElement) !== -1) {
window.location.reload();
} else {
setTimeout(refreshIfSafe, refreshPeriod);
}
}
setTimeout(refreshIfSafe, refreshPeriod);
}
autoRefresh(2 * 1000);
</script>
Or
<script>
function autoRefresh(refreshPeriod) {
var elementArray = ["create", "update", "delete", "reload"];
function refreshIfSafe() {
if (document.activeElement && elementArray.indexOf(document.activeElement.id) !== -1) {
window.location.reload();
} else {
setTimeout(refreshIfSafe, refreshPeriod);
}
}
setTimeout(refreshIfSafe, refreshPeriod);
}
autoRefresh(2 * 1000);
</script>
You can try ... no don't !
if(!(document.activeElement in [obj,obj_two])){
// ...
}
By the way, when comparing objects, you actually compare their references adress in memory ... so '!=' is enough.
Related
Basically, I want to add an additional class when a certain IF condition is met.
<?php
if($type == 'NEW')
{
$('#'+day+s).addClass('new');
}
if($type == 'USED')
{
$('#'+day+s).addClass('used');
}
?>
You would need to do it through JavaScript / jQuery inside of a PHP conditional.
You can either close your PHP tags while leaving the conditional open:
<?php
if($type == 'NEW')
{
?>
<script>$('#'+day+s).addClass('new');</script>
<?php
}
if($type == 'USED')
{
?>
<script>$('#'+day+s).addClass('used');</script>
<?php
}
?>
Or echo() out the <script> tags from within PHP:
<?php
if($type == 'NEW')
{
echo "<script>$('#'+day+s).addClass('new');</script>";
}
if($type == 'USED')
{
echo "<script>$('#'+day+s).addClass('used');</script>";
}
?>
Having said that, you'd be better off simply altering your logic to output classes based on your conditionals. That way you would simply need to add a regular CSS rule for each class. The right rule would be selected based on which class was outputted.
It should be directly in your HTML :
<div class="<?php if ($type == 'NEW') echo 'new';?>"></div>
You have to assign your calss name in a variable and simply give that to your corresponding MHTL.
<?php
if($type == 'NEW')
{
$style = "class_name for if"; //eg:- new
}
if($type == 'USED')
{
$style = "class_name for else"; //eg:- used
}
?>
//html element
for eg:
<p id="days" class="<?php echo $style;?>"></p>
several ways to do that and depends also in your code
<!-- Assignment inline -->
<div class="<?= $type === 'NEW' ? 'newClass' : 'usedClass'?>"></div>
<!-- Assignment previous -->
<?php
$class = 'defaultClass';
if ($type === 'NEW') { $class = 'newClass'; }
if ($type === 'USED') { $class = 'usedClass'; }
?>
<div class="<?=$class?>"></div>
<!-- Assignment in script -->
<?php $class = $type === 'NEW' ? 'newClass' : 'usedClass'; ?>
<script>
$(document).ready(function(){
$('#'+day+s).addClass('<?= $class ?>');
});
</script>
You can put the if condition of PHP inside class attribute directly. No need to do any method or js for this. You can use the logic as below:
<div class="<?php if($type == 'NEW'){ echo 'new';} else if($type == 'USED'){ echo 'used'; } ?>"></div>
I written code below that will extract the js like this:
src="assets/js/jquery.min.js"
src="assets/smooth-scroll/smooth-scroll.js"
I would like to have it like: (I guess my regex is wrong):
<script src="assets/js/jquery.min.js"></script>
<script src="assets/smooth-scroll/smooth-scroll.js"></script>
Here is my code:
$htmlData = file_get_contents($url);
if ($htmlData === false) {
echo "error!!";// Handle the error
die();
}
preg_match_all("/\<script(.*?)?\>(.|\\n)*?\<\/script\>/i", $htmlData, $matches);
//example output #1
echo "<pre>";
echo print_r($matches[1]);
echo "</pre>";
//example output #2
$matches = $matches[1];
foreach ($matches as $val) {
//echo "<script";
echo $val;
//echo "</script>"; //<-- adding <script> tags breaks this code
}
So how would I add all scripts into a textarea from this point?
Not sure the regex for styles to do the same.
You need to include the script part in the captured segment.
preg_match_all("/(\<script(.*?)?\>(?:.|\\n)*?\<\/script\>)/i", $htmlData, $matches);
Ok I figured out my code:
$htmlData = file_get_contents($wurl);
if ($htmlData === false) {
echo "error!!";// Handle the error
die();
}
preg_match_all("/(\<script(.*?)?\>(?:.|\\n)*?\<\/script\>)/i", $htmlData, $scripts);
preg_match_all('/<link(.*?)?\>/is', $htmlData, $styles);
//$scripts.=implode(" ",$matches[2]);
//Print array for scripts to get array level;
echo "<pre>";
print_r($scripts[2]);
echo "</pre>";
//Print array for styles to get array level;
echo "<pre>";
print_r($styles[1]);
echo "</pre>";
$scripts = $scripts[2];
foreach ($scripts as $script) {
$all_scripts.= "%script ".$script."#%/scripts#"."\n";
}
$styles = $styles[1];
foreach ($styles as $style) {
$all_styles.= "%link ".$style."#"."\n";
}
$all_scripts = str_replace(array('%', '#'), array(htmlentities('<'), htmlentities('>')), $all_scripts);
$all_styles = str_replace(array('%', '#'), array(htmlentities('<'), htmlentities('>')), $all_styles);
echo "<p>My Scripts:<br/>";
echo $all_scripts;
echo "</p>";
echo "<p>My Styles:<br/>";
echo $all_styles;
echo "</p>";
?>
<textarea name="my_Styles" rows="8" cols="100">
<?php echo $all_styles; ?>
</textarea>
<textarea name="my_Scripts"rows="8" cols="100">
<?php echo $all_scripts; ?>
</textarea>
Hello my problem is simple , i have a table news , i have a button bt1 , and a div to show the results , i want to display all rows from table when i click the button,i only get the first row , how can i display all results ?
<script>
function shownews(id) { <? php
include('db.php');
$query = mysql_query("SELECT * FROM news");
while ($row = mysql_fetch_array($query)) {
$a = $row['news_title'];
} ?>
var ab = <? php echo json_encode($a); ?> ;
id.innerHTML = ab;
}
</script>
<div id="results"></div>
<button id="btn1" onclick="shownews(results)">See news</button>
try
$a = array();
while ($row = mysql_fetch_array($query)) {
$a[] = $row['news_title'];
} ?>
// print array
print_r($a);
Your echo json_encode($a); is not in your while loop, so you only render 1 line.
Also if i understand what you're doing, you want your PHP to be executed only when you trigger your button click ? This is not the way to do it... php is a server language where javascript is executed only by your browser.
I didn't
Try this :
<script type="text/javascript">
function shownews(id) {
document.getElementById(id).innerHTML = document.getElementById('news').innerHTML ;
}
</script>
<div id="news" style="display:none ;">
<?php
include ('db.php');
$query=mysql_query("SELECT * FROM news");
while($row=mysql_fetch_array($query)){
echo $row['news_title'] . '<br />' ;
}
?>
</div>
<div id="results"></div>
<button id="btn1" onclick="shownews('results')">See news</button>
You are overwriting $a, hence you will only get the last row.
Change
while($row=mysql_fetch_array($query)){
$a=$row['news_title'];
}
to
$a = array();
while($row=mysql_fetch_array($query)){
array_push($a, $row['news_title']);
}
Edit: Royal_bg is correct - extra info:
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function. http://us2.php.net/array_push
You execute all the while before writing anything. Try to change the closing bracket after writing the answer...
<script>
function shownews(id){
<?php
include ('db.php');
$query=mysql_query("SELECT * FROM news");
while($row=mysql_fetch_array($query)){
$a=$row['news_title'];
?>
var ab = <?php echo $a; ?>;
id.innerHTML += ab;
<?php
}
?>
}
</script>
<div id="results"></div>
<button id="btn1" onclick="shownews(results)">See news</button>
function shownews(id){
<?php
include ('db.php');
$query=mysql_query("SELECT * FROM news");
while($row=mysql_fetch_array($query)){
$a[]=$row['news_title'];
}
?>
id.innerHTML=<?php echo json_encode($a); ?>;
}
I was thrown some code and I'm trying to edit the log-in functionality but I'm having trouble locating where the actual login is going. The login url at the address bar states that it's in site/index.php but when I check that page, the codes there are completely irrelevant so I found the "login.php" page that points towards the _login.php as a view.
Here is the code for login.php:
<?php
require 'facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'secret',
'secret' => 'secret',
'cookie' => true,
));
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
// login or logout url will be needed depending on current user state.
if ($me) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
// This call will always work since we are fetching public data.
$naitik = $facebook->api('/naitik');
?>
<?php
$this->pageTitle=Yii::app()->name . ' - Login';
$this->breadcrumbs=array(
'Login',
);
?>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $facebook->getAppId(); ?>',
session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// whenever the user logs in, we refresh the page
FB.Event.subscribe('auth.login', function() {
window.location.reload();
});
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
<div style="float:left;"><?php echo $msg ?></div>
<div style="clear:both;"></div>
<div id="form_login" class="form">
<h1>Login</h1>
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
?>
<div class="row">
<?php //echo $form->labelEx($model,'username'); ?>
<?php //echo $form->textField($model,'username'); ?>
<?php //echo $form->error($model,'username'); ?>
<?php echo $form->labelEx($model,'first_name'); ?>
<?php echo $form->textField($model,'first_name'); ?>
<?php echo $form->error($model,'first_name'); ?>
<?php echo $form->labelEx($model,'last_name'); ?>
<?php echo $form->textField($model,'last_name'); ?>
<?php echo $form->error($model,'last_name'); ?>
<?php echo $form->labelEx($model,'password'); ?>
<?php echo $form->passwordField($model,'password'); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<div class="row rememberMe">
<?php echo $form->checkBox($model,'rememberMe'); ?>
<?php echo $form->label($model,'rememberMe'); ?>
<?php echo $form->error($model,'rememberMe'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Login',array('id'=>'submit_button'));
?>
<a href="<?php echo Yii::app()->getBaseUrl(); ?>/index.php/persons/create">
<?php echo CHtml::button('Sign Up',array('id'=>'submit_button')); ?>
</a>
</div>
<?php $this->endWidget(); ?>
</div>
<!-- form -->
Then I went on to check the _login.php and this is what I found and I think this is where the actual login happens:
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'login-form'.$box,
'enableClientValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
),
));
?>
<?php
if($model->hasErrors()){
//$nameErrMsg = $model->getError('first_name').'\n';
$nameErrMsg = $model->getError('email').'\n';
$unameErrMsg = $model->getError('username').'\n';
$passErrMsg = $model->getError('password');
//$err = $nameErrMsg.$unameErrMsg.$passErrMsg;
$err = $nameErrMsg.$passErrMsg;
?>
<script>alert("<?=$err?>");</script>
<?php } ?>
<?php //echo $form->textField($model,'first_name',
//array('id'=>'fname'.$box, 'class'=>'login_typebox','placeholder'=>'FIRST NAME','title'=>ucfirst(strtolower(strip_tags($form->error($model, 'first_name')))))); ?>
<?php echo $form->textField($model,'email',
array('id'=>'email'.$box, 'class'=>'login_typebox','placeholder'=>'EMAIL','title'=>ucfirst(strtolower(strip_tags($form->error($model, 'email')))))); ?>
<?php //echo $form->textField($model,'last_name',
//array('id'=>'lname'.$box, 'class'=>'login_typebox','placeholder'=>'LAST NAME','title'=>ucfirst(strtolower(strip_tags($form->error($model, 'last_name')))))); ?>
<?php echo $form->passwordField($model,'password',
array('id'=>'pword'.$box, 'class'=>'login_typebox','placeholder'=>'PASSWORD','title'=>ucfirst(strtolower(strip_tags($form->error($model, 'password')))))); ?>
<input type="hidden" name="box" value="<?php echo $box ?>">
<input type="submit" class="login_submitbtn" style="font-family: 'AsapRegular', Helvetica, sans-serif;color: #FFF;font-size: 14px;padding: 5px 0;border-radius: 5px;border: 1px solid #d0e7ef;background-color: #67b3cf;" name="LOG IN" value="LOG IN"/>
<?php $this->endWidget(); ?>
<div class="login_note_box">
<p><a target="_blank" href="<?php echo Yii::app()->createUrl('register')?>">Not yet a member?</a></p>
<p><a target="_blank" href="<?php echo Yii::app()->createUrl('user/forgot')?>">Forgot password?</a></p>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('input').placeholder();
$('#login-form<?php echo $box?> input.login_typebox').each(function(i,e){
$(this).keydown(function(){
$(this).removeClass('error').attr('title', '');
});
});
$('#login-form<?php echo $box?>').submit(function(){
var email = $("#email<?php echo $box?>").val();
// var fname = $("#fname<?php echo $box?>").val();
// var lname = $("#lname<?php echo $box?>").val();
var pword = $("#pword<?php echo $box?>").val();
//if(fname == '' && lname == "" && pword == "") {
if(email == "" && pword == "") {
alert('Please input your Email and Password');
//alert('Please input your First Name, Last Name, and Password');
$('#login-form<?php echo $box?> input.login_typebox').each(function(i,e){
//$(this).keydown(function(){
//$(this).addClass('error').attr('title', 'Please input your First Name, Last Name, and Password');
$(this).addClass('error').attr('title', 'Please input your Email and Password');
//})
});
return false;
}
var $data = $(this).serialize();
$.ajax({
url : $(this).attr('action'),
data : $data,
type : 'POST',
beforeSend : function(){
$("#login-form<?php echo $box?> .login_submitbtn").addClass("loading");
},
success : function($return){
try{
$arr = $.parseJSON($return);
if($arr.status == 'success'){
location = $arr.url;
}
}catch(e){
$('.loginform').html($return);
}
},
complete : function(){
//$(".login_submitbtn").removeClass("loading");
}
});
return false;
});
$('#login-form<?php echo $box?> input.error').each(function(i,e){
$(this).keydown(function(){
$(this).removeClass('error').attr('title','');
})
});
});
LoginForm.php in the models folder is used along with UserIdentity.php which is in the components folder are the basis of the login process. That is the basis of a Yii login, how a facebook specific login works in conjunction with these is a different matter.
I am trying to execute a simple javascript file with if and else in php. So far it is working but i have an issue.. See the example bellow.
<?
$varone = "Popup One";
$vartwo = "Popup Two";
if ($_GET['myrequest'] == "")
{
echo <<<html
<script>
alert($varone);
</script>
html;
}else{
echo <<<html
<script>
alert($vartwo);
</script>
html;
}
?>
So i want to pass my php variables inside each alert! Or is there any other simply way to execute my javascript and pass my php variables in javascript?
Thank you!!!
Try
<?php
$varone = "Popup One";
$vartwo = "Popup Two";
if ($_GET['myrequest'] == "")
{
echo " <script>
alert('".$varone."');
</script>";
}else{
echo "<script>
alert('".$vartwo."');
</script> ";
}
?>
To Keep separate your JavaScript and PHP try this
<?php
$varone = "Popup One";
$vartwo = "Popup Two";
if ($_GET ['myrequest'] == "") {
?>
<script>
alert('<?php echo $varone; ?>');
</script>
<?php
} else {
?>
<script>
alert('<?php echo $vartwo; ?>');
</script>
<?php
}
?>
I think you are just missing quotes around your variables inside the alerts.
Try this:
<?
$varone = "Popup One";
$vartwo = "Popup Two";
if ($_GET['myrequest'] == "")
{
echo <<<html
<script>
alert('$varone');
</script>
html;
} else {
echo <<<html
<script>
alert('$vartwo');
</script>
html;
}
?>
You may have spotted this javascript error if you had looked in your browser's javascript console, which is very helpful for debugging. Google for how to open the javascript console in whichever web browser you use.
i don't know what you're trying to achieve but i think that if you want to pass some var from php to js the best approach would be use $.ajax , but this depend on what your trying to do or in this case maybe something like this should do the tricks.
<?php
if($_GET['myrequest'] == ""){
$alertVar = "popupone";
}
else{
$alertVar = "popuptwo";
}
?>
<script>
alert('<?php echo $alertVar ?>');
</script>
You have few choices as seen in the answers.
<?php
$varone = "Popup One";
$vartwo = "Popup Two";
?>
<script>
<?php if ($_GET['myrequest'] == ""):?>
alert('<?php echo $varone; ?>');
<?php else: ?>
alert('<?php echo $vartwo; ?>');
<?php endif; ?>
</script>