Passing Values to JavaScript Functions in PHP - javascript

while ($row= mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row["madh"] . "</td>";
.....
echo "<td><input type='button' onclick='detail()' value='d'></td>";
echo "</tr>";
}
function detail(data){}
i want to pass $row["madh"] to detail() but I have problem with "" and ''.

put Id here
echo "<td id="id_madh">" . $row["madh"] . "</td>";
when you click on button as in your code
echo "<td><input type='button' onclick='detail()' value='d'></td>";
you can get value using jquery like this
function detail(){
var value_madh = $('#id_madh').val();
}

Though isn't the best option, you can try to separate that echo line into different parts
echo "<td><input type='button' onclick='detail(" . $row["madh"] . ")' value='d'></td>";

I think you just need to escape the quotes?
echo "<td><input type='button' onclick='detail($row[\"madh\"])' value='d'></td>";
note that the function will be immediately involved on page load, you probably want to wrote this within a closure so it's not actually invoked until it's clicked:
echo "<td><input type='button' onclick='function(){ detail($row[\"madh\"]) }' value='d'></td>";

First put $row["madh"] in a variable;
$var = $row["madh"];
then
echo "<td><input type='button' onclick='detail('$var')' value='d'></td>";

Related

PHP and Javascript : Multiple Buttons inside a table

I'm working with PHP, Javascript and MySQL. My goal is to have a button on each row. The button should call the onclick fucntion and href to another page.
My problem with my code -- > only the button from the first row is clickable...
I'm assuming the Button ID needs to be unique for each button.. What are my options to make all buttons clickable ?
// printing table rows
while($row = mysqli_fetch_row($result))
{
echo "<tr>";
echo "<td><button id='greenbutton' class='small pill green'>$row[0]</button></td>";
echo "<td><img src='/iframe/$row[7]'>&nbsp$row[5]</td>";
echo "<td>$row[4]&nbspmin(s)</td>";
echo "<td><img src='/iframe/$row[6]'>&nbsp$row[2]</td>";
if ($row[3] == 0) {
echo "<td>Unknown</td>";
}
else {echo "<td>$row[3]</td>";}
echo "</tr>\n";
// FOR ONCLICK
echo "<script type='text/javascript'>";
echo "document.getElementById('greenbutton').onclick = function () {";
echo "location.href = '/user';";
echo "};";
echo "</script>";
}
echo "</table></center>";
You're id's of your dom elements should be unique at all time. To achieve this you can add a counter in your while so that all of your button have an id like 'greenbutton1', 'greenbutton2', 'greenbutton3', etc.
$cnt = 1;
// printing table rows
while($row = mysqli_fetch_row($result))
{
echo "<tr>";
echo "<td><button id='greenbutton$cnt' class='small pill green'>$row[0]</button></td>";
echo "<td><img src='/iframe/$row[7]'>&nbsp$row[5]</td>";
echo "<td>$row[4]&nbspmin(s)</td>";
echo "<td><img src='/iframe/$row[6]'>&nbsp$row[2]</td>";
if ($row[3] == 0) {
echo "<td>Unknown</td>";
}
else {echo "<td>$row[3]</td>";}
echo "</tr>\n";
$cnt++;
}
echo "</table></center>";
In that exemple I didnt add your javascript function into your while loop because it look like the same function for all your buttons. I suggest you add the function only once but bound it with the class selector instead of the id selector like this.
// FOR ONCLICK
echo "<script type='text/javascript'>";
echo "document.getElementsByClassName('myGreenButtons').onclick = function () {";
echo "location.href = '/user';";
echo "};";
echo "</script>";
And then add the myGreenButtons class to your buttons in the while loop. You can also use attributes or types selector to gather your dom elements in a more flexible way. Check out theses links for more info:
http://www.w3schools.com/cssref/css_selectors.asp
http://www.htmlgoodies.com/beyond/javascript/using-javascripts-css3-selectors.html#fbid=FhIuAA6GqpH
hope this helps!
echo "<td><a href='/user'><button class='small pill green'>$row[0]</button></a></td>";
...will do the trick.

Two different actions in one form

