Using JavaScript inside PHP code [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Ok so I have a booking system that I am working on and I have events created in a table which gets populated by PHP if the admin adds new events. I would like to run a script if the user tries to book an event and then submit the form to php. I would like to do this because I want to know if the user has a voucher and wants to pay either by card or via paypal.
Here is the table screenshot, sorry only a link I need 10 rep points.
The PHP code that creates the tables:
<?php
$con = mysql_connect("localhost","root","");
if(!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("flexiflash", $con);
echo "<thead>";
echo "<tr>";
echo "<th>ID</th>";
echo "<th>Venue</th>";
echo "<th>Event</th>";
echo "<th>Date</th>";
echo "<th>Time</th>";
echo "<th></th>";
echo "</tr>";
echo "</thead>";
$result = mysql_query("SELECT * FROM events");
while($row = mysql_fetch_array($result))
{
echo "<tbody>";
echo "<form class='table-form' action='book_event.php' method='post' onsubmit='return check()'>";
echo "<tr>";
echo "<td>" . $row['Event_ID'] . "</td>";
echo "<td>" . $row['Event_Venue'] . "</td>";
echo "<td>" . $row['Event_Name'] . "</td>";
echo "<td>" . $row['Event_Date'] . "</td>";
echo "<td>" . $row['Event_Time'] . "</td>";
echo "<td><input type='submit' class='sub_btn' name='submit' value='Book now'></td>";
echo "</tr>";
echo "</form>";
echo "</tbody>";
}
mysql_close($con);
?>
IF YOU NEED ANY MORE INFO LET ME KNOW

PHP is backend. JavaScript is frontend. What do you want to do in the frontend? Perform the check() function? If so, just put this
<?php
echo '<script>
function check() {
//do something
return true;
}
</script>';
?>
before the table. This should do it. But it's kinda ugly :)

Related

Make cell a clickable link in Bootstrap using URL stored as string in database

I have a mysql database table called "names" as per below :
All columns (other than id) are stored as varchar
There is a full .php URL stored in Column "Full Name" for each record but I am getting a stackoverflow code error when using the URL in table below.
id
First Name
Surname
Full Name
Profile
1
John
Smith
John Smith
.PHP URL stored as a text string
2
Jane
Doe
Jane Done
.PHP URL stored as a text string
3
Prakash
Singh
Prakash Singh
.PHP URL stored as a text string
I have some mysql and php that returns the records for the first four columns and puts them into a bootstrap table :
<?php
// Include config file
require_once "conn.php";
// Attempt select query execution
$sql = "SELECT * FROM names";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo '<table class="table table-dark table-hover table-bordered table-striped">';
echo "<thead>";
echo "<tr>";
echo "<th>#</th>";
echo '<th>First Name</th>';
echo "<th>Surname</th>";
echo '<th>Full Name</th>';
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['First Name'] . "</td>";
echo "<td>" . $row['Surname'] . "</td>";
echo "<td>" . $row['Full Name'] . "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo '<div class="alert alert-danger"><em>No records were found.</em></div>';
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close connection
mysqli_close($link);
?>
What I would like to do:
Make all cell's in Column "Full Name" to be independently clickable.
Onclick, I would like to take the user to the respective profile URL of the record id without opening a new page.
Attempts:
I added a class to the td for Full Name for an onclick event :
echo "<td class='clickme'>" . $row['First Name'] . "</td>";
This made only the first row of the table clickable.
I added some javascript for the class :
var myMap = document.getElementById("clickme");
myMap.onclick = function() {
var myVar = window.location.replace("https://www.stackoverflow.com");
};
This partially worked, the page refreshes and redirects to the URL provided. However, as each record has it's own URL (stored in the database) I'd like to retrieve the specific URL rather than input an absolute URL here.
Thanks alot in advance for any help rendered!
I never worked with php but in plane html js. you can pass your url through data attibute.
<td class='clickme' data-url="your_cell_url"> First Name </td>
and then in js file
var myMap = document.getElementById("clickme");
myMap.onclick = function() {
var url = this.dataset.url
var myVar = window.location.replace(url);
};
i think it may helps
Try:
echo "<td>" . $row['First Name'] . "</td>";
or if you're using get method for profile page it will look something like this:
echo "<td>" . $row['First Name'] . "</td>";

PHP: javascript alert, with value from sql query, into IF condition

With the following code, a popup table should appear with sql query data, only when retrieved records are greater than 1.
$sql = "SELECT * FROM pt_locations WHERE country = ('$countryCode') AND location = ('$cityCode')";
$result = $conn->query($sql);
$rowcount=mysqli_num_rows($result);
$message = "Records found: " . $rowcount . "<br /><br />";
if ($rowcount > 1) {
echo '<script language="javascript">';
echo 'alert' .$message;
foreach($result as $val){
$id_country = $val["country"] ;
$id_code = $val["code"] ;
$id_location = $val["location"] ;
$id_latitude = $val["latitude"] ;
$id_longitude = $val["longitude"] ;
echo "<table border='1' cellpadding='5'>";
echo "<tr>";
echo "<td><i><strong>ID Code</strong></i></td><td>";
echo $id_code."</td>";
echo "<td><i><strong>Country</strong></i></td><td>";
echo $id_country."</td>";
echo "<td><i><strong>Code</strong></i></td><td>";
echo $code."</td>";
echo "<td><i><strong>Location</strong></i></td><td>";
echo $id_location."</td>";
echo "<td><i><strong>Latitude</strong></i></td><td>";
echo $id_latitude."</td>";
echo "<td><i><strong>Longitude</strong></i></td><td>";
echo $id_longitude."</td>";
echo "</tr>";
echo "</table><br /><br />";
}
echo '</script>';
}
Recording counts are done correctly, but I can not make the popup appear in any way.
try this. Hope this help you.
$sql = "SELECT * FROM pt_locations WHERE country = ('country') AND
location = ('location')";
$result = $conn->query($sql);
$rowcount=mysqli_num_rows($result);
$message = "Records found: " . $rowcount;
if ($rowcount > 1) {
echo '<script language="javascript">';
echo 'alert("'.$message.'")';
echo '</script>';
while($val=mysqli_fetch_assoc($result)){
$id_country = $val["country"] ;
$id_code = $val["code"] ;
$id_location = $val["location"] ;
$id_latitude = $val["latitude"] ;
$id_longitude = $val["longitude"] ;
echo "<table border='1' cellpadding='5'>";
echo "<tr>";
echo "<td><i><strong>ID Code</strong></i></td><td>";
echo $id_code."</td>";
echo "<td><i><strong>Country</strong></i></td><td>";
echo $id_country."</td>";
echo "<td><i><strong>Code</strong></i></td><td>";
echo $code."</td>";
echo "<td><i><strong>Location</strong></i></td><td>";
echo $id_location."</td>";
echo "<td><i><strong>Latitude</strong></i></td><td>";
echo $id_latitude."</td>";
echo "<td><i><strong>Longitude</strong></i></td><td>";
echo $id_longitude."</td>";
echo "</tr>";
echo "</table><br /><br />";
}
}
There are some errors, because for logic you must put the alert at the end of the table complete, just for logic and after you put alert something without brakets and you open a script before the foreach loop and after the foreach loop you close the script, this is absolutley wrong, another error is in the $message, you are using br inside an alert javascript that isn't recognize as html but just like characters at the least you can use unicode \n\t not br, i used also a setTimeout,but works also without setTimeout.
Sometimes can result essential use javascript injection inside the php for example to autofill of some forms and input select or to call a change event from external compilation of other application that pass variables in get and need to autofill a form, but i think in this case is not necessary do a javascript injection you can print the total Records just in the page, btw...
The code under works
Bye
$message = "Records found: " . $rowcount." \\n\t\\n\t";
if ($rowcount > 1) {
foreach($result as $val){
//var_dump($val);
$id_country = $val["country"] ;
$id_code = $val["code"] ;
$id_location = $val["location"] ;
$id_latitude = $val["latitude"] ;
$id_longitude = $val["longitude"] ;
echo "<table border='1' cellpadding='5'>";
echo "<tr>";
echo "<td><i><strong>ID Code</strong></i></td><td>";
echo $id_code."</td>";
echo "<td><i><strong>Country</strong></i></td><td>";
echo $id_country."</td>";
echo "<td><i><strong>Code</strong></i></td><td>";
echo $code."</td>";
echo "<td><i><strong>Location</strong></i></td><td>";
echo $id_location."</td>";
echo "<td><i><strong>Latitude</strong></i></td><td>";
echo $id_latitude."</td>";
echo "<td><i><strong>Longitude</strong></i></td><td>";
echo $id_longitude."</td>";
echo "</tr>";
echo "</table><br /><br />";
}
$jvsVar = "<script type='text/javascript'>;setTimeout(function(){alert('$message');},100)</script>";
echo $jvsVar;
}

Oop check if database table is empty

I have a selector wich gets information from the database. But when my database table is empty, the selector still shows up like this:
However, when my database is empty. I don't want to show the selector. but a message that says something like: Database is empty! Add something.
My code for the selector:
$results = $database->Selector();
echo "<form name='form' method='POST' id='selector'>";
echo "<select name='train_name' id='train_name' multiple='multiple'>";
// Loop trough the results and make an option of every train_name
foreach($results as $res){
echo "<option value=" . $res['train_name'] . ">" . $res['train_name'] . "</option>";
}
echo "</select>";
echo "<br />" . "<td>" . "<input type='submit' name='Add' value='Add to list'/>" . "</td>";
echo "</form>";
The function:
function selector() {
$sql = "SELECT train_name, train_id FROM train_information ORDER BY train_name";
$sth = $this->pdo->prepare($sql);
$sth->execute();
return $sth->fetchAll();
}
EDIT:
Got this now:
$results = $database->Selector();
if(count($results) > 0) {
//Form etc here//
}else echo "nope";
It is working now! :D

Stuck in endless loop while creating buttons

I'm trying to create a website, where I can insert products with a button.
So for now I got one button which creates one div as a product box. When the button is clicked it becomes invisible, under this I can see the div now; and under the div, there's the next button which should be able to create one more divs (always the same way).
The problem is that I can't find any solution to do that. I always land in an endless loop.
If you're wondering about the mailer, the idea for the first step is, to send a mail as newsletter for every created product.
Here's my code:
<?php
echo "<form action='index.php' method='GET'>";
echo "<input type='submit' name='insert' id='insert' value='INSERT'>";
echo "</form>";
if ($_GET["insert"]) {
echo " <script language='JavaScript'> ";
echo "";
echo " ";
echo " document.getElementById('insert').style.visibility='hidden' ";
echo "";
echo "</script>";
echo " <div class='article'>";
echo "<h2>product</h2>";
echo "<p>";
echo "EXAMPLE";
echo "</p>";
echo "</div> ";
echo "<form action='index.php' method='GET'>";
echo "<input type='submit' name='ins ert' id='insert' value='INSERT'>";
echo "</form>";
//send mail
$message = "hello TEST!";
for ($i = 0; $i < $z; $i++) {
mail('' . $res[$i] . '', 'Newsletter', $message);
}
}
?>
You are hiding an "id=insert" item, and then creating a second "id=insert" item. So you get 2 identical id, which is not good.
You should "remove" the "id=insert" rather than "hide" it. jquery may help you on that.
(And so you may not need to remove the "id=insert" item, but rather "add" a new div "after" your last product).

Javascript/PHP redirect

Hello fellow programmers!
I'm working on a personal project (mainly to learn php/javascript) and have ran into an issue with redirection when clicking on a link. I have a bit of a strange situation on a tabbed page I've created and I think that may be what is causing my problem.
I'm trying to allow the user to click the (which due to css has made it look different than normal ) to redirect them to a new page with more details. I THINK that the second tag on my page is what is throwing me off because I have a form in it.
I have tried tons of different things like window.location.href="", location.href="", document.location="", etc... But the same thing always occurs. I am able to get both alert messages, so I know I am getting into my JavaScript (even when I put it into it's own .js file).
Anyway advice/help would be very helpful. Also, if anyone has a suggestion on cleaning this code up a bit, that would also be truly helpful.
Below is basically what I have.
Thanks in advance for your help!
<html>
<head>
<title>test site</title>
<link rel="stylesheet" href="test.css" type="text/css" media="screen" />
<script src="test.js" type="text/javascript"></script>
<script type="text/javascript">
function viewDetails(modelId){
alert(modelId);
window.location.href="new url?ModelID=" + modelId;
alert('redirecting would be way awesome...');
}
</script>
</head>
<body onload="load()">
<div id="tabbed_box_1" class="tabbed_box">
<h4>Navigation Tabs<small>Select a tab</small></h4>
<div class="tabbed_area">
<?php
mysql_connect('host','user','password');
mysql_select_db("database");
echo "<ul class='tabs'>";
echo "<li><a href='javascript:tabSwitch(1, 2);' id='tab_1' class='active'>Inventory</a></li>";
echo "<li><a href='javascript:tabSwitch(2, 2);' id='tab_2' >Add Project</a></li>";
echo "</ul>";
echo "<div id='content_1' class='content'>";
echo "<ul>";
$modelsSQL = "SELECT * FROM Model ORDER BY Name";
$modelsResult = mysql_query($modelsSQL);
while ($modelRow = mysql_fetch_array($modelsResult)){
$modelID = $modelRow[0];
$sqlAvailCount = "SELECT * FROM Project WHERE ModelID = " . $modelID . " AND Sold = 0";
$sqlSoldCount = "SELECT * FROM Project WHERE ModelID = " . $modelID . " AND Sold = 1";
$resultAvailCount = mysql_query($sqlAvailCount);
$resultSoldCount = mysql_query($sqlSoldCount);
$rowAvailCount = mysql_num_rows($resultAvailCount);
$rowSoldCount = mysql_num_rows($resultSoldCount);
echo "<li><a href='' onclick='javascript:viewDetails($modelID);'>" . $modelRow[1] . "<small>in stock: <value>"
. $rowAvailCount . "</value> sold: <value>" . $rowSoldCount . "</value></small></a></li>";
}
echo "</ul>";
echo "</div>";
echo "<div id='content_2' class='content'>";
echo "<form action='project_insert.php' method='post' name='projectAddForm'>";
echo "<table cellpadding='5'>";
// Project Model Selection
echo "<tr><td>";
echo "<label for='model'>Model</label>";
echo "</td><td>";
echo "<select name='model' style='width: 250px;'>";
echo "<option value='-1' selected>SELECT</option>";
$modelListSQL = "SELECT * FROM Model ORDER BY Name";
$modelListResult = mysql_query($modelListSQL);
while ($modelListRow = mysql_fetch_array($modelListResult)){
echo "<option value='" . $modelListRow['ID'] . "'>" . $modelListRow['Name'] . "</option>";
}
echo "</select>";
echo "</td></tr>";
// Project Material Selection
echo "<tr><td>";
echo "<label for='material'>material</label>";
echo "</td><td>";
echo "<select name='material' style='width: 250px;'>";
echo "<option value='-1' selected>SELECT</option>";
$materialListSQL = "SELECT * FROM Material ORDER BY Name";
$materialListResult = mysql_query($materialListSQL);
while ($materialListRow = mysql_fetch_array($materialListResult)){
echo "<option value='" . $materialListRow['ID'] . "'>" . $materialListRow['Name'] . "</option>";
}
echo "</select>";
echo "</td></tr>";
// Project Finish Selection
echo "<tr><td>";
echo "<label for='finish'>finish</label>";
echo "</td><td>";
echo "<select name='finish' style='width: 250px;'>";
echo "<option value='-1' selected>SELECT</option>";
$finishListSQL = "SELECT * FROM Finish ORDER BY Name";
$finishListResult = mysql_query($finishListSQL);
while ($finishListRow = mysql_fetch_array($finishListResult))
{
echo "<option value='" . $finishListRow['ID'] . "'>" . $finishListRow['Name'] . "</option>";
}
echo "</select>";
echo "</td></tr>";
// Project Craftsman Selection
echo "<tr><td>";
echo "<label for='craftsman'>craftsman</label>";
echo "</td><td>";
echo "<select name='craftsman' style='width: 250px;'>";
echo "<option value='-1' selected>SELECT</option>";
$craftsmanListSQL = "SELECT * FROM Craftsman ORDER BY FirstName";
$craftsmanListResult = mysql_query($craftsmanListSQL);
while ($craftsmanListRow = mysql_fetch_array($craftsmanListResult)){
echo "<option value='" . $craftsmanListRow['ID'] . "'>" . $craftsmanListRow['FirstName'] . " " . $craftsmanListRow['LastName'] . "</option>";
}
echo "</select>";
echo "</td></tr>";
//Project Description
echo "<tr><td>";
echo "<label for='description'>Description</label>";
echo "</td><td>";
echo "<input type='text' name='description' id='textArea' style='width:250px'>";
echo "</td></tr>";
// Project Selling Price
echo "<tr><td>";
echo "<label for='price'>Price</label>";
echo "</td><td>";
echo "<input id='price' name='price' type='number' style='width:150px'>";
echo "</td></tr>";
// Project Completion Date
echo "<tr><td>";
echo "<label for='date'>Finish Date</label>";
echo "</td><td>";
$dateArray = getdate();
$month = $dateArray[mon];
$day = $dateArray[mday];
if ($month < 10){
$month = '0' . $dateArray[mon];
}
if ($day < 10){
$day = '0' . $dateArray[mday];
}
$todaysDate = $dateArray[year] . '-' . $month . '-' . $day;
echo "<input type='date' name='date' value='" . $todaysDate . "' style='width:150px'>";
echo "</td></tr>";
// Buttons
echo "<tr><td align='center'>";
echo "<input type='button' name='Save' value='Save' onclick='javascript:validateAndSubmit(this.form);' style='width:100px'>";
echo "</td><td align='center'>";
echo "<input type='button' name='Cancel' value='Cancel' onclick='javascript:cancelEntry();' style='width:100px'>";
echo "</td></tr>";
echo "</table>";
echo "</form>";
echo "</div>";
?>
</div>
</div>
</body>
window.location.href may not trigger reload in some browsers and cases..
You should add a reload after
like this:
window.location.href = '/foo/bar/';
window.locaton.reload(true)
But, some browsers delay milliseconds to perform location.href set. In this cases the window.location.reload(true) may complete before this.
Therefore, add a timeout in reload:
window.location.href = '/foo/bar/';
setTimeout('window.locaton.reload(true)', 500);
works in all browsers for me
Good morning! I found the cause of my problem this morning and have been able to resolve the issue. The problem I was causing is because I am using the tag (stylized by css) to display the information, with an onclick event to call my JS code to redirect. Within the tag I had the href='', thinking that the JS would override that functionality, it doesn't!
Removing the href='' from the tag resolved the issue and allowed me to redirect to the new page. A second solution is to use my php code to dynamically create the href link within the tag.
echo "<li><a onclick='viewDetails($modelID);'>" . $modelRow[1] . "<small>in stock: <value>" . $rowAvailCount . "</value> sold: <value>" . $rowSoldCount . "</value></small></a></li>";
OR
echo "<li><a href='inventorydetails.php?ModelID=" . $modelID . "'>" . $modelRow[1] . "<small>in stock: <value>" . $rowAvailCount . "</value> sold: <value>" . $rowSoldCount . "</value></small></a></li>";
I think I will go with the second example for two reasons. First, it provides the link icon when hovering (which I know I can add through css, but this is easier. Second, less JS code.
I thank you for all your help in resolving this!

Categories