I am trying to pass more then 1 php variable in parameter in a onclick.
<button type="button" class="btn btn-dark bmd-btn-fab bmd-btn-fab-sm"
onclick="<?php echo 'analyse(\'' . $name . '\', \''. $type .'\')'; ?>">
<img src="../assets/add.png" />
</button>
For only 1 parameter it worked with this :
onclick=<?php echo "analyse('$name')"; ?>"
and this:
onclick="<?php echo 'analyse(\'' . $name . '\')'; ?>"
I would put this as a comment but the placeholder text in comments says to not put answers in comments...
First, analyse has to be a JS function, not a PHP function.. Also, you don't need to put analyse inside of the <?php code block..
<button onclick="analyse('<?php echo $name ?>', '<?php echo $type ?>')">
Full demo PHP file:
<?php
$name = "John Smith";
$type = "Best Type"
?>
<div>
<button onclick="analyze('<?php echo $name ?>', '<?php echo $type ?>')">Show Name</button>
<p id="results"></p>
</div>
<script>
function analyze(name, type) {
document.getElementById("results").innerHTML = "<b>NAME:</b> " + name + " <b>TYPE:</b> " + type;
}
</script>
To elaborate, just in case you wanted to use a PHP function to return a name or type, you would use it like so:
<?php
$name = "John Smith";
$type = "Best Type";
function get_Name($nameToGet) {
return $nameToGet;
}
function get_Type($typeToGet) {
return $typeToGet;
}
?>
<div>
<button onclick="analyze('<?php echo get_Name($name) ?>', '<?php echo get_Type($type) ?>')">Show Name</button>
<p id="results"></p>
</div>
<script>
function analyze(name, type) {
document.getElementById("results").innerHTML = "<b>NAME:</b> " + name + " <b>TYPE:</b> " + type;
}
</script>
Related
I am trying create a social media site.
In the fourth line, the onclick='func_cmnt_open(".$row['post_ID'].") should display a div unique to each entry. it seems like a syntax error but I'm unable to narrow it down if its in PHP or javascript.
In line 6, id attribute was set to comment".$row['post_ID']." to make each div unique from the while loop iteration.
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<h4>".$row["username"]." said ".$row["cm_text"]." at ".$row["time"]." comment".$row['post_ID']."</h4>";
echo "<button class='w3-button w3-teal w3-xlarge' onclick='func_cmnt_open(".$row['post_ID'].")'>☰</button>";
echo "<button class='w3-button w3-teal w3-xlarge' onclick='func_like()' id='like'>☰</button>";
echo "<div class='w3-black' id='comment".$row['post_ID']."' style='display: none'>";
echo " <div class='w3-container''>";
echo " <h4>";
echo " ///code was here ";
echo " </h4>";
echo " <button class='w3-button w3-grey w3-xlarge' onclick='document.getElementById('id02').style.display='block''>☰</button>";
echo " <div id='id02' class='w3-modal'>";
echo " <div class='w3-modal-content w3-card-4'>";
echo " <header class='w3-container w3-teal'> ";
echo " <span onclick='document.getElementById('id02').style.display='none'' class='w3-button w3-display-topright'>×</span>";
echo " ///code was here";
echo " </header>";
echo " <div class='w3-container'>";
echo " <form class='w3-container' action='home.php' method='GET'>";
echo " <p><input type='text' class='w3-input' name='post_comment' placeholder='Whats happening there...'/></p>";
echo " <p><button class='w3-button w3-black'>Post</button></p>";
echo " </form>";
echo " </div>";
echo " <footer class='w3-container w3-teal'>";
echo " <p>nothing here</p>";
echo " </footer>";
echo " </div>";
echo " </div>";
echo " </div>";
echo "</div>";
}
}
JAVASCRIPT:
i had tried using string concat to join "comment" and "num" to get the unique id of div. that did not work either.
function func_cmnt_open(num) {
if (document.getElementById('comment'+num.tostring()).style.display == "none")
{
document.getElementById('comment'+num.tostring()).style.width = "100%";
document.getElementById('comment'+num.tostring()).style.display = "block";
}
else
{
document.getElementById('comment'+num.tostring()).style.width = "0%";
document.getElementById('comment'+num.tostring()).style.display = "none";
}
}
OUTPUT:the selected button should invoke the javascript with arguments from PHP code and display a black div where i can enter comments
I'm not sure of this is the most efficient way of doing it. please advice if there are any other way also to achieve the same output.
If post_ID is not strictly a string you will get a syntax error in Javascript.
... onclick='func_cmnt_open(".$row['post_ID'].")'...
Consider this value 1 Above will create this in the page source code.
... onclick='func_cmnt_open(1)'...
Now consider this value post1
... onclick='func_cmnt_open(post1)'...
In the second case it should be
... onclick='func_cmnt_open("$row['post_ID']")'...
To get that in PHP with the way you have echo you'll have to escape double quotes or the ' in the attribute will also cause issues. So like this:
... onclick='func_cmnt_open(\"".$row['post_ID']."\")'...
There were a few other quoting issues onclick='document.getElementById('id02').style.display='block'' ..>, I don't know if I got them all but should be better.
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<h4>{$row["username"]} said {$row["cm_text"]} at {$row["time"]} comment{$row['post_ID']}</h4>
<button class='w3-button w3-teal w3-xlarge' onclick='func_cmnt_open(\"{$row['post_ID']}\")'>☰</button>
<button class='w3-button w3-teal w3-xlarge' onclick='func_like()' id='like'>☰</button>
<div class='w3-black' id='comment{$row['post_ID']}' style='display: none'>
<div class='w3-container''>
<h4>
///code was here
</h4>
<button class='w3-button w3-grey w3-xlarge' onclick='document.getElementById(\"id02\").style.display=\"block\"'>☰</button>
<div id='id02' class='w3-modal'>
<div class='w3-modal-content w3-card-4'>
<header class='w3-container w3-teal'>
<span onclick='document.getElementById(\"id02\").style.display=\"none\"' class='w3-button w3-display-topright'>×</span>
///code was here
</header>
<div class='w3-container'>
<form class='w3-container' action='home.php' method='GET'>
<p><input type='text' class='w3-input' name='post_comment' placeholder='Whats happening there...'/></p>
<p><button class='w3-button w3-black'>Post</button></p>
</form>
</div>
<footer class='w3-container w3-teal'>
<p>nothing here</p>
</footer>
</div>
</div>
</div>
</div>";
}
}
Hey I need to know how to post the information to another php page using javascript to provide a preview table.
Here's my HTML that has a onchange tag that sends the productID to the function.
<form action="Home.php" method="Post">
<div>
<p>
<span class="text">Please Select a product:</span>
<select id="Select_Product" name="Select_Product" onchange="productInfo(this.value)" class="select">
<?php
//setting the select statement and running it
$search = "SELECT * FROM Library.Products order by Name";
$return = mysql_query($search);
//echo "<select id=Select_Product name=Select_Product onchange=productInfo(this.value) class=select>";
while ($row = mysql_fetch_array($return)) {
echo "<option value='" . $row['ProductID'] . "' selected='selected'>".$row['Name'] . "</option>";
}
?>
</select>
</p>
<table>
<tr>
<td>
<input name="action" type="submit"class="button" id="button_Add" value="Add"/>
</td>
<td>
<input name="action" type="submit" class="button" id="button_Remove" value="Remove"/>
</td>
<td>
<input name="action" type="submit" class="button" id="button_empty" value="Empty"/>
</td>
</tr>
</table>
</div>
From there I want it to send it to catalogue.php.
<script>
function productInfo(key) {
//Send key to catalogue.php
}
</script>
If I can get the other page to get that variable I can run a MYSQL command to get the information. Here is what catalogue.php looks like at the moment.
<?php
$sql = "SELECT Name, Price FROM Library.Products WHERE ProductID = " . $product_id;
echo "<table border=\"1\" padding=\"3\" width=\"650px\"><tr><th>Name</th><th>Description</th><th>Price</th><th width=\"80px\">Image</th></tr>";
echo "<tr>";
echo "<td>" .$product_id . "</td>";
echo "<td> Hi</td>";
echo "<td></td>";
echo "<td align=\"center\"><img alt=\"\" src=\"productImages/".$product_id.".jpg\ width=\"120\" height=\"120\"/></td>";
echo "</tr>";
echo "</table><br>";
document.
?>
So in a sense I want to turn the key in productInfo(key) to be assigned to the variable $product_id in catalogue.php. Thanks for helping.
You can add an invisible form :
<script>
function productInfo(key) {
//Send key to catalogue.php
document.getElementById( "key" ).value = key;
document.getElementById( "frm" ).submit(); // SUBMIT FORM.
}
</script>
<form action="catalogue.php" method="post" id="frm"
style="display:none" target="_blank">
<input type="text" id="key" name="key"/>
</form>
catalogue.php needs one little change :
<?php
$product_id = $_POST[ "key" ]; //<================== VALUE FROM THE INVISIBLE FORM.
$sql = "SELECT Name, Price FROM Library.Products WHERE ProductID = " . $product_id;
echo "<table border=\"1\" padding=\"3\" width=\"650px\"><tr><th>Name</th><th>Description</th><th>Price</th><th width=\"80px\">Image</th></tr>";
echo "<tr>";
echo "<td>" .$product_id . "</td>";
echo "<td> Hi</td>";
echo "<td></td>";
echo "<td align=\"center\"><img alt=\"\" src=\"productImages/".$product_id.".jpg\ width=\"120\" height=\"120\"/></td>";
echo "</tr>";
echo "</table><br>";
document.
?>
Or you can use Ajax :
html file
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax ( key ) {
$.ajax( { type : 'POST',
data : { 'param' : key },
url : 'catalogue.php',
success: function ( data ) {
document.getElementById( "my_div" ).innerHTML = data;
},
error: function ( data ) {
alert( "error" );
}
});
}
function productInfo( key ) {
//Send key to catalogue.php
myAjax( key );
}
</script>
</head>
<body>
<button onclick="productInfo('123')">Click here to get the data</button>
<div id="my_div">
- data will show here -
</div>
</body>
</html>
catalogue.php
<?php
$key = $_POST[ "param" ];
echo "<table border='1'>" .
" <tr>" .
" <td>$key</td>" .
" <td>ABC</td>" .
" </tr>" .
"</table>";
?>
So I've made a database where people can upload pictures to. The pictures are linked to a place which is linked to a category.
I'm trying to create a gallery page that displays all the images, and then the categories available. When you click on a category it's meant to show all the pictures for that category.
I've got my categories in my database as well, which I'm using php to echo out:
<?php
include('includes/connectdb.php');
/* Selects id and name from the table 'category' */
$query = "SELECT id, name FROM category";
$result_category = mysqli_query($dbc,$query);
?>
<h1>Category</h1>
<!-- iterate through the WHILE LOOP -->
<?php while($row = mysqli_fetch_array($result_category)): ?>
<!-- Echo out values {id} and {name} -->
<button name="category[]" value=" <?php echo $row['id']; ?> "><?php echo $row['name'] . '<br />'; ?></button>
<?php endwhile; ?>
When a button is clicked I need it to run this php:
<?php
if(isset($_POST['category[]'])){
displayimage();
function displayimage()
{
$con=mysql_connect("localhost","root","");
mysql_select_db("ssdb",$con);
$qry="SELECT pictures.name, pictures.image, pictures.place_id
FROM pictures
INNER JOIN sted
ON pictures.place_id = sted.id
INNER JOIN placecategory
ON sted.id = placecategory.place_id
INNER JOIN category
ON placecategory.category_id = category.id
WHERE placecategory.category_id = $row['id']";
$result=mysql_query($qry,$con);
while($row = mysql_fetch_array($result))
{
//var_dump($row);
echo '<img height="300" width="300" src="data:image;base64,'.$row["image"].' "> ';
echo '<p style="display:inline-block">'.$row["name"].' </p> ';
}
mysql_close($con);
}
}
?>
I found out that it should be possible with ajax, so I added the following to my ajax.php file:
<?php
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'category':
category();
break;
}
}
function category() {
displayimage();
function displayimage()
{
$con=mysql_connect("localhost","root","");
mysql_select_db("ssdb",$con);
$qry="SELECT pictures.name, pictures.image, pictures.place_id
FROM pictures
INNER JOIN sted
ON pictures.place_id = sted.id
INNER JOIN placecategory
ON sted.id = placecategory.place_id
INNER JOIN category
ON placecategory.category_id = category.id
WHERE placecategory.category_id = $row['id']";
$result=mysql_query($qry,$con);
while($row = mysql_fetch_array($result))
{
//var_dump($row);
echo '<img height="300" width="300" src="data:image;base64,'.$row["image"].' "> ';
echo '<p style="display:inline-block">'.$row["name"].' </p> ';
}
mysql_close($con);
}
exit;
}
?>
And this to my gallery.php file where I'm displaying the pictures and categories.
<script>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert("action performed successfully");
});
});
});
</script>
And lastly I changed my button to be
<?php while($row = mysqli_fetch_array($result_category)): ?>
<!-- Echo out values {id} and {name} -->
<input type="submit" class="button" name="category[]" value=" <?php echo $row['id']; ?> "><?php echo $row['name'] . '<br />'; ?>
<?php endwhile; ?>
I'm linking to the jquery library and I've tested the SQL statement that I need to run, and it works when I specify what the placecategory.category_id is.
Im trying to get a value of an input into my buttons action url before the button is pushed.
I need to get the value of:
id="qty<?php echo $i;?>"
Into where it says:
<?php echo VALUE OF $qtyforaction; ?>
My Code is:
<?php $i = $_product->getId();?>
<form action="<?php echo $this->helper('checkout/cart')->getAddUrl($_product); ?>" method="post" id="product_addtocart_form_<?php echo $_product->getId()?>"<?php if($_product->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>
<input type="text" name="qty" id="qty<?php echo $i;?>" maxlength="12" value="1" title="Qty" class="cartnum" />
<?php $qtyforaction = 'qty'.$i; ?>
<?php echo $qtyforaction; ?>
<button type="button" class="addtocartbutton button btn-cart" onclick="setLocation('<?php echo $this->helper('checkout/cart')->getAddUrl($_product); ?>qty/<?php echo VALUE OF $qtyforaction; ?>')" ><span><span>Order Again</span></span></button>
</form>
Would I have to use javascript to get it into the url string? My javascript is a bit ropey, would something like this work?
<script type="text/javascript">
var something= document.getElementById('<?php echo $qtyforaction;?>');
</script>
UPDATE WITH FULL CODE:
<?php
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
/* Get the customer data */
$customer = Mage::getSingleton('customer/session')->getCustomer();
/* Get the customer's email address */
$customer_email = $customer->getEmail();
}
$collection = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('customer_email', array(
'like' => $customer_email
));
$uniuqProductSkus = array();
foreach ($collection as $order) {
$order_id = $order->getId();
$order = Mage::getModel("sales/order")->load($order_id);
$ordered_items = $order->getAllItems();
foreach ($ordered_items as $item)
{
if (in_array($item->getProduct()->getSku(), $uniuqProductSkus)) {
continue;
} else {
array_push($uniuqProductSkus, $item->getProduct()->getSku());
$_product = Mage::getModel('catalog/product')->load($item->getProductId());
$product_small_image_path = Mage::helper('catalog/image')->init($_product, 'small_image')->resize(200);
$product_thumbnail_path = Mage::helper('catalog/image')->init($_product, 'small_image')->resize(150);
$summaryData = Mage::getModel('review/review_summary')->load($item->getProductId());
echo "<li>";
echo "<div class='previous-name'><p><a style='color:black; font-weight:bold; font-size:14px;' href='" . $_product->getProductUrl() . "'>";
echo $item->getName() . "</a></p></div>";
echo "<div class='previous-image'><a href='" . $_product->getProductUrl() . "'>";
echo "<img src='" . $product_small_image_path . "' />";
echo "</a></div>";
echo "<div class='previous-rating'>";
echo "<p><a style='color:black; font-weight:bold; font-size:14px;' href='" . $_product->getProductUrl() . "#product_tabs_review_tabbed'>Review this beer now</a></p>";
echo $summaryData->getRatingSummary() . '% Would buy again <br/>';
echo "<div class='rating-box' style='float:left;'>";
echo "<div class='rating' style='width:" . $summaryData->getRatingSummary() . "%'></div></div>";
echo "</div>";
/**echo "<div class='previous-button'>";
echo '<button type="button" title="Add to Cart" class="button btn-cart" onclick="setLocation(\'';
echo $this->helper('checkout/cart')->getAddUrl($_product);
echo '\')"><span><span>Order Again</span></span></button>';
echo "</div>";**/
?>
<?php $i = $_product->getId();?>
<div class='previous-button'>
<form action="<?php echo $this->helper('checkout/cart')->getAddUrl($_product); ?>" method="post" id="product_addtocart_form_<?php echo $_product->getId()?>"<?php if($_product->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>
<input type="text" name="qty" id="qty<?php echo $i;?>" maxlength="12" value="1" title="Qty" class="cartnum" />
<?php $qtyforaction = 'qty'.$i; ?>
<script type="text/javascript">
var xy = document.getElementsByTagName("input")[0].getAttribute("qty");
var x = "<button type='button' class='addtocartbutton button btn-cart' onclick='setLocation()'><span><span>Order Again</span></span></button>";
document.getElementById("buttonaddcart").innerHTML = x;
</script>
<div id="buttonaddcart">
<button type="button" class="addtocartbutton button btn-cart" onclick="setLocation('<?php echo $this->helper('checkout/cart')->getAddUrl($_product); ?>qty/')" ><span><span>Order Again</span></span></button>
</div>
</form>
</div>
<?php
echo "<div class='previous-clear'></div>";
echo "</li>";
}
}
}
?>
You need to get the value of the id attribute:
var x = document.getElementsByTagName("input")[0].getAttribute("id");
But how do you plan on using PHP to echo out this variable if PHP is loaded and done with before Javascript even comes into play? You could use Javascript though to display this variable on the page if that's all you needed.
If you had something in your HTML to target, you could do it like this:
document.getElementById("result").innerHTML = x;
But anyways, get the action attribute value...
var y = document.getElementsByTagName("form")[0].getAttribute("action");
Then set the action attribute to this + the qty...
document.getElementsByTagName("form")[0].setAttribute("action", x + y);
That should work for you, if not, try wrapping x + y in additional parentheses...("action", (x + y));
I am creating a cms and am using php to dynamically create jquery on the fly. The first below works fine when the php renders the jquery inlce in my code but the second only works if I place on my js function script which is called into the header of the page:
# start index video row
echo '<script type="text/javascript">';
echo "$('#indexVid').fancybox({"; echo " \n";
echo "'width' : '75%',"; echo " \n";
echo "'height' : '75%',"; echo " \n";
echo "'autoScale' : true,"; echo " \n";
echo "'transitionIn' : 'elastic',"; echo " \n";
echo "'transitionOut' : 'elastic',"; echo " \n";
echo "'type' : 'iframe'"; echo " \n";
echo "});"; echo " \n";
echo '</script>';
# open help
echo '<script type="text/javascript">';
echo '$("#open_testing").click( function(){ $("#info_testing").css("display","block"); } );'; echo " \n";
echo '$("#close_testing").click( function(){ $("#info_testing").css("display","none"); } );'; echo " \n";
echo '</script>';
$name = 'testing';
$this_label = 'Learn about Site Settings';
$info = 'Site Settings are variable aspects of the site which are common to all or most all of the pages on the site such as copyright information and such, or they are miscellaneous variables necessary to a specific aspects of the site such as the send mail limitation. To find out more about each click on the info icon.';
<p id="open_'.$name.'" class="info-link"><i class="icon-info-sign"></i> '.$this_label.'</p>
<div id="info_'.$name.'" class="hide info-wrap">
<h3>'.$this_label.'</h3>
echo $info;
<p class="center"><a id="close_'.$name.'" class="button small" title="Close Info Panel">
<i class="icon-remove-sign"> </i> Close</a></p>
</div>
The html is above
$("#open_testing").click( function(){ $("#info_testing").css("display","block"); } );
$("#close_testing").click( function(){ $("#info_testing").css("display","none"); } );
which is working if the above jquery is in the header but not if inline in the code
can some explain why? thanks