I have a form with two different submit buttons. One is to delete the corresponding row in the MySQL, which is done on the same page, the other is to save the row to another database, which is done on a separate page. The delete action works fine, but I cannot figure out how to send the save form data to the other page without putting it in the "action" value. I've tried JavaScript, but haven't had much luck. It's a bit of a lengthy post, but I figure the more information I give, the easier it will be for a solution to be found.
Here's just the save submit button:
echo "<td><input type=\"submit\" name=\"save\" value=\"Save\" onclick=\"this.form.action='publishmod.php'\"></td>";
Here's the form code (main page):
echo "<form name=\"editmod\" method=\"post\">";
echo "<tr class='modlist'>";
echo "<td>".$row['id']."</td>";
echo "<td><div class=\"edit\" id=\"div_1\">".$row['title']."</div></td>";
echo "<td><div class=\"edit\" id=\"div_2\">".$row['mod_url']."</div></td>";
echo "<td><div class=\"edit\" id=\"div_3\">".$row['developer']."</div></td>";
echo "<td><div class=\"edit\" id=\"div_4\">".$row['type']."</div></td>";
echo "<td><div class=\"edit\" id=\"div_5\">".$v162."$nbsp".$v164."$nbsp".$v172."</div></td>";
echo "<td><div class=\"edit\" id=\"div_6\">".$row['title'].",$nbsp".$row['developer']."</div></td>";
echo "<td><input type=\"submit\" name=\"save\" value=\"Save\" onclick=\"this.form.action='publishmod.php'\"></td>";
echo "<td><input type=\"submit\" name=\"delete\" value=\"Delete\"></td>";
echo "</tr>";
echo '<input type="hidden" name="id" value="', htmlspecialchars($row['title'], ENT_QUOTES, 'UTF-8'), '" />';
echo '<input type="hidden" name="id" value="', htmlspecialchars($row['mod_url'], ENT_QUOTES, 'UTF-8'), '" />';
echo '<input type="hidden" name="id" value="', htmlspecialchars($row['developer'], ENT_QUOTES, 'UTF-8'), '" />';
echo '<input type="hidden" name="id" value="', htmlspecialchars($row['type'], ENT_QUOTES, 'UTF-8'), '" />';
echo '<input type="hidden" name="id" value="', htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8'), '" />';
echo "</form>";
}
Publish code (page that the save action is supposed to redirect to):
Variable sanitation omitted for Stack Overflow purposes.
$name = $_GET['title'];
$desc = "Installation tutorial for '.$name.'";
$url = ereg("^[A-Za-z_\-]+$", $name) + ".php";
$keywords = "'.$name.', '.$dev.'";
$type = $_GET['type'];
$link = $_GET['mod_url'];
$dev = $_GET['developer'];
$id = $_GET['id'];
// Query
$savequery = "INSERT INTO search (title, description, url, keywords, type, mod_url, developer, v162, v164, v172)
VALUES ('$name', '$desc', '$url', '$keywords', '$type', '$link', '$dev', '$v162', '$v164', '$v172')";
// Mod file creation
$file = ereg("^[A-Za-z_\-]+$", $name) + ".php";
$handle = fopen($file, 'w');
$data = '<?php
$title = "'. $name. '";
$keywords = "'. $name. ','. $developer. '";
$description = "How to install '. $name. ' for PC and Mac.";
include("templates/modheader.php");
include("templates/modfooter.php");
?>';
$save = $dbsave->query($savequery) or die(mysqli_error($dbsave));
// Run creation
echo $save;
fwrite($handle, $data);
print " mod file created!";
fclose($handle);
?>
Don't send it to another page. Use one page and branch with an if (or switch or whatever) statement.
e.g.
if (isset($_POST['save'])) {
include('save.php');
} elseif (isset($_POST['delete'])) {
include('delete.php');
} else {
# logic for when the page is arrived at without the form being submitted with a submit button
}
As an aside. A <form> may not be the parent element of a <tr>, and no element that may have a <td> as a child element may also have an <input> as a child element, you will find some browsers will move elements around to make them acceptable in a way that is going to break your form. Write valid HTML.
I Think you should change type of submit to button for both delete and save and the use following jquery code:
$("#savebutton_id").onclick(function(){
$("#formid").attr('action','Your save Page');
$("#formid").submit();
});
$("#deletebutton_id").onclick(function(){
$("#formid").attr('action','Your delete Page');
$("#formid").submit();
});
you can send data to other pages using hyperlink
eg:Shoes
we can get the category variable in the next page by using
$_GET['category'];

Using jQuery to get the data of a JSON Object

