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"); ?>
Related
I have the following problem, the following script sends a keyword a PHP file hosted in another domain (I already added the CROS headers), this PHP returns me some "echos of different variables" (title, thumbnail, url, etc.) And it works but randomly returns me "Undefined variables".
The first thing was to add an if (isset ()) to my variables in PHP and the error does not appear anymore but the results returned by my searches are much smaller (Before adding it averaged 10 to 20 results, Now I get 5 results).
Can this be a problem with my script?
My form.php
<form method="POST" action="" id="form-busqueda">
<input type="text" name="keyword">
<button id="search" name="search">Search</search>
<div id="results"></div>
<script>
jQuery(function($){
var pluginUrl = '<?php echo plugin_dir_url( __FILE__ ); ?>' ;
$('[id^="form-busqueda"]').on('submit', function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
url : 'http://localhost/ladoserver/script.php',
data : $(this).serialize(),
beforeSend: function(){
$('#results').html('<img src="'+pluginUrl+'../../assets/img/loading.gif" />');
}
}).done(function(data) {
$('#results').html(data);
});
});
});
</script>
</form>
My script.php (dlPage is a function that create cURL connection):
<?php
if (isset($_POST['keyword'])) {
$search = $_POST['keyword'];
$html = dlPage("http://example.com/" . $search);
//where I search and get with simple_html_dom example:
$video = $videos->find('div.example2>a', 0);
$title = $video->innertext;
$url = $video->attr['href'];
$id = $video->attr['id'];
$thumbnail = $video->find('div.thumb', 0)->innertext;
echo $title;
echo $url;
echo $id;
echo $thumbnail[0];
}
?>
I've updated my code, I didn't put all the code because I thought that it isn't relevant, my script.php works fine with pure PHP. The problem appear when I use AJAX.
I'm getting the following error:
Notice: Undefined variable: title in C:\xampp\htdocs\webs\ladoserver\script.php on line 13
Notice: Undefined variable: title in C:\xampp\htdocs\webs\ladoserver\script.php on line 13
Notice: Undefined variable: url in C:\xampp\htdocs\webs\ladoserver\script.php on line 14
The undefined variable is coming from your PHP file (/ladoserver/script.php).
What generates the variables being returned? The most common "cause" of this, is by only setting the variables within a block of code that might not be executed (eg within an if block, or in a loop that iterates 0 times)
You could get around the error (assuming you're okay with blank values) by defining each of the variables at the top of your script.
<?php
$title = "";
$thumbnail = "";
$url = "";
$id = "";
?>
Edit: #snip1377 reminded me that you can also just use isset at the end of your script before the output as well.
Here's some sample code for your $thumbnail variable, which you could apply to all your variables being returned
<?php
if (isset($thumbnail))
{
echo $thumbnail;
}
else
{
echo "";
}
?>
Alternativaely, you can use a ternary operator:
<?php
echo (isset($thumbnail)) ? $thumbnail : '';
?>
Edit again: just to illustrate what I mean about how the variables might not get defined within a script, here is an example that could cause that undefined error:
<?php
if ($_POST['value'] == 1)
{
// This will never be reached unless $_POST['value'] is exactly 1
$return_val = 1;
}
echo $return_val;
?>
This will give the undefined warning, if $_POST['value'] is anything other than 1.
Similarly, if $_POST['value'] were 0 in the following code, it would have that undefined warning as well:
<?php
for ($i=0; $i<$_POST['value']; $i++)
{
// This will never be reached if $_POST['value'] is less than 1
$return_val = $i;
}
echo $return_val;
?>
In the examples above, you can simply define $return_val at the top of the script, and you won't get the error anymore.
You send this data as a post method.you shuld echo them with $_post['name'] but you just echo $name
Use this in script.php :
<?php
echo $_POST['title'];
echo $_POST['thumbnail'];
echo $_POST['url'];
?>
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\')"';
}
?>
>...
I want to know if my php variable does not exists, then I want to execute my javascript.
For example-
<?php
if(!isset($_REQUEST['myVar'])){
?>
<script>
alert('variable not exist');
</script>
<?php
}
?>
Is this right way to use javascript code in php extension file
I know all other answers solve your issue but i prefer it to do this way
<script>
<?php
$isset = !isset($_POST['myVar']) ? 'true' : 'false';
echo "var isset = $isset;";
?>
if(isset) {
alert('variable not exist');
}
</script>
when php render your page it will give this output
<script>
var isset = true;
if(isset) {
alert('variable not exist');
}
</script>
Do it like this and it will work:
if (!isset($_REQUEST['myVar'])) {
echo "<script>alert('variable not exist');</script>";
}
you can try writing this piece of code where you want the script to be placed:
<?php
if (!isset($_REQUEST['myVar'])) {
echo '<script>
alert("variable not exist");
</script>';
}
?>
I'm having some trouble in JS function for combobox. It functions well if there is a PHP variable being passed, but if there's nothing, the whole block of code doesn't work. I've tried using if(typeof(<?php echo json_encode($information['day']) ?>)!='undefined') but it still doesn't work. Is there another way on how to determine if the PHP variable is set or passed?
There are more ways to do this than I can think of. Here is one.
<script>
<?php if( isset($information) && isset($information['day']) ) { ?>
var myJson = <?php echo json_encode($information); ?>;
<?php } else { ?>
var myJson = null;
<?php } ?>
if(myJson != null) {
// do something
}
</script>
Change this line of code
if(typeof(<?php echo json_encode($information['day']) ?>)!='undefined')
to this
if(typeof("<?php echo json_encode($information['day']); ?>") != 'undefined')
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.
}