Using simple PHP and Javascripet (no JSON, AJAX, or anything fancy) I am trying to echo a javascript onClick event function. This onClick function takes two strings, and as a start I want to see those strings using the "alert" function. Below is my code in the html/php file::
<DIV id="show">
!-- few more lines here -->
<?PHP
$CONN = mysqli_connect($SERVER_w, $USER_w, $PASS_w, $DBNAME_w);
$SQL = "SELECT * from COUNTRYTABLE";
$RESULT = mysqli_query($CONN, $SQL);
$NUM_RECORDS = mysqli_num_rows($RESULT);
echo "<BR>";
for($x = 1; $x<=$NUM_RECORDS; $x++)
{ $ROW = mysqli_fetch_array($RESULT, MYSQLI_ASSOC);
//the main line::
echo "<button onClick=\"Show_Pair(\"" . $ROW['CONTINENT'] . "\",\"" .
$ROW['COUNTRY'] . "\")\"> Show! </button> <BR>";
}
mysqli_free_result($RESULT);
mysqli_close($CONN);
?>
</DIV>
The Javascript function is a simple one:
function Show_Pair_In_Alert(CON, CTR)
{
alert(CON + CTR);
}
When the PHP evaluates, the HTML looks like follows:
<DIV id="show">
<p>CONTINENT - COUNTRY Linkage: </p><BR><BR><button
onClick="Show_Pair_In_Alert("AFRICA_EAST","Comoros")">Show</button> <BR>
<button onClick="Show_Pair_In_Alert("AFRICA_EAST","Eritrea")">Show</button>
<BR>
<button onClick="Show_Pair_In_Alert("AFRICA_EAST","Kenya")">Show</button>
<BR>
</DIV>
HOWEVER, when I look at the developer tools/console thingy in Chrome, I see the following error::
Uncaught SyntaxError: Unexpected token }, and this error occurrs just above the end of the and below the last button.. theres a red circle with a yellow cross in it.. as can be seen in the image below
Would appreciate any feedback.. just to reiterate.. im not using any JSON, AJAX, anything... just trying to achieve something fairly complex for my begineer level :P.. thank you very much for your assistance in advance!!
Related
I have a odd question i cannot find the answer to, which probably means it is impossible. The reason i ask is i am creating a food delivery website. In the admin panel of my website administers are able to input restaurant details and menus. Part of the details is how much a customer must spend before they can checkout for delivery. so i want to be able to deactivate the checkout button, but when they met the minimum order fee the button activates.
This is my first time attempting anything like this, i have looked all over and i can only find posts or tutorials on how to deactivate then activate a button when a certain event takes place using javascript or jQuery and i know i would have to get the minimum order fee from the DB.
The only logical answer is to combine them.
I am trying to achieve something similar to this...
Shopping
I followed a tutorial to do this, it is a mini fixed shopping cart, which is on the same page as the shopping cart. It redirects to shopping_cart.php from product_page.php. Most aspects on product_page.php is dynamically made.
mysqli_stmt_execute($runn_query);
while ($get_row = mysqli_fetch_array($runn_query)) {
echo "<div id='prods_ere'>";
$item_sub = $get_row['Product_Price'] * $value;
echo $value . ' x ' .$get_row['Product_Name']. ' # £' . $get_row['Product_Price'] . '<a id="minus" class="buttons" href="Shopping_cart.php?remove=' . $Product_Id . '">-</a> <a id="plus" class="buttons" href="Shopping_cart.php?add_item=' . $Product_Id . '"> + </a> <a id="del" class="buttons" href="Shopping_cart.php?delete=' . $Product_Id . '">✖</a> </br><p id="sub">£' . $item_sub . '</p>';
echo "<br>";
echo "<br>";
echo "<hr id='shopp_dashed'>";
echo "</div>";
}
}
//creating subtotal
$sub_total += $item_sub;
$num_items += $value;
$total += $sub_total;
}
}
//subtotal and empty cart message
if ($sub_total == 0) {
echo "Ouch.. its empty in here";
} else {
echo "<div id='grey'>";
echo"Subtotal (excl delivery)";
echo "<br/>";
echo "<div id='sub_t'>";
echo '£' . number_format($sub_total, 2);
echo "</div>";
echo "<br/>";
echo"Items";
echo "<br/>";
echo "$num_items";
echo "<br/>";
echo "</div>";
echo "<div id='total'>";
echo"Total: ";
echo "$total";
echo "</div>";
}
Products page
<div id="prods_here">
<!-- PLACE PRODUCTS HERE-->
<?php cart(); ?>
</div>
Well, I'm not sure how you're keeping track of the customer's order but let's say you're keep track of it in a counter, say, totalOrderAmt. As they are making changes to the order, keep this updated and add a condition to the page, that when the totalOrderAmt >= checkOutAmt, enable the checkOut button.
I can add more details if you post some code, may be.
If you're using PHP you could load a JavaScript object on each restaurant page that basically makes a minimum_order_price variable available on the DOM for the JavaScript to handle the rest:
<html>
<head>
...
</head>
<body>
<h1>Restaurant X</h1>
<p>Minimum order: <span id="_restaurantMinimumOrder"></span></p>
<input id="submit" type="submit" class="disabled" value="Checkout" disabled>
<script type="text/javascript">
<?php
echo "window.RestaurantDetails = {}";
echo "window.RestaurantDetails.minimum = $RestaurantMinimumOrder";
?>
</script>
</body>
</html>
In this instance, $RestaurantMinimumOrder is something you configure and setup on PHP (I am not sure what you're setup is so I went with a variable name). From there, when the page is parsed from the server, the PHP will echo out that JavaScript. Once the page loads, window.RestaurantDetails will be available for the rest of your JavaScript to use. I've also included an example implementation:
<script type="text/javascript">
// set price on the DOM
var priceEl = document.getElementById('_restaurantMinimumOrder');
priceEl.textContent = window.RestaurantDetails.minimum;
// ensure submit button is disabled initially
var submitEl = document.getElementById('submit');
submitEl.disabled = true;
</script>
From here, if you're using jQuery you can easily adjust the state of the submit button based on whatever logic flow you have setup. Let me know if you have more questions. Best of luck! Cheers ~
I have a problem, trying to create a button with Ajax/Php which is to appear on my main page and is supposed to have a onclick function. To be more specific, I end up in a while loop, which fetches through the rows of my mySQL-table and displays the following:
echo "<table>";
while($result == true && $a <= 15){
$res = $result["uberschrift"];
echo "<tr id='$res'>";
echo "<td>".$a."</td>";
echo "<td>".$res."</td>";
echo "<td>"."<button id='b_löschen' onclick='k_löschen($res)'> löschen </button>"."</td>";
echo "</tr>";
$result = $stmt->fetch();
$a++;
}
echo "</table>";
In fact, this works quite well, and on my main page the string contained in $result["uberschrift"] is displayed properly. However, if I call the function k_löschen with $res as shown above, it will not take the String but a certain
[object HTMLTablerowElement] as input, which naturally causes an Error. Can someone tell me how to change the code so that the function actually takes the string as it's input?
You have issues with your quotes. Also you could tell us what $res typically contained.
I would do this
echo "<tr id=\"".$res."\">";
echo "<td><button id='b_löschen' onclick='k_löschen(\"".$res."\")'>löschen</button></td>";
I've this PHP page:
<?php
$lines = array();
$lines[] = "I am happy";
$lines[] = "I'm happy";
foreach ($lines as $line){
$message = htmlspecialchars($line);
?>
<div onclick="alert('<?=$message?>');"><div>
<?php
}
It generates this HTML results:
<div onclick="alert('I am happy');"><div>
<div onclick="alert('I'm happy');"><div>
This code seems to be correct, however, clicking on second "div" element an error occurs.
The ' char is equivalent to ' and javascript generates an error:
alert('I'm happy');"
I solved this problem adding to code addslashes() PHP function:
$lines = array();
$lines[] = "I am happy";
$lines[] = "I'm happy";
foreach ($lines as $line){
$message = htmlspecialchars(addslashes($line));
?>
<div onclick="alert('<?=$message?>');"><div>
<?php
}
Correct results:
<div onclick="alert('I am happy');"><div>
<div onclick="alert('I\'m happy');"><div>
My question:
Is this the right/best solution?
Which is the best practice to manage this kind of problems?
Don't try to generate JavaScript string literals by mashing strings together. json_encode will do it for you along with all the escaping (', ", new lines, etc) that you need for JS. It is preferred to addslashes because it is designed for the target data format and isn't generic (generic escaping solutions tend to miss things).
Encode data for HTML attribute values as the last thing you do to the data before putting it in the value. Don't encode for HTML before putting data into JavaScript.
foreach ($lines as $line){
$message = json_encode($line);
$javascript = "alert($message)";
$html = htmlspecialchars($javascript);
?>
<div onclick="<?= $html ?>"><div>
<?php
}
That said, a modern approach would generally keep the JavaScript separate and store the data in a data attribute.
You should also avoid putting click events on div elements, they aren't designed to be user controls so they can't (without more mucking about) be triggered by (for example) focusing the element and pressing enter which creates accessibility problems.
foreach ($lines as $line){
$html = htmlspecialchars($line);
?>
<button type="button" data-message="<?= $html ?>">...</button>
<?php
}
with
<script>
function buttonAlert(event) {
var message = event.target.dataset.message;
if (message) {
alert(message);
}
}
addEventListener("click", buttonAlert);
</script>
Your correct result is actually wrong, and would output I'm happy instead of I'm happy.
Asside from that, yes your solution will work and i don't see any problem with that way of doing in your particular context.
You can use below code
<?php
$lines = array();
$lines[] = "I am happy";
$lines[] = "I'm happy";
foreach ($lines as $line){ ?>
<div onclick="alert('<?=addslashes($line); ?>');"><div>
<?php } ?>
I'm building a web App for a friend, this is my first async site and I'm learning lots of cool stuff, but there are some details that make me struggle.
This is the general idea:
This simple app gets specific tables from a database using PHP and jQuery and shows them asynchronously on the page. There's this specific table (a waitlist) that shows all atributes from all entries on the table plus a small button that SHOULD delete that specific entry, the PHP code for the creation of the table is as follows:
<?php
include("con.php");
$result = mysqli_query($c,"SELECT * FROM waitlist");
echo "<thead>";
echo "<tr>";
echo "<th>Nombre</th><th>Sillas</th><th>Hora de Llegada</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while ($places = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>". $places ['NAME']."</td>";
echo "<td>". $places ['CHAIRS']."</td>";
echo "<td>". $places ['CREATED']."</td>";
echo '<td>
<button class="btn btn-default" type="submit" name=' . $places ['ID'] . ' id="deleteWaitlist">X</button>
</td>';
echo "</tr>";
}
echo "</tbody>";
mysqli_free_result($result);
?>
This is the table schema:
CREATE TABLE WAITLIST (
ID MEDIUMINT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(255),
CHAIRS VARCHAR(255),
CREATED DATETIME NOT NULL,
PRIMARY KEY(ID)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
What is the best way of having the button delete the entry it apears on? The function refreshes the table every few seconds so deleting it from the database is all I need. I also have an incomplete PHP function that gets called on buttonpress that shold delete the entry, but Im unsure as to how to complete it. Here it is:
<?php
include("con.php");
$sql = "DELETE FROM waitlist WHERE id='.$_POST[id]'.";
mysqli_query($c,$sql);
?>
I need to replace the $_POST[name] with an identifier for the row, this is my problem. What's the best way of doing this? Can I pass it somehow though the jquery.ajax() call? Do I need a new table attribute ID? I'm sure the "this" keyword can be used somewhere. Is PHP and ajax even the best way of doing it?
Ajax writes the table on "#result_table", here's the relevant code if it's needed:
<div class="row">
<div class="col-lg-12" id="table_container">
<table class="table table-striped" id="result_table">
</table>
</div>
</div>
</div>
EDIT: I updated the code as recomended by #vnponce
This is the code for the ajax call:
$("#deleteWaitlist").click(function(){
// Get the varible name, to send to your php
var i = $(this).attr('name');
$.post({
url: 'deleteWaitlist.php',
data: { id : i},
success: function(result){
// do some code here
// here yo can see 'result' response of YOUR_PHP_FILE
console.log(result);
}
});
});
After fiddling with the code I got rid of all errors and updated the post, but the entries are still not getting deleted.
The best way is creating an ID identifier in your table, then this identifier can be added in your 'Delete' button.
The button trigger a function that send ID, and your PHP file recive it and delete de data comparing the ID.
The identifier can be added in table schema ( i don't know if it is the rigth code, I always made in phpMyAdmin )
CREATE TABLE WAITLIST (
ID MEDIUMINT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(255),
CHAIRS VARCHAR(255),
CREATED DATETIME NOT NULL
);
First add the ID in delete photo.
echo '<td>
<button class="btn btn-default" type="submit" name=' . $places ['ID']. ' "id="deleteWaitlist">X</button>
</td>';
The ajax
$("#deleteWaitlist").click(function(){
// Get the varible name, to send to your php
var i = $(this).attr('name');
$.post({url: "YOUR_PHP_FILE.php", {id: i}, success: function(result){
// do some code here
// here yo can see 'result' response of YOUR_PHP_FILE
// console.log(result);
}});
});
Now your PHP with ID
<?php
include("con.php");
$sql = "DELETE FROM waitlist WHERE id='.$_POST[id]'.";
mysqli_query($c,$sql);
?>
Well I hope help. If i have an error or you have a question let me know.
UPDATE*
Maybe there's an error deleteWaitlist.php , you can return error if it exist.
<?php
include("con.php");
$sql = "DELETE FROM waitlist WHERE id='.$_POST[id]'.";
if ( ! mysqli_query($c,$sql) )
{
return "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
I'm dealing with this problem since 2 days and I haven't found a solution.
Here's the tooltip script that I'm using: http://iamceege.github.io/tooltipster/
It works fine, I'm able to show data in HTML format, no problem.
But the problem comes when I want to echo a HTML code from a function that was written by me. The output of the function isn't showed in the tooltip, but outside it.
Here's my function:
public function showProducts($uId, $wid){
$sql1 = "SELECT pids FROM wishlists WHERE uid='$uId' AND id='$wid'";
$q = mysql_query($sql1) or die(mysql_error());
while($data=mysql_fetch_array($q)){
$dbprods = $data['pids'];
$prods = explode(",", $dbprods);
for($i = 0; $i < count($prods); $i++){
$id=$prods[$i];
$q=mysql_query("SELECT * from products where id='$id'");
while($bd = mysql_fetch_array($q)){
echo ''.$bd['name'].'<br />';
}
}
}
}
If I'm typing return $bd['id'];, the tooltip is fine. The problem comes only with that HTML output. The tooltip and function call is this echo '# <a class="tooltip" title="Products <br />'.$this->showProducts($uid, $wid).'">'.$data['name'].'</a><br />';
I have also tried to modify the my function into something like
while($bd = mysql_fetch_array($q)){ ?>
<?php echo $bd['name'];?><br />
<?php }
but still no result. Does anyone helps me out?