PHP Sending 2 variables onClick to Javascript - 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 />';

Related

Passing encoded variable from php and decoding in 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

Pass a variable from JavaScript to PHP

I'm trying to pass the variable from a JavaScript function - selected text - to the same page using php post method:
if (isset($_POST['u_name']))
{
echo $_POST['u_name'] . '</p>';
}
echo "<script type='text/javascript'>";
echo "var var1 = 0; var range = window.getSelection ();";
echo "function gst () { var range = window.getSelection (); alert (range.toString ()); var1 = range.toString ();}";
echo "document.write('<form method=\'post\'>');";
echo "document.write('<p>selected area:<br />');";
echo "document.write('<button onclick=\'gst ()\' type=\'submit\' name=\'u_name\' value = \'' + var1 + ' \' />Button</button>');";
echo "document.write('</form>');";
echo "alert (interesting);";
echo "</script>";
after pressing the button the selected page text is correct: it is checked with alert (range.toString ()) , however, the initial value of var1 variable - 0 is posted.
What could cause it and how one can pass the value, obtained from the javascript function through post method ?
Anton
That's because you set value attribute on the page load.
You can change it dynamically on button click. Replace one of your rows to:
echo "document.write('<button onclick=\"this.setAttribute(\'value\', var1); gst()\" type=\'submit\' name=\'u_name\' value = \'' + var1 + ' \' />Button</button>');";
Note this.setAttribute.
If you want to pass JavaScript variables to PHP, you'll have to use an Ajax request.
PHP is server sided, whereas JavaScript is client sided. This means that all PHP code is done before any JavaScript is even triggered. You can manipulate JavaScript with PHP, but if you want to manipulate PHP with JavaScript, use an Ajax call.

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>';
}
}

Get embedded values in javascript function on HTML Page

I am using php and trying to fetch a value in a javascript function.
The javascript in the HTML page is the following:
<script type="text/javascript">
function show(q)
{
if(q.length > 0)
{
if(q.indexOf("tid") > -1)
{
location.href = "map.jsp?" + q;
}
else
{
location.href = "listmap.jsp?" + q;
}
}
return false;
}
$(function() {
$("#map").goMap({
latitude: -35.331415
,longitude: 149.131851
,maptype: 'ROADMAP'
,scrollwheel: false
,zoom: 11
,markers: [ {latitude: -35.192103,longitude: 149.332313,icon: 'images/m/marker1.png',html: {content: 'Loading...', ajax: 'mapinfo.jsp?sid=9057'}}]
I need to get the values of (3rd and 4th lines in second function) the latitude and longitude which are: -35.331415 and 149.131851
I'm just not sure how to access the individual values...
EDIT: I AM USING PHP to save these values in variables then later write them to a csv file
Currently i'm using this code (here's a snippit) to get everything else on other pages
<?php
$ch = curl_init("http://pvoutput.org/listmap.jsp?sid=312");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$cl = curl_exec($ch);
$dom = new DOMDocument();
#$dom ->loadHTML($cl);
$Lat_data = $dom -> getElementsByTagName("script");
print_r($Lat_data -> item(1) );
EDIT 2:
I fixed all the problems by doing this:
$Lat_data = $dom -> getElementsByTagName("script");
$content =$Lat_data -> item(10) -> textContent;
$regex = "/latitude: ([^\b,]*)/";
if (preg_match( $regex , $content , $values )) {
echo $values[1];
$regex2 = "/longitude: ([^\b,]*)/";
}
if (preg_match($regex2, $content, $values2)) {
echo $values2[1];
}
You managed to get the script node. Now you want its content (the javascript code)
$content = $Lat_data -> item(1) -> textContent
Once you got the content you can parse it using regex expression to get what you want
$regex = "/latitude: ([^\b\n]*)(.|\n)*,longitude: ([^\b\n,]*)/";
if (preg_match($regex, $content, $values)) {
echo 'latitude: ' . $values[0];
echo 'longitue: ' . $values[2];
}
regex explanation (test here):
finds "latitude: "
then we get the first group (), [^\b\n]* means anything but blackspace or newline characters
get anything between latitude value and ',longitude: '
next find ",longitude: "
third group just as the previous one. I added ',' so that if there is not blank between the longitude and ', maptype' it still works.
this regex explanation is getting a little messy, check the test link to more detailed explanation.
I have not tested it so there might be some syntax error but the idea is there ;)
Would it not be more efficient to implement a bit of ajax to submit the Longitude and Latitude from your js file to your php file?

Categories