Passing encoded variable from php and decoding in javascript? - javascript

I have a very ugly piece of code in php that does something like this:
for ($i = 0; $i <= ($fi_int-1); $i++) {
$song_uri = urlencode($songs[$i]);
echo "URI: " . $song_uri . "<br>";
echo "<li><a href='#' onclick='PlaySong(".$song_uri.")'>" . $songs[$i] . "</li><br>";
}
Now when PlaySong() is being called, this happens:
<script>
function PlaySong(title) {
title = decodeURIcomponent(title));
document.getElementById("player").src = "./mp3/" + title;
}
</script>
The current problem is when $songs[$i] is being passed to PlaySong(), it looks like that right away:
PlaySong(Name+Of+The+Song+-+Artist+LastName+blah) {
...
}
So JS obviously has a problem with it. It tries to add things, because there are pluses... Now how can I convert that mess to string right when it comes in? Or is there a better way to do it? I'm sure there is but this ugliness is strictly for me, so I don't care too much about fast performance :)

You need some quotes around the song_uri string. I can't paste code on mobile... but the php should output like this
Onclick="PlaySong ('this+song')"
At the moment you've got it doing
Onclick="PlaySong(this+song)" and the argument isn't being treated as a string

Related

extract substring inside text from input and store the text inside folder/directory

I have a text area that does this when the image button is pressed:
When the user "adds message" I need to find the strings in the text such that I can extract the url. For example <img src="image.png"> I want to grab the image.png so that I can process it and store in a folder system.
1. Regex to find location
I will need to use some javascript here. I'll need to start at the first quote and end at the second quote. I'm struggling to find a way to do this without mistaking other quotes used in the text.
What I have tried:
function getIndicesOf(text) {
var StartIndex = text.search("src=\"") + 5;
var EndIndex = // not sure, maybe I can search for image extensions (png,jpeg) etc.
var imageAddress = text.substring(StartIndex,EndIndex);
return imageAddress;
}
2. Storing into folder
I understand I believe, how to do this process when using an <input type=file>. However, in php can I replace the $_FILE['image']['name'] with $imageAddress
So instead of
<?php
$name = (isset($_POST['project_name']) ) ? $_POST['project_name'] : '';
$fixedPath = "projects_data/";
if (file_exists("uploads/" . $_FILES["project_image"]["name"]))
{
echo $_FILES["project_image"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["project_image"]["name"],
"$fixedPath/$name/". $_FILES["project_image"]["name"]);
echo "Stored in: " . "$fixedPath/$name/" . $_FILES["project_image"]["name"];
}
?>
can I replace the $_FILES['project_image']['name'] and do this:
<?php
$name = $imageAddress;
$fixedPath = "projects_data/";
if (file_exists("uploads/" . $imageAddress))
{
echo $imageAddress . " already exists. ";
}
else
{
move_uploaded_file($imageAddress,
"$fixedPath/$name/". $imageAddress);
echo "Stored in: " . "$fixedPath/$name/" . $imageAddress;
}
?>
I hope I have provided enough information to help yo understand what I am trying to achieve. If I haven't then please let me know and I will edit it.
Thanks.

Using PHP and JavaScript to display rotating images

