Use PHP to conditionally render a Javascript function call in the browser - javascript

I have a button which successfully triggers a "load more" on click. Once it is clicked, a SESSION variable is set, so that when the user reloads the page, the new posts should appear loaded already, so that the user does not need to click again "load more".
I would thus like to render the same "load more" Javascript function in a PHP IF statement, according if a SESSION or COOKIE is set or not:
<?php
if ((isset($_SESSION['isloaded'])) || (isset($_COOKIE['isloaded']))){
echo '<script>loadmore(\'posts\');</script>';
}
else {
echo 'Load More';
}
?>
However the Javascript does not get triggered once the page is rendered. What am I doing wrong?

As #Austin and #Angry Coder said, check your console for errors.
Also, make sure function loadmore() is defined before it's called. So either place the function declaration above the loadmore('posts'); call or add the call on a onload or something similar.
An other thing, maybe for clearness you can write your code like (but it's an opinion):
<?php if ((isset($_SESSION['isloaded'])) || (isset($_COOKIE['isloaded']))) { ?>
<script>loadmore('posts');</script>
<?php } else { ?>
Load More
<?php } ?>

To have your JavaScript run automatically, you can use the onLoad event, like
<body onload="loadmore('posts')">
...
</body>
or maybe
<body onload="conditionally_loadmore('posts')">
<?php
if ((isset($_SESSION['isloaded'])) || (isset($_COOKIE['isloaded']))){
// Only have the function do something if we really want to.
echo '<script>function conditionally_loadmore(s) {';
echo ' loadmore(s); ';
echo '}</script>';
}
else {
echo '<script>function conditionally_loadmore(s) {';
echo ' // Do nothing. ';
echo '}</script>';
echo 'Load More';
}
?>
or, as #Astaroth suggested:
<body
<?php
if ((isset($_SESSION['isloaded'])) || (isset($_COOKIE['isloaded']))) {
echo 'onload="loadmore(\'posts\')"';
}
?>
>...

Related

Is the function binded to the button always executed or did I make a mistake?

So I have this PHP page, with at the start some unimportant stuff and a session opening :
<?php
session_start();
?>
I want the disconnect button to appear only if the user is already connected, which means that $_SESSION['Pseudo'] is set. If this is the case, I create a button, and bind to that button a function to destroy the session. The problem is, each time I go on this page, the session is destroy, even though it's in a condition.
Here's my code :
<?php
if (isset($_SESSION["pseudo"])) {
echo '<p><button type="button" id="deco">Disconnect</button></p>';
}
?>
<script>
let btn = document.getElementById('deco');
if (btn) {
btn.addEventListener('click', updateBtn);
function updateBtn() {
<?php
session_destroy();
?>
window.location.href = "/"
}
}
</script>
Any clue ?
You cannot combine PHP within Javascript like that.
When you're doing , it's not a part of the Javascript. It's PHP code and is executed as part of the PHP code in the file.
This means that it has nothing to do with the javascript aspect. your updateBtn function is effectively, when the page source code loads:
function updateBtn() { window.location.href = "/" }
What you really want to do is make it so that when someone clicks the button, it takes them to a logout page or a page with a logout query param.
eg.
<?php
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
session_destroy();
echo 'You have successfully logged out!';
}
if (isset($_SESSION["pseudo"])) {
echo '<p><button type="button" id="deco">Disconnect</button></p>';
}
?>
<script>
let btn = document.getElementById('deco');
if (btn) {
btn.addEventListener('click', updateBtn);
function updateBtn() {
window.location.href = "/?action=logout"
}
}
</script>

Why my jQuery show() function in php foreach loop work only for first element

I have the following problem on my wordpress project :
I have 2 div call "div_sc_1" and "div_sc_2" which are hidden on my page.
I want to show them with a jQuery function .show() if they are not "checked". "Checked" status is writen in my db.
With my actual code, If only div_sc_1 or div_sc_2 is not "checked", everything is allright BUT if both of the 2 divs are not checked, only one is displaying and I don't understand why.
This is my code :
foreach($list_id_scores as $scores){
$id_s = $scores->id_score;
$checked = $wpdb->get_var( "SQL query for 'checked' status");
if($checked == "1"){
echo " score n°".$id_s." is over<br />";
}else{
$div_id = "div_sc_".$id_s;
echo $div_id; /// this echo show me that my loop is working
?>
<script>
var div_sc = <?php echo json_encode($div_id); ?>;
jQuery(document).ready(function(){ jQuery("#"+div_sc).show(); });
</script>
<?php
}
}
What is the problem for you ? Thanks for your time
You're defining a global variable div_sc multiple times. All <script> tags share the same scope, so only one value is retained. The .ready() handler only executes after all variables have been defined (and the rest of the page has finished loading), not in between.
It might be better to do this instead:
<script>
jQuery(document).ready(function(){
<?php
foreach($list_id_scores as $scores){
$id_s = $scores->id_score;
$checked = $wpdb->get_var( "SQL query for 'checked' status");
if($checked == "1"){
echo " score n°".$id_s." is over<br />";
}else{
$div_id = "div_sc_".$id_s;
echo $div_id; /// this echo show me that my loop is working
?>
jQuery("#"+<?php echo json_encode($div_id); ?>).show();
<?php
}
}
});
</script>

Show div element after reCaptcha validation

