PHP Variable Seen in Javascript - javascript

I am trying to load some select options by using a few JS functions. I want to have one option selected by default if it is equal to a PHP variable defined before.
I receive an error:
Unexpected token
and I am sure I am doing something wrong with the syntax:
This is a section of my JS functions:
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].id);
if (select.options[i].text== <?php echo '$categoriesSelect'; ?>)
{
select.options[i].selected=true;
}
}
The variable $categoriesSelect is defined before the JS. Thank you!

You need to quote your strings.
Change (from your comment):
if (select.options[i]== <?php echo "json_encode($categoriesSelect)"; ?>)
to:
if (select.options[i].text == "<?php echo $categoriesSelect; ?>")
This will validate against the text for the option. Change .text to .value to validate against value for the option.
...also removed json_encode() since the variable only contains a string.

You need to remove quotes around php function:
From
if (select.options[i].text== <?php echo '$categoriesSelect'; ?>)
To
if (select.options[i].text== '<?php echo $categoriesSelect; ?>')

Related

AJAX - Undefined PHP variable

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'];
?>

PHP variable, and change javascript properties

I have got the most biggest problem, I have see.
piece of code (just and example, the main example use database querys):
<?php $var1="999"?>
<script>
bigvar= <?php echo json_encode($var1); ?>;
var lolo = {
big: 2
}
lolo.big=bigvar;
alert(lolo.big);
</script>
Problem:
It does not recognize the PHP variable (it doesn't change to 999 value), and passing php value to javascript variable, doesn't work.How can help me ?.It is a big issue.
you should add quotes while assigning value from php variable to javascript, like as follows
<script>
bigvar= "<?php echo json_encode($var1); ?>"
var lolo = {
big: 2
}
lolo.big=bigvar;
alert(lolo.big);
</script>
and its </script>, not </scripts>
<script>
var bigvar= "<?php echo($var1); ?>"
var lolo = {
"big": "2"
}
lolo.big=bigvar;
alert(lolo.big);
</scripts>
The above example works fine for me..Try it
You have to add quotes around your php, so your JS know that this value is a string.
bigvar = "<?php echo json_encode($var1); ?>";

Array of Javascript in PHP

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.

SyntaxError: unterminated string literal var address = "

I've this problem at the var address line, i think to have write all correctly or not?
<?php for ($i = 1; $i <= count($data); $i++) { ?>
var address = "<?php echo $address[$i].','.$city[$i].','.$region[$i] ?>";
alert(address);
<?php } ?>
You're generating javascript with php and the error you get comes from the javascript part, not php. I guess that one of your variables like $address contains something that isn't valid in js strings, like a newline. The best practice is to use json_encode to encode values for use in javascript:
var address = <?php echo json_encode($address[$i].','.$city[$i].','.$region[$i]) ?>;

quotes in onclick event

I had an onclick event as below.
<div onclick="display_function('<?php echo $user_id;?>','<?php echo $student_id;?>','<?php echo $student_name;?>')"></div>
function display_function(user_id,student_id,student_name)
{
alert(user_id+'-'+student_id+'-'+student_name); //<-- testing only. I have my own code here
}
the function works fine with the name like Mary, Chris and etc.
However, if the student name contains a ', e.g. Cheng'li, the function won't work.
I need help to fix this. How can I make the function works by 'escaping' the quote mark in name?
Thanks.
You need to add a call to htmlentities around the data you wish to echo.
Not doing so exposes your code to XSS attacks.
use PHP function addslashes
<?php
$str = "Is your name O'reilly?";
// Outputs: Is your name O\'reilly?
echo addslashes($str);
?>
IN your case
<?php echo addslashes($student_name);?>
REFERENCE
http://www.php.net/addslashes
Note: If your code contain html tag than use htmlentities (Entoarox Answer)
you can either use escape()
<div onclick="display_function(escape('<?php echo $user_id;?>'),escape('<?php echo $student_id;?>'),escape('<?php echo $student_name;?>'))"></div>
function display_function(user_id,student_id,student_name)
{
alert(user_id+'-'+student_id+'-'+student_name); //<-- testing only. I have my own code here
}
That is because you are passing the values in function in single quotes. When name will have a single quote, this will cause error.
try double quotes like
<div onclick="display_function(\"<?php echo $user_id;?>\",\"<?php echo $student_id;?>\",\"<?php echo $student_name;?>\")"></div>
Just add \ before ' to tell your script that it is a string. I hope it helps
<?php
$user_id = 1;
$student_id = 1;
$student_name = "Cheng\'li";
?>
<div onclick="display_function('<?php echo $user_id;?>','<?php echo $student_id;?>','<?php echo $student_name;?>')">Click</div>
<script>
function display_function(user_id,student_id,student_name)
{
alert(user_id+'-'+student_id+'-'+student_name); //<-- testing only. I have my own code here
}
</script>
If you cannot put \ directly in String, you need to use [addslashes][1]
<script>
function display_function(user_id,student_id,student_name)
{
alert(user_id+'-'+student_id+'-'+addslashes(student_name)); //<-- testing only. I have my own code here
}
</script>

Categories