What i'm trying to do is do display images from a directory and rotate every x seconds, in
this case 2 seconds.
I wrote this java script code and it works great but the image names are hard coded.
<script language="javascript" type="text/javascript">
img2 = new Image()
seconds = "2";
function imgOne()
{
setTimeout("imgTwo()", seconds * 1000);
}
function imgTwo()
{
document.myimg.src = "pics/WM/IMAGE02";
setTimeout("imgThree()", seconds * 1000);
}
function imgThree()
{
document.myimg.src = "pics/WM/IMAGE01";
setTimeout("imgOne()", seconds * 1000);
}
So I'm trying to use PHP to read the directory and create the javascript but am getting an internal server error. I'm using $p so it's img1 instead of imgOne so I can increase it. It loops thru and after the end loops back to 1. Any help is appreciated.
<?php
$files = glob('pics/WM/*.jpg');
echo
'
<script language="javascript" type="text/javascript">
img2 = new Image()
seconds = "2";
function img1()
{
setTimeout("img2()"), seconds * 1000);
}
'
$p=2;
for ($i=0; $i < count($files) $i++)
{
$image=$files[$i];
echo 'function img' .$p . '()'
echo '{'
echo 'document.myimg.src = "' .$image . '";'
$p++;
echo 'set Timeout(img"' .$p . '()", seconds * 1000); '
echo '}'
}
echo 'function img' .$p . '()'
echo '
{
document.img src="IMAGE01";
set Timeout("img1()", seconds * 1000);
}
</script> '
?>
the echostatements in your php scripts are missing the final ;. This should be the problem that causes the internal server error.
How to fix your implementation:
You should write something like
// using multiple echo statements
echo "..... your string ... ";
echo $p;
echo "--- something else ----";
// or you can concatenate strings with .
echo ".... your string ... " . $p . "---- something else ----";
Similar but safer and clearer PHP implementation:
Printing out Javascript code via PHP could be error prone, therefore I would recommend to use output big parts of text outside PHP code, like this
Some text where p = <?php echo $p; ?> is printed out.
How to improve the Javascript part:
Load all images at once
This is not related on the specific question, but simplifies your solution. Regarding your own project (rotating images), as suggested in the comments there are many reusable javascript components you can use (firstly using some javascript libraries, e.g. jQuery). But if you want to develop this feature by yourself, keep in mind that changing the src attribute of an image tells the browser to download it from scratch, resulting in glitches. To solve this issue, you may insert many <img> elements and than display it one at the time (using css styling directives).
Iterate over the images using one timed function
Furthermore, you could simplify your javascript code: instead of using a different function to display each image you can use global variables (i.e. window.my_rotate_current_img_id) or better clojures to select and show the current image:
// 1. Declare an array of img tags ID, identifying the different images
// Note that we are using PHP to generate the array - the implode function
// concatenates array items into a string separated by the first argument
// given
var images = [<?php echo '"' . implode('","', $images) . '"'; ?>];
// 2. Define a function that shows the correct image
function hide_first_and_show_second(first, second){ ... }
// img_num is the number of images to rotate
var update_img = function(idx){
return function(){
hide_idx = idx;
show_idx = (idx + 1) % img_num;
hide_first_and_show_second(hide_idx, show_idx);
}
};
setInterval(update_img(0), 1000);
This are possible (and useful) improvements of your solution for this problem. Hope i clarified.

javascript call inside php where loop not working and breaks query