I am using Googles reCaptcha API for form validation.
I have opted to have the submit button show once the validation has been complete by using a little bit of JS.
<?php
if(isset($_POST['Login'])){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = '6LerNA0UAAAAAEReb9rS5JXjtvNSYlMjKiocUv_O';
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if(isset($data->success) AND $data->success==true){
//show submit button
echo '<script type=\"text/javascript\">
function myFunction() {
document.getElementById("logDiv").style.visibility="visible";
}
</script>';
}
else{ // stay hidden
'<script type=\"text/javascript\">
function myFunction() {
document.getElementById("logDiv").style.visibility="hidden";
}
</script>';
}
}
?>
<div id='logDiv' style='visibility:hidden')
<?php
echo $form->add('Login',array('type' => 'submit'));
?>
</div>
Currently, the solution isn't working; when the Captcha is validated the div remains hidden.
Is this a result of a syntax error or have a made a logical error?
What is the bug in my code?
Are there any more robust solutions?
Why not simply use a php condition to show the div? I think your JS isn´t working because you never call myFunction().
Try something like this but it will become complex over time and amount of code:
if(isset($data->success) AND $data->success==true){
$showButton = true;
}
......
if($showButton) { ?>
<div id='logDiv' style='visibility:hidden'
<?php echo $form->add('Login',array('type' => 'submit'));
?> </div> <?php }
......
Or a simple Solution:
if(is_bool($data -> success) && $data -> success){
echo '<div id="logDiv">'.$form->add('Login',array('type' => 'submit')).'</div>';
}
Echo the HTML Elements only if validition was successful otherwise simply dont ouput any HTML for the Div.
Hope this Helps.

Creating a PHP Session using jQuery / JS

On page load, I want to check if a PHP Session variable exists:
If it does, alert() the contents
If it doesn't, create it and save the current time
Here is my code:
$(document).ready(function(){
<?php if(session_id() == '') { session_start(); } ?>
if (!<?php echo isset($_SESSION['lbBegin'])?'true':'false'; ?>) {
<?php $_SESSION['lbBegin'] = date("Y-m-d H:i:s"); ?>
} else {
alert("<?php echo $_SESSION['lbBegin']; ?>")
}
});
This code works in the sense that the first page load doesn't produce an alert() and a refresh shows the time, however every refresh / link click afterwards changes the time. I was expecting the time to stay the same during the entire session.
What have I done wrong?
You need to add session_start() at the very beginning and check if a session variable exists. Do this way:
<?php session_start(); // At the very top! No matter what! ?>
<script>
$(document).ready(function(){
if (!<?php echo isset($_SESSION['lbBegin']) ? 'true' : 'false' ; ?>) {
// And you cannot do the below thing, because, first PHP executes before JS even runs. So, you need to use an AJAX Call for this:
<?php $_SESSION['lbBegin'] = date("Y-m-d H:i:s"); ?>
} else {
alert("<?php echo $_SESSION['lbBegin']; ?>")
}
});
</script>
Correcting the AJAX Bit:
<?php session_start(); // At the very top! No matter what! ?>
<script>
$(document).ready(function(){
if (!<?php echo isset($_SESSION['lbBegin']) ? 'true' : 'false' ; ?>) {
// And you cannot do the below thing, because, first PHP executes before JS even runs. So, you need to use an AJAX Call for this:
$.getScript("setTime.php");
} else {
alert("<?php echo $_SESSION['lbBegin']; ?>")
}
});
</script>
Inside the setTime.php add the code:
<?php $_SESSION['lbBegin'] = date("Y-m-d H:i:s"); ?>

How can I pass the name of the field in form_error ()

It's part of my view. Me need transmit input name in on which i click.
Below is a script that will get the name input after click
<div class="form_hint"><?=form_error('this get value from javascript after click')?></div>
<?php echo form_open("onenews/" . $onenews['id'] . "#signup", $form_reg['main_form']); ?>
<?php echo form_input($form_reg['login'], $this->form_validation->set_value('login')) ?>
<?php echo form_input($form_reg['email'], $this->form_validation->set_value('email')) ?>
<?php echo form_input($form_reg['password']) ?>
<?php echo form_input($form_reg['conf_password']) ?>
<?= MY_Controller:: create_captcha(); ?>
<?php echo form_input($form_reg['captcha']) ?>
<?php echo form_input($form_reg['submit']) ?>
<?php echo form_close(); ?>
</div>
</div>
jq
<script type="text/javascript">
$(function(){
var curInput = '';
$('#form_reg').find('input').on('click', function(){
curInput = $(this).attr("name");
});
})
</script>
Or i must use ajax?
Thanks!
Your question is not clear at all, but I assume you want to dynamically change the content of the form_hint div. You can't do that with PHP. Once PHP renders the page, it shuts down and does nothing more. So the only way to make PHP show that message is after the form submit, but then you lose your click data. There is a way to save the clicked element in a session for example, but that would be a really bad solution.
So the best solution would probably be to list all the hints in a JavaScript variable, and call the appropriate one upon the click event, and fill the form_hint div with it.
$('.form_hint').text(yourAppropriateMessageHere);
An example with a hidden div for the login input field with exactly how you described would be:
<div class="form_text_login"><?=form_error('login')?></div>
JS
var loginMessage = $('.form_text_login').text();
// list others here
// then make a tree with switch/case or if/else
if (curInput == 'login') {
$('.form_hint').text(loginMessage);
}
else if (curInput == 'email') {
// do the same with the email message, etc.
}

Categories