I am new to jQuery and JSON. I have the following PHP code (getData.php) performs query from the database:
<?php
header('Content-Type: application/json');
....
// some code here
....
$my_arr=array();
// fectching data into array
while($info = mysqli_fetch_array($result))
{
// convert to integer value if there is a bug after passing json_encode
$rev=intval($info['bIRevNum']);
$name=$info['bIName'];
echo "<tr>";
echo "<td>" . $info['bName'] . "</td>";
echo "<td>" . $info['bRevNum'] . "</td>";
echo "<td>" . $info['bIName'] . "</td>";
echo "<td>" . $info['bIRevNum'] . "</td>";
$my_arr[]=array('br'=>$name,'rev'=>$rev);
echo "<td>" . $info['pName'] . "</td>";
echo "<td>" . $info['pRevNum'] . "</td>";
echo "</tr>";
}
// json encode
echo json_encode($my_arr);
?>
After use echo 'json_encode' here I can see the JSON object under this format
[{"br":"itemsb1","rev":37},{"br":"itemb2","rev":45}] on my page.
Now I want to access the integer of rev element of the object (37 and 45) for future usage by jQuery in a different PHP file, lets call it index.php and with the below script
<html>
.....
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("getData.php", function(obj) {
$.each(obj, function(key, value){
$("#div1").append("<li>"+value.rev+"</li>");
});
});
});
});
</script>
...
// test here
<!---jquery--->
<div id="div1"><h2>CHANGE >>>> ....!!!!</h2></div>
<button>Calling from different PHP file</button>
</html>
If it is correct, when I click on the button "Calling from different PHP file" it should appears the value of JSON object as 37, 45.
I have tried many ways, but it does not display anything on my page.
Please help me with this!
It appears your problem is that you are echo'ing the html as well as the JSON. try removing the 'echo' from these lines
echo "<tr>";
echo "<td>" . $info['bName'] . "</td>";
echo "<td>" . $info['bRevNum'] . "</td>";
echo "<td>" . $info['bIName'] . "</td>";
echo "<td>" . $info['bIRevNum'] . "</td>";
echo "<td>" . $info['pName'] . "</td>";
echo "<td>" . $info['pRevNum'] . "</td>";
echo "</tr>";
DO NOT delete this line:
$my_arr[]=array('br'=>$name,'rev'=>$rev);
Also make sure your javascript is syntax correct
$("button").click(function(){
$.getJSON("getData.php", function(obj) {
$.each(obj, function(key, value) {
$("#div1").append("<li>"+value.rev+"</li>");
});
});
});
Ensure that the only content coming back from getData.php is JSON-formatted; otherwise, it won't be parsed correctly. If you visit getData.php in your browser directly, you should only see JSON content, and nothing else (including errors, warnings, etc.). Your jQuery looks good; so the issue would have to be whatever content is coming back from the PHP script. I just whipped up a trivial test case using this PHP:
<?php
header('Content-type: application/json');
$my_arr[]=array('br'=>'something','rev'=>'2.0.5');
echo json_encode($my_arr);
?>
Using the exact HTML you provided, that works just as expected.

Save Id from PHP database as variable

I'm working on a offine web application. But on a certain point it need to receive data from a sql database. This is done with an iframe. However the PHP files print all the data available. Every row of data has a workID, and i want them to be clickable. When you click on the work ID i need to save the work ID as variable so i can use the work ID through my whole application.
For example: I choose 1 work ID. Onclick the work ID is written in my header on every page.
I don't know if this can be done with cookies or just a javascript function on the main page.
See the following code:
<?php
$result=mysql_query("SELECT workid,problem,request FROM workreport ORDER BY workid;");
$i=0;
while( $row=mysql_fetch_array($result) )
{
if($i>0)
{
echo "<tr valign=bottom>";
echo "</tr>";
}
echo "<tr valign=center>";
echo "<td class=tabval></td>";
echo "<td class=tabval><b>".htmlspecialchars($row['workid'])."</b></button></td>";
echo "<td class=tabval>".htmlspecialchars($row['problem'])." </td>";
echo "<td class=tabval>".htmlspecialchars($row['request'])." </td>";
$i++;
}?>
PHP is loaded in an iframe. So i prefer to create the function to save the work id on my main page.
<iframe src="http://localhost/receive.php" width="400" height="300" style="border:none;"> </iframe>
Hope you can help me! thanks in advance.
You can do it like this, using javascript and PHP:
PHP:
while( $row=mysql_fetch_array($result) )
{
if($i>0)
{
echo "<tr valign=bottom>";
echo "</tr>";
}
echo "<tr valign=center>";
echo "<td class=tabval></td>";
echo "<td class=tabval><button id=\"saveid\"><b>".htmlspecialchars($row['workid'])."</b></button></td>";
echo "<td class=tabval>".htmlspecialchars($row['problem'])." </td>";
echo "<td class=tabval>".htmlspecialchars($row['request'])." </td>";
$i++;
}
Javascript
window.onload = function () {
document.getElementById('saveid').onclick = function () {
var id = this.innerHTML;
document.cookie = "saveid=" + id + ", expires=Monday, 04-Apr-2020 05:00:00 GMT";
alert('Cookie saved!');
}
}
Okay, the cookie is now saved. You can access it in PHP using $_COOKIE['saveid'].

Echoing a table in PHP

I want to have this table in PHP? how can I create this and use it in Javascript after?
echo "<table border='1'>
<tr>
<th>word</th>
<th>meaning</th>
<th>checking</th>
</tr>";
while($row = mysql_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['word'] . "</td>";
echo "<td>";
echo "<div";
echo "class='hiding' style='display:none'>" . $row['meaning'];
echo "</div>";
echo "</td>";
echo "<td>";
echo "<input name=\"f\" type=\"checkbox\" value=\"\"> ";
echo "</td>";
echo "</tr>";
}
echo "</table>";
I want to use columns that have class=hiding attribute. but in this way it doesn't work and I have an error:
document.getElementsByClassName(...).item(0) is null
document.getElementById('hiding').style.visiblility = 'visible';
I think I should echo table another way but I don't know how?
Here is my Javascript code:
document.getElementsByClassName.item(0).('hiding').style.visiblility = 'visible';
You can not use getElementById to get an element by its classname.
Try something like
document.getElementsByClassName('hiding')[0].style.visibility = 'visible'
change style.visiblility to style.display, and style.display = 'block' for shown

Categories

Resources