passing a MySQL data as string through PHP to javascript - javascript

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

Related

Can't pass php variables in parameter in a HTML onclick

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>

When a month is clicked on it only prints 1 of the rows from database rather than all rows linked to that month

So I have a calendar on my webpage. When a month is clicked, it should print all data linked to that month. However with the current code I have it does not do this. So for example, if I click on January it will print the first January from the database. However, when I click February it should print the data from February but it prints the second piece of data linked to the month January. I want it to print all data from January when I click January and when I click February it should print all data from February etc.
Below is my HTML:
<div class="calander-container">
<div class="months">
<p class="months-text">January</p>
</div>
<div class="months">
<p class="months-text">February</p>
</div>
<div class="months">
<p class="months-text">March</p>
</div>
<div class="months">
<p class="months-text">April</p>
</div>
<div class="months">
<p class="months-text">May</p>
</div>
<div class="months">
<p class="months-text">June</p>
</div>
<div class="months">
<p class="months-text">July</p>
</div>
<div class="months">
<p class="months-text">August</p>
</div>
<div class="months">
<p class="months-text">September</p>
</div>
<div class="months">
<p class="months-text">October</p>
</div>
<div class="months">
<p class="months-text">November</p>
</div>
<div class="months">
<p class="months-text">December</p>
</div>
</div>
My PHP:
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<div class='rallyPrint'>";
echo "<h2>" . $row['rallyVenue'] . " in " . $row['month'] . " " . $row['year'] . "</h2>";
echo "<h4>Event: ". $row['rallyEvent'] . " </h4>";
echo "<h3>Your Marshall(s): " . $row['rallyMarsh'] . "</h3>";
echo "<h4>When? ". $row['rallyDate'] . " </h4>";
echo "<p>" . $row['rallyDesc'] . "</p>";
echo "<p>How much? ". $row['rallyCost'] . " </p>";
echo "<p>How long? ". $row['rallyNights'] . " Nights</p>";
echo "<p>Pitch Limit? ". $row['pitchLimit'] . "</p>";
echo "<p>Phone Number: 0". $row['phoneNo'] . " </p>";
echo "<p>Email: <a href='mailto:". $row['email'] . "'> ". $row['email'] ."</a></p>";
echo "<p>Please make sure you to contact ". $row['rallyMarsh'] . " for more information.</p>";
if(isset($_SESSION['loggedin'])){
echo "<a href='' id='". $row['rallyId'] . "' class='trash'>Delete</a>";
}
echo "</div><br>";
}
} else {
echo "<h2 align='center'>Rallies Currently Not Available!</h2>";
}
My Javascript:
document.querySelector('.calander-container').addEventListener('click', (e) => {
const months = e.target.closest('.months');
if (!months) {
return;
}
const thisIndex = [...months.parentElement.children].indexOf(months);
const rallyPrint = document.querySelectorAll('.rallyPrint');
rallyPrint.forEach((div) => {
div.style.display = 'none';
});
rallyPrint[thisIndex].style.display = 'block';
});
There's some flaw in logic...PHP returns several divs with class .rallyPrint, then you set them all to 'none', and just one of them you set to 'block'
And the index you set to block you get from months array, but applies it to rallyPrint elements Gut Knows Why
May be you should add class which represebts month to your .rallyPrint divs and display or hide depends on this class

Get input before submitting to insert into action url

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));

why does this one jquery work and the other does not

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

PHP Combobox last selected same after changing page

Can all help me with my php. i can keep my combobox not changing after reload. but after im changing a page in my paging. it not work can you help me?
THIS IS MY PHP.
PHP
Category :
>All
>Computer
>Peripheral
>Gadget
";
else
echo "";
echo " Category : ".$baris["Category"]."";
echo " ";
echo " ";
echo " ";
echo " ";
echo " Nama : ".$baris["Nama"]. "";
echo " Harga : Rp. ".$newprice. "";
echo " Keterangan : ".$baris['Keterangan']."";
echo " ";
echo "";
echo "";
$no=$no+1;
}
?>
$i ";
}
?>
</div>
<div class="footer">
(C)
</div>
</div>
</body>
</html>
I think the problem lies on the line (roughly 101;):
for ($i=1;$i<=$jum_page;$i++){
echo "<a href = index.php?page=$i>$i</a> ";
}
The middle line should read:
echo "<a href=index.php?page=$i&choice=$selected_choice>$i</a> ";
This will ensure that the combo box choice is preserved across pages. Is this problem you were experiencing?

Categories

Resources