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')
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'];
?>
Is there a best way to separate javascript and php code. for example:
//php code
if(condition1)
{
?>
// javascript code
$card_typej = $(this).val().trim();
if(condition2)
{
$("#id1").html('<?php echo($var1); ?>');
}
else
{
$("#id1").html('<?php echo($var2); ?>');
}
<?php
}
?>
If yes then, how to separate the above code?
First store required PHP variables in Javascript vars and then manipulate it.
<script>
var var2 = <?php echo json_encode($var2); ?>;
var var1 = <?php echo json_encode($var1); ?>;
if(condition1)
{
?>
// javascript code
$card_typej = $(this).val().trim();
if(condition2)
{
$("#id1").html(var1);
}
else
{
$("#id1").html(var2);
}
<?php
}
?>
</script>
You can see, complicated php+js code mixture is not there now.
EDIT: Missed the echo statement!
EDIT2: Added missing paranthesis!
EDIT3: Found the solution. See below!
What I am trying to achieve is this:
Dynamically create a Javascript-file with PHP
Serve Javascript-file as .js as embeddable Javascript on different URLs
Dynamically add Page Name and Page URL information inside the JS to be used in Javascript
Currently I do the following:
code.php
<?php header("Content-type: application/x-javascript"); ?>
/*
<?php echo $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] ;?>
*/
/*
<?php
$func = new Functions;
echo $func->getPageURL();
echo $func->getPageName();
?>
*/
var fred;
...
class.functions.php
<?php
class Functions {
function getPageURL() {
$isHTTPS = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on");
$port = (isset($_SERVER["SERVER_PORT"]) && ((!$isHTTPS && $_SERVER["SERVER_PORT"] != "80") || ($isHTTPS && $_SERVER["SERVER_PORT"] != "443")));
$port = ($port) ? ':'.$_SERVER["SERVER_PORT"] : '';
$data = ($isHTTPS ? 'https://' : 'http://').$_SERVER["SERVER_NAME"].$port.$_SERVER["REQUEST_URI"];
return $data;
}
function getPageName() {
$data = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
return $data;
}
}
Whenever someone triggers my script-embed code I route them to my code.php. Example:
<script src="//servingdomain/dynamic/123.js"></script>
Now, my code.php does a great job, but returns me this:
/*
servingdomain/dynamic/123.js
*/
/*
https://servingdomain/dynamic/123.js
index.php
*/
var fred;
...
Unfortunately my getPageURL und getPageName are not executed properly, but I am failing to understand why.
I am aiming to get this as output:
/*
servingdomain/dynamic/123.js
*/
/*
https://otherdomain/blog/awesome-article (page-url)
Awesome Article to read (page-name)
*/
var fred;
...
How should I takle this problem and get this working correctly either by clean code or dirty workaround ... I am aware of window.location.pathname and window.location.href in Javascript, but I need those to be passed in PHP, since I need to reuse this information to generate dynamic code in code.php.
Solution
Using $_SERVER['HTTP_REFERER'] gives correct referrer and running that through
<?php
echo $_SERVER['HTTP_REFERER'];
$func = new Functions;
echo $func->getPageTitle($_SERVER['HTTP_REFERER']);
?>
class.functions.php
function getPageTitle($url){
$str = file_get_contents($url);
if(strlen($str)>0){
preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
return $title[1];
}
}
Output
https://otherdomain/blog/awesome-article (page-url)
Awesome Article to read (page-name)
<?php
$func = new Functions;
$purl = $func->getPageURL()."\n";//use ()
$pname = $func->getPageName();
echo $purl;
echo $pname;
?>
The PHP code is executed just fine, but it just doesn't have any result. You need to write out the values to the file:
<?php header("Content-type: application/x-javascript"); ?>
/*
<?php echo $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] ;?>
*/
/*
<?php
$func = new Functions;
$purl = $func->getPageURL;
$pname = $func->getPageName;
printf("%s\n", $purl);
printf("%s\n", $pname);
?>
*/
var fred;
...
This will write the values of those variables to the javascript file.
Note that if you want to use these values in the javascript code, you need to assign them to a javascript variable like this, outside of javascript comments:
printf("var pageName='%s'\n", $pname);
That way, you can use pageName in your javascript.
Solution
Using $_SERVER['HTTP_REFERER'] gives correct referrer
<?php
echo $_SERVER['HTTP_REFERER'];
$func = new Functions;
echo $func->getPageTitle($_SERVER['HTTP_REFERER']);
?>
Running that through this function
class.functions.php
function getPageTitle($url){
$str = file_get_contents($url);
if(strlen($str)>0){
preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
return $title[1];
}
}
Output
https://otherdomain/blog/awesome-article (page-url)
Awesome Article to read (page-name)
This is my example code
<script>
var item = "yooow";
jQuery("#view").html(item);
</script>
<?php $str_html = '<p id="view"></p>';
echo $str_html; //it will output "yooow"
?>
but...
when i'm trying to compare this into another php variable
<?php $str_php ="yooow";
if($str_html == $str_php)
{
echo "true";
}
else
{
echo "false";
}
?>
but it returns to false
how can they be an equal?
PHP is run serverside which means it's not aware of any changes you make in the DOM using Javascript.
<script>
var item = "yooow";
Value set only in clinet side, PHP don't know about changes here
jQuery("#view").html(item);
</script>
<?php $str_html = '<p id="view"></p>';
WRONG, it will output "<p id="view"></p>"
echo $str_html; //it will output "yooow" ?>
<?php $str_php ="yooow";
Comparing "<p id="view"></p>" and "yoow" and that is not equal!
if($str_html == $str_php)
Better, you give the item value in cookie/session. And, compare the cookie value with $str_php.
<?php session_start(); ?>
<script>
$(document).ready(function(){
var item = "<?php echo $_SESSION['html']="yooow"; ?>";
$("#view").html(item);
});
</script>
<?php
$str_html = '<p id="view"></p>';
$strHtml=$_SESSION['html'];
$str_php ="yooow";
if($strHtml == $str_php)
{
echo "true";
}
else
{
echo "false";
}
?>
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>';
}
?>