Weird passing php string to javascript sometimes not work - php

how i what it to work:
goal: make a album viewer without reload the page, with a img html element, change img SRC dynamically with javascript, but image url's stored in php variables and what copy to javascript array.
Problem: example have album where have 17 picture, if i echo in php then $i count from 1-17 but in javascript count to 2-12 and 15-17 so ignore 1,13,14 etc. have no ideea why because no difference in data, so DataPicId[13] is undefined but 15th index or 12th index got value normally.
while($row = mysql_fetch_array($SQLpic))
{
$i=$i+1;
$PicId=$row['id'];
$Url=$row['url'];
$Desc=" ".$row['description'];
$UpUser=$row['uploader'];
$Update=$row['udate'];
echo"<script>
nr=Number('".$i."');alert(nr);
DataPicId[nr]=Number('".$PicId."');
DataPicUrl[nr]='".$Url."';
DataPicDesc[nr]='".$Desc."';
DataPicUser[nr]=Number('".$UpUser."');
DataPicDate[nr]='".$Update."';
alert(DataPicUrl[nr]);
</script>";
$ThumbUrl=GetNameOnly($Url);
echo "<div id='PicBoxOut'>
<div id='PicBoxIn' onclick=SelectSrc('".$i."');>
<a href='javascript:void(0);'>
<img src='".$ThumbUrl."' border='0'></a>
</div></div>";

Without seeing the generated html / javascript, I would guess that your variables are breaking your javascript. That could be for example a single quote in the description of a photo.
To make sure that you output valid javascript, it is better to send your complete row-set to javascript as json and build your html in javascript using that json.
So something like:
<?php
// Note that normally you would have done this already in a controller
// and not when you are outputting html
$rows = array();
while($row = mysql_fetch_array($SQLpic))
{
$rows[] = $row;
}
?>
<script>
var json = <?php echo json_encode($rows); ?>,
object = JSON.parse(json);
// now `object` will contain all your rows in a javascript object / array
</script>

Related

Change html code depending on the size of the array in php

Hi i have an array with some Urls and Html code for open this webs in others tabs.
But the array dynamically changes the amount of Urls it contains. How can I change the Html code depending on the number of Urls that my array contains?
Code:
<?php
//$myarray can change dinamicaly the amount of urls contains
$myarray=array('www.google.com','www.piza.com','www.5.com');
?>
Now in my HTML code I have the code for open a tab, but i need open the array numbers of urls. In this case I need window.open('') three times.
<p><a href='#'
onclick='window.open('');
>Click to open webs</a></p>
<?php
//$myarray can change dinamicaly the amount of urls contains
$myarray=array('www.google.com','www.piza.com','www.5.com');
$windowsOpen = '';
foreach ($myarray as $value) {
$windowsOpen .= "window.open('$value', '_blank');";
}
?>
//now in my HTML code I have the code for open a tab, but i need open the array numbers of urls. In this case I need 'window.open('')' three times.
<p>Click to open webs</p>
Few things you should know, the URLs need to start with 'http://' or 'https://' in order to be an external link, if not it be considered as an internal link.
Moreover, most of the browsers will block the window.open if it is more than one as spam.
You could do something like this (although I'd advise against it without careful sanitzation if the urls are originating from inputs entered by users)
<?php
$arr = array("https://www.google.com", "https://www.pizza.com");
?>
<script>
function openWindows() {
var urlsArray = <?php echo '["' . implode($arr, '","') . '"]'; ?>;
for(i=0; i<urlsArray.length; i++) {
window.open(urlsArray[i]);
}
}
</script>
Open Windows

Angular.js modal window within php echoes not working

I'm using code from this angular.js modal window tutorial by Jason Watmore: http://jasonwatmore.com/post/2016/07/13/angularjs-custom-modal-example-tutorial
I'm trying to implement an angular.js modal window within a php partial. Here is the code where I believe there's a problem:
<div id="screenings">
<?php
//MySQL database connection established
...
while ($row = mysqli_fetch_array($result)){
echo "<div class='img_div'>";
echo "<img class='modal_img img_screenings' ng-click=\"vm.openModal('custom-modal-1')\" src='images/".$row['image']."' >";
...
echo "</div>";
}
?>
</div>
<modal id="custom-modal-1">
<div class="modal">
<div class="modal-body">
<img id="popup_img" src="#">
</div>
</div>
<div class="modal-background"></div>
</modal>
<script>
$('.img_div').on("click", function() {
var source = ( $('.modal_img').attr("src") );
alert(source);
$('#popup_img').prop('src', this.src);
});
</script>
The First Problem
The while loop spits out a bunch of images. The script at the bottom should then grab the src of whichever image is clicked and then alert that src in a pop-up message. However, it only alerts the src of the first image in the while loop regardless of which image of the bunch is clicked. I've tested this script outside of the while loop on separate img elements with different src attributes, and it works fine outside of the echoed while loop.
The Second Problem
Within the while loop, there is an ng-click in the second echoed statement that just isn't working. In my app.js file, here is the controller code that ng-click=\"vm.openModal('custom-modal-1')\" should go to (the slashes are because of the echo statement):
app.controller('screeningsController', ['$scope', '$log', "ModalService", function($scope, $log, ModalService){
var vm = this;
vm.message = "Hello World!";
$log.log(vm.message);
vm.openModal = openModal;
vm.closeModal = closeModal;
function openModal(id){
ModalService.Open(id);
}
function closeModal(id){
ModalService.Close(id);
}
};
}]);
Right after the var vm = this; statement, I'm trying to output a message to the browser console as a test, but it's not working. Maybe my syntax is wrong?
here's a couple quick thoughts. In the first portion, I don't think you were actually capturing the correct click. I added a variable to pass into the on click function to select the one that was actually clicked.
As far as the php, sometimes its easier to toggle out of php and do a chunk of html. If you're passing a lot of html chunks you might want to consider doing output buffering.
<?php
while ($row = mysqli_fetch_array($result)){ ?>
<div class='img_div'>";
<img class="modal_img img_screenings" ng-click="vm.openModal('custom-modal-1')" src="images/<?php echo $row["image"]; ?>" />
</div>
As far as the jquery on the page:
you need to grab the actual node with the click event - the "e" is a common convention for that, but its really just a variable
$('.img_div').on("click", function(e) {
var source = $(e).attr("src"); // here you grab the actual attribute
alert(source);
$('#popup_img').attr('src', source);
});
i'm assuming you actually want to set the img src attribute in your target modal here.

Store data in html element

I have dynamic content which I generate with PHP, and i want to store some various text in data attribute. Bu the problem is that i need to escape various characters that could damage my entire html
So I need to do some kind of encoding with php and then decode that string with javascript when i want to use that data, what would be the best way to do that?
And just to clarify i do not want to use any inputs or anything like that, i need to store this data in various elements for example a or div and so on...
If all you want is to pass some data to JavaScript, why not just write it directly to a variable:
<html>
<head>
<script>
var data = <?php echo json_encode($data); ?>
</script>
<!-- etc. -->
Anyway, if you want to do it your way, you can use htmlspecialchars to escape arbitrary data before putting it in an HTML attribute:
<div data="<?php echo htmlspecialchars('"\'!)(#UI#_!)(#JP_!()#J'); ?>">Example</div>
If you then read that with JavaScript, it should understand the HTML encoding, so you won't need to do anything special to read it.
If your data is more complex, but not binary, you could JSON encode it, then use htmlspecialchars:
<?php
$data = array();
$data["a"] = 123;
$data["b"] = "example";
$jsonData = json_encode($data);
$escapedJsonData = htmlspecialchars($jsonData);
echo "<div data=\"$escapedJsonData\">example</div>";
?>
You can then read that data in JavaScript using JSON.parse:
var yourDiv = getDivSomehow();
var data = JSON.parse(yourDiv.getAttribute("data"));
If your data is binary, you can base64 encode it:
<?php
$data = someImage();
$encodedData = base64_encode($data);
echo "<div data=\"$encodedData\">example</div>";
?>
Presumably there's some way to decode this in JavaScript.

PHP javascript call with PHP variable

Good day, I am having a very odd error with my PHP code. I am attempting to dynamically change the content of my webpage by reading from an xml file. I read in some data and assign the data to a PHP variable called $course_title and then attempt to call some Javascript that will update the "innerHTML" of a DOM element. Note: on the line "echo $course_title;' that prints out the correct data to the screen.
$fn = dirname(__FILE__)."/course.xml";
$xml = simplexml_load_file($fn);
$course_bookimagelocation = "";
foreach ($xml->children() as $child)
{
if($child[0]->getName()=="book")
$course_bookimagelocation = $child;
if($child[0]->getName()=="title")
$course_title = $child;
}
//Problems start here...
echo $course_title;
echo '<script type="text/javascript">document.getElementById("heading").innerHTML = "';
echo $course_title;
echo '";</script>';
What is very unique is that the first echo statement prints the correct information, but the next three lines, the .innerHTML does not get changed to that same value. Does anyone know what that is? What is also weird is that if I replace the second "echo '$course_title';" with something like 'Hello world!' then "Hello World!" appears as the innerHTML of the "heading" id object.
EDIT
In the XML file called course.xml, the title element is IC 210 Fall 2010 and the contents of $course_title is IC 210 Fall 2010 so the parsing of the php file appears to be correct and there does not seam to be any special characters like a " or '
I also tried putting everything on the same line and not luck... (I even made sure in the xml file that the <title> element had the text on the same line...
Make sure that .innerHTML = "Some text" are on the same line because .innerHTML = "\nSome Text\n" won't work in javascript.
If you want to have something like this:
.innerHTML = "
Some String
";
try:
.innerHTML = ""+
"Some String" +
"";
"call some Javascript that will update the "innerHTML" of a DOM element." for that we use AJAX, no?
well you can do that way but i think it would be simpler to have the text preloaded in some hidden DIV's and use your functions just to change content's of the DIVS or even toggle visibility of the DIV (as you prefer). That way you will avoid many escaping problem's referred in the comments.
that's the way i would do it if not to use AJAX

Having trouble passing text from MySQL to a Javascript function using PHP

So here's the problem. I have data in a MySQL DB as text. The data is inserted via mysql_real_escape_string. I have no problem with the data being displayed to the user.
At some point I want to pass this data into a javascript function called foo.
// This is a PHP block of code
// $someText is text retrieved from the database
echo "<img src=someimage.gif onclick=\"foo('{$someText}')\">";
If the data in $someText has line breaks in it like:
Line 1
Line 2
Line 3
The javascript breaks because the html output is
<img src=someimage.gif onclick="foo('line1
line2
line3')">
So the question is, how can I pass $someText to my javascript foo function while preserving line breaks and carriage returns but not breaking the code?
===========================================================================================
After using json like this:
echo "<img src=someimage.gif onclick=\"foo($newData)\">";
It is outputting HTML like this:
onclick="foo("line 1<br \/>\r\nline 2");">
Which displays the image followed by \r\nline 2");">
json_encode() is the way to go:
$json = json_encode($someText); # this creates valid JS
$safe = HtmlSpecialChars($json); # this allows it to be used in an HTML attribute
echo "<img src=someimage.gif onclick=\"foo($safe)\">";
You can see a demo here: http://codepad.org/TK45YErZ
If I'm not interpreting badly you may do this:
// This is a PHP block of code
// $someText is text retrieved from the database
echo "<img src=someimage.gif onclick=\"foo('{".trim( preg_replace( '/\s+/', ' ',$someText ) )."}')\">";
You'll save yourself a lot of headaches by pulling the JavaScript out of the HTML:
<img id="myImage" src="someimage.gif"/>
<script type="text/javascript">
var str = <?php echo json_encode($json); ?>;
document.getElementById('myImage').addEventListener(
'click',
function() {
foo(str);
}
);
</script>
Or something similer...
Only json_encode() is enough to escape the new line
echo "<img src=someimage.gif onclick=\"foo(".json_encode($newData).")\">";

Categories