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'];
?>
Related
My script removes the http:// and www from urls displayed in a post's content but for some reason it either affects all the posts but the last one or just the first post of the page depending on where I place the script.
For instance if it's in the loop it will affect all the posts but the last but if it's outside the loop it only affects the first post.
I'm looking for a solution so that it takes affect on all urls being displayed on a page. Any help would be much appreciated.
<?php
if (have_posts()) :
while (have_posts()) : the_post(); ?>
<Script>
$(document).ready(function removeFunction() {
let post_id = '<?php global $post; echo $post->ID; ?>';
var str = document.getElementById("link" + post_id).innerHTML;
var res = str.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0];
document.getElementById("link" + post_id).innerHTML = res;
});
</Script>
<p><?php the_content(); ?></p>
<!-- This is where the URL's are EX: <a id="link[return_post_id]" href="http://example.com/">http://example.com/</a> -->
<?php endwhile;
else :
echo '<p>No content found</p>';
endif;
?>
1.You tagged jQuery there so put jQuery code outside of loop.
2.It has to iterate over all <p> and do what you are doing.
3.Change <p><?php the_content(); ?></p> to <p data-id="<?php global $post; echo $post->ID; ?>"><?php the_content(); ?></p> (inside while loop)
4.After above steps followed, change jQuery code like below:
<Script>
$(document).ready(function() {
$('p').each(function(){
let post_id = $(this).data('id');
var str = $(this).html();
var res = str.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0];
$(this).html(res);
});
});
</Script>
there is a problem and this is on mixture of php and javascript.
Your php code Generate JS Within a Loop, in each loop it will create a function named removeFunction() and your browser interpreter mixed up things. it will replace the last one.
There Are 2 Solution for Your problem:
First is to make These Functions Distinct like This:
$(document).ready(function removeFunction<?php echo $post->ID; ?>() {
this will make function names as removeFunction1() removeFunction2() ...
The Second Sulotion is to Define The function outside The loop and in the php loop just call the function like this:
while (have_posts()) : the_post(); ?>
<script>
removeFunction(<?php global $post; echo $post->ID; ?>);
and your function definition would be like this:
removeFunction(post_id){
I am trying to call JavaScript function in php and pass it value of a php json array type variable as an argument. I found from search on SO forum one way to do this is to echo/print_r the variable value to a js var inside a js script within php code. I am trying do it this way but I am not able to recover from 'unexpected token: identifier error ' while doing so.
I am trying to figure out the reason of syntax error but couldn't. I tried different ways what I found; by putting quotes single/double around php part within the script, without quotes as some places I found solution with quotes some places without but no one seems working.
Here is my code. It will be very helpful if someone sees it and point what is causing this error.
<script>
dspChrt(WData);
.......
</script>
<HTML>
<?php
$WData;
require("Connection.php");
try {
$stmt = $conn->prepare("Select humidity, temperature FROM weatherdata");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt->fetchAll() as $k=>$v) {
$WData = json_encode($v);
//print_r($WData);
}?>
<script>
var Wdata = <?php print_r($WData);?>
dspChrt(WData);
consol.log(WData);
</script>
<?php
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
</HTML>
First of all you need to parse the JSON using JSON.parse.
Also you need to change the sequence of php and javascript code.
If you want to assign php data to Javascript variable, please retrieve data using php first and write javascript code below it.
For example :
<?php
$v = array(1,2,3);
$data = json_encode($v);
?>
<script>
var WData = JSON.parse('<?php echo $data; ?>');
dspChrt(WData);
</script>
You should encode your PHP into JSON to pass it to JavaScript.
And you should prepare your data first.
<?php
$data = array('xxx'=>'yyy');
?>
<script>
var data = <?php echo json_encode($data); ?>;
//then in js, use the data
</script>
for your code, there are too many errors to be fixed:
<HTML>
<?php
require("Connection.php");
$stmt = $conn->prepare("Select humidity, temperature FROM weatherdata");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$WData = array();
foreach($stmt->fetchAll() as $k=>$v) {
$WData[] = $v;
}
?>
<script>
var WData = <?php echo json_encode($WData);?>;
console.log(WData);
dspChrt(WData);
</script>
</HTML>
I was trying to get datas from the database and put them into the array in Javascript but Javascript is not working in PHP command area.
Here is the whole PHP codes;
<?php
mysql_connect("mysql.metropolia.fi","localhost","") or die("ERROR!!");
mysql_select_db("localhost") or die("COULDN'T FIND IT!!") or die("COULDN'T FIND DB");
$sql = mysql_query("SELECT * FROM METEKSAN_HABER_CUBUGU");
$haber = 'haber';
$list = array();
$i=0;
while($rows = mysql_fetch_assoc($sql)){
$list[] = $rows[$haber];
$i++;
}
echo $i;
echo '<script type="text/javascript">
var yazi=new Array();';
echo $i;
for ($k = 0 ; $k < $i ; $k++){
echo 'yazi['.$k.']="'.$list[$k].'';
}
echo '</script>';
?>
But when it comes to;
echo '<script type="text/javascript">
var yazi=new Array();';
this command line, the problem begins. Though I write 'echo $i;' after that command, I get nothing on the screen but I get the result if I write before that command. So, it means that everything works well before that command. What you think about the problem ? Why can't I starting the Javascript command ? Am I writing something wrong ?
Please give me a hand.
Thanks.
UPDATE;
I opened the web source and yeah it exactly seems there is a problem. So, I think it's better to ask that how can I write
<script type="text/javascript">
/*Example message arrays for the two demo scrollers*/
var yazi=new Array()
yazi[0]='METEKSAN Savunma, Yeni Dönemin Örnek Oyuncusu Olmaya Hazır'
yazi[1]='METEKSAN Savunma Bloomberg TVde'
</script>
this Javascript code in PHP ??
You can see my output at http://users.metropolia.fi/~buraku/Meteksan/index.php
try something like this
while($rows = mysql_fetch_assoc($sql)){
$list[] = ''.$rows[$haber].'';
}
$js_array = json_encode($list);
echo "<script>var yazi = ". $js_array . ";</script>";
It seems you are executing it currently in your browser? Then you should find your second output when opening page source, because your browser tries to executes the output as JS code. If you execute it on cli, everything should work as expected.
EDIT based on your comment:
Bullshit i wrote before, obviously. Viewing line 122 of your current html shows me a problem with your quotation marks. try the following:
for ($k = 0 ; $k < $i ; $k++){
echo 'yazi['.$k.']=\''.$list[$k].'\';';
}
In the end you should try to avoid using this kind of js rendering at all. The json_encode proposal of jeremy is the correct way to go.
You may have much more compact code:
....
$list = array()
while($rows = mysql_fetch_assoc($sql)) {
$list[] = $rows[$haber];
}
echo '<script type="text/javascript">' . "\n";
echo 'var yazi=';
echo json_encode($list,JSON_HEX_APOS | JSON_HEX_QUOT);
echo ";\n";
echo '</script>' . "\n";
What is this doing:
There's no need to count the added elements in $i, count($array) will give you the cutrrent number.. But it's not needed anyway.
Put some newlines behind the echo, better readable source
json_encode will format an JSON array from your php array, which can be directly used as source code.
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)
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')