I am attempting to call a javascript function inside a php where loop. I've succeeded in calling the variable, however the function only works on the first line, and then breaks a subsequent query.
The javascript is a simple show/hide of a div or span tag with a specific id. I'm trying to have this appear for every instance of a variable, but only open the span associated with that entry, so I used a php variable from the query.
The javascript code is contained in the header; it works fine without the php, and the php works fine without the javascript but I can't seem to make them work together.
Here's the code:
while($row = mysqli_fetch_array($qir)) {
$ingredient_id = $row['ingredient_id'];
echo '<input type="checkbox" value="' . $ingredient_id . '" name="markdelete[]">';
echo $row['amt'] . ' ' .$row['ingredient_name']; ?> <button onclick="showHide('<?php echo $row['ingredient_id']; ?>'); return false">Edit amount</button> <br />
<span id="<?php echo $row['ingredient_id']; ?>" class="hide">
<?php include_once('amt.php');
echo '</span> ';
// }
echo '<br />';
}
echo '<input type ="submit" name="remove" value="Remove">';
First of all, the showHide is only working on the first record
It is also making this query not respond at all.
if (isset($_POST['remove'])) {
iF (!empty($_POST['markdelete'])) {
foreach ($_POST['markdelete'] as $delete_id) {
// remove specific source from source_subject
$rem_ing = "DELETE from dish_ingredient
where ingredient_id = $delete_id
and dish_id = $dish_id ";
mysqli_query($dbc, $rem_ing)
or die ('Error removing ingredient: '.mysqli_error($dbc));
}
}
}
I tried removing the return false;, to no avail. Please let me know if I need to show more of the code (e.g. the javascript itself)
Edit:
I've tried working within the php string (this is actually what I had tried first) but it seems to break everything (no javascript, no php)
echo $row['amt'] . ' ' .$row['ingredient_name'] . '<button onclick="showHide(\''. $row['ingredient_id'] .'\') return false">Edit amount</button> <br />';
echo '<span id=" '. $row['ingredient_id'] .' " class="hide">';
include_once('amt.php');
echo '</span> ';
Edit: I am open to other solutions if this is not something that is possible. I'm feeling a bit stumped. Realistically I just want to have a list of items called from a mysql database, and have a field appear onclick to edit an associated variable if desired without having to send it to another page or reload the script for usability (hence the javascript piece).
Thanks again, anyone who can assist.
Note: this is the script that I am calling:
<script language="JavaScript" type="text/JavaScript">
menu_status = new Array();
function showHide(theid){
if (document.getElementById) {
var switch_id = document.getElementById(theid);
if(menu_status[theid] != 'show') {
switch_id.className = 'show';
menu_status[theid] = 'show';
}else{
switch_id.className = 'hide';
menu_status[theid] = 'hide';
}
}
}
</script>
You don't need tag there as you are already in php block.Try it without and use
showHide(\''.$row['ingredient_id'].'\')
and change
<?php include_once(....);
to
include_once(........);
Hopefully that would work
===========
try this for you javascript
<script language="JavaScript" type="text/JavaScript">
function showHide(theid){
if (document.getElementById) {
var switch_id = document.getElementById(theid);
if(!switch_id) {
switch_id.className = (switch_id.className.indexOf("show") > -1) ? "hide" : "show"
}
}
}
Okay after a long time on this, I finally figured out what was going on. Part of the issue was that I was trying to call a form inside a form, which I had forgotten is not permitted in HTML, so this required some redesign.
Other issues involved calling loops within inside loops, which caused problems where the first record would work, but not for the remaining records.
The javascript above did not need to be modified, only the way that it was called.
Here is what worked. The main key was using include() instead of include_once().
while($r = $qir->fetch_assoc()) {
$ingredient_id = $r['ingredient_id'];
$amt = $r['amt'];
$ingredient_name = $r['ingredient_name'];
echo $r['amt'] . ' ' .$r['ingredient_name'];
if ($row['user_id'] == $user_id) {
echo ' <span class="openlink"><button onclick="showHide(\''.$ingredient_id. '\')">edit amount</button></span><br/>';
echo '<div id="'.$ingredient_id.'" class="hide">';
include('amt1.php');
echo '</div>';
}
}

Error when sending html source from javascript to PHP

I am using the following to encode the html source of a ckeditor in a web application.
var updateString = app.getValue('wysiwygHomePage');
var encodedString = encodeURIComponent(updateString);
alert(encodedString);
app.httpRequest("www.xxxx.com/techy/savealldata.php", "GET", function(data, error, httpResponse){
alert(data);
},
{
"updateType":"homePage","updateString":encodedString}, "String", {}, {});
}
Then at the PHP end I am using :
<?php
$updateType = $_GET["updateType"];
$updateString = $_GET["updateString"];
$updateString2 = urldecode($updateString);
echo 'success here '.$updateType .' '.$updateString2 ;
?>
I am adding some coloured tex and the html source for this is:
<p>
<span style="color: rgb(255, 140, 0);">123</span><br />
</p>
<p>
This works okay until I cut and paste more than 32 times.
I then just get error returned from the PHP call.
I presume there are to many chars arriving at the PHP end ???
Any ideas why this is happening ?
Mr WARBY.
UPDATED PHP Code.
<?php
include 'dbdata.php';
$updateType = $_POST["updateType"];
$updateString = $_POST["updateString"];
$updateString2 = urldecode($updateString);
//echo 'success here '.$updateType .' '.$updateString2 ;
if($updateType === 'homePage')
{
$query5 = "UPDATE pageText SET HTML= "."'".$updateString2."'"." WHERE ID = 12";
//echo $query5;
echo 'Home Page Updated 2';
mysql_query($query5);
}
if($updateType === 'instructionPage')
{
$query5 = "UPDATE pageText SET HTML= "."'".$updateString2."'"." WHERE ID = 13";
echo 'Instruction Page Updated 2';
mysql_query($query5);
}
if($updateType === 'FAQPage')
{
$query5 = "UPDATE pageText SET HTML= "."'".$updateString2."'"." WHERE ID = 14";
echo 'FAQ Page Updated';
mysql_query($query5);
}
?>
There are a lot of variables in play here. You need to change your debugging strategy. Instead of testing end to end each time try isolating each component.
In Javascript, call "app.getValue('wysiwygHomePage')", encode the string, decode the string, and put it right back in the editor. Do that in a loop until you can determine if the client-side is mangling anything.
If not, try encoding a complicated string in Javascript, sending it to a PHP script that decodes/re-encodes and echos it back. Do that in a loop several times.
If you still haven't found the problem try making a PHP script that takes a complicated string, INSERTS it, SELECTs it, UPDATEs it in a loop to see if you database encoding or escaping is affecting it.
If at any point you find the string changing when it shouldn't you've probably found your problem.

PHP Sending 2 variables onClick to Javascript

I want to send 2 variables (im using php to create an html element) and when the user clicks, an alert pops up with the 2 variables.
I've set this up:
PHP:
$item = array (
'string' => $node->getElementsByTagName('string1')->item(0)->nodeValue,
'string2' => $node->getElementsByTagName('string2')->item(0)->nodeValue,
);
$string1 = str_replace(' & ', ' & ', $item['string']);
$string2 = str_replace(' & ', ' & ', $item['string2']);
'.$title.'</strong><br />';
Javascript:
<script>
function doSomething(variable1,variable2) {
var myVar1 = variable1;
var myVar2 = variable2;
alert (myVar1+ ' ' +myVar2);
return false;
}
</script>
I tried this but when I click the link nothing happens.
What is the proper way to send variables from php to javascript?
Thank you for your time.
Is it possible to do this?
<a href="#" onclick"doSomething(this) id="'.string1.'" description="'.string2.'" />link </a>
And do this instead of the other solution?
<script>
function doSomething(obj) {
if(obj!= null)
alert ('Obj is Null');
}else {
alert (obj.getAttributeById("id")+' '+obj.getAttributeById("description"));
return false;
}
</script>
You didn't quote the parameters in your onclick, so your code looks literally like:
<a href="#" onclick="doSomething(Hello, World!)" ...
turning your variables' contents into undefined variables and a syntax error ("Not bracket"?).
Try
<a href="#" onclick="doSomething('$title', '$string')" id= etc...
instead.. Note the quotes around the variables. Also note that you should NEVER directly dump PHP data into a Javascript context like this. As you've found out, the slightest glitch and you've introduced a JS syntax error, which kills the ENTIRE javascript block.
Always output json_encode()'d data, ensuring that you're generating syntactically valid JS code.
You just need to concat the values into your echo string:
echo '' . $title . '</strong><br />';
When you are printing the php variables it prints only the variable, so if $title equals Hello the Java Script interpreter think there a variable in Java Script named Hello.
To avoid this you have to print into the HTML the variable value inside quotes.
$string = 'World!';
$title = 'Hello';
echo ''.$title.'</strong><br />';

Categories