I'm developing a web application which is like a notepad or a to-do list with php sql html css jquery
The query gets the list at index page and displays it and on displaying it adds a button with an "edit" class.
When they press on the edit the edit works but only once after submitting.
On submitting the button launches an ajax call with jQuery to another PHP file which edits the data and and displays all the items from the database again.
There's also an "add item" button which adds a new item. Which on submit adds a new item and also gets everything again from the database and displays it (also ajax).
The bug is either after submitting a new item or after editing, the edit button stops working
Please check the snippet below -- snippet 1 is the jquery, snippet 2 is the file to be run on ajax call, and snippet 3 is the index php file:
$("#submit").click(function(){
textarea = $("#textarea").val();
date = $("#date").val();
if(textarea == "" || date == ""){
$("#message").html("<span class='error'>Make sure you didn't leave anything empty");
}
else{
$("#message").html("");
submitItem();
$("#contentCont").fadeOut(200);
}
});
$(".edit").click(function(){
i = "edit";
itemID = $(this).attr("name");
var dateValue = $("#date"+itemID).text();
var statusValue = $("#status"+itemID).attr("name");
var textboxValue = $("#textbox"+itemID).text();
var categoryValue = $("#category"+itemID).text().toLowerCase();
$("#contentCont").fadeIn(200);
$("#textarea").val(textboxValue);
$("#date").val(dateValue);
$("#categories").val(categoryValue).prop("selected",true);
$("#status").val(statusValue).prop("selected",true);
});
function submitItem(){
textarea = $("#textarea").val();
status = $("#status").val();
category = $("#categories").val();
date = $("#date").val();
var ajaxReq = new XMLHttpRequest();
ajaxReq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("todoCont").innerHTML = this.responseText;
}
}
ajaxReq.open("POST","../php/addItem.php",true);
ajaxReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxReq.send("textarea="+textarea+"&category="+category+"&status="+status+"&date="+date+"&itemID="+itemID+"&i="+i);
}
<?php
session_start();
require("server.php");
$cnx = new mysqli($server_name,$server_username,$server_password,$db);
$category = validate($_POST["category"]);
$item = $_POST["textarea"];
$date = $_POST["date"];
$status = validate($_POST["status"]);
$userID = $_SESSION["userID"];
$itemID = $_POST["itemID"];
$i = $_POST["i"];
$searchForCategoryID = "SELECT * FROM categories where userID='$userID' AND categoryname = '$category'";
$result = $cnx->query($searchForCategoryID);
$row = $result->fetch_assoc();
$categoryID = $row["CategoryID"];
if ($i === "new"){
$addItem = "INSERT INTO Items(userID,ItemValue,DueDate,CategoryID,Status) VALUES ($userID, '$item' , '$date' , $categoryID,'$status')";
$cnx->query($addItem);
}
else if ($i === "edit"){
$editItem = "UPDATE Items SET ItemValue='$item' , DueDate='$date' , CategoryID = $categoryID,Status='$status' WHERE itemID = $itemID " ;
$cnx->query($editItem);
}
$getTableRows = "SELECT * FROM Items WHERE userID = $userID ORDER BY DueDate";
$result = $cnx->query($getTableRows);
if($cnx->error){
echo "Could not get your stuff";
}
if($result->num_rows > 0){
while ($rows = $result->fetch_assoc()){
$getCategory = "SELECT CategoryName FROM Categories WHERE CategoryID = " . $rows["CategoryID"] . ";";
$result2 = $cnx->query($getCategory);
$rows2 = $result2->fetch_assoc();
if ($rows["Status"] == "ongoing"){
$status = "ongoing";
}else
if ($rows["Status"] == "overdue"){
$status = "overdue";
}else
if ($rows["Status"] == "done"){
$status = "done";
}
echo ' <div class="box-container">
<div class="right">
<div class="textbox">
<span id="textbox'.$rows["itemID"].'">'. $rows["ItemValue"] .'</span>
</div>
<div class="footer">
<div class="status '. $status .'" id="status'.$rows["itemID"].'" name="'.$status.'"></div>
<span class="date" id="date'.$rows["itemID"].'">'.$rows["DueDate"].'</span>
<span class="category" id="category'.$rows["itemID"].'">'.ucfirst($rows2["CategoryName"]).'</span>
<button type="button" name="'. $rows["itemID"] .'" class="btn btn-info edit">Edit</button>
</div>
</div>
</div>';
}
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php session_start();?>
<?php
include("server.php");
$cnx = new mysqli($server_name,$server_username,$server_password,$db);
$userID = $_SESSION["userID"];
<!--This is how the info is shown and the EDIT button is made-->
echo ' <div class="box-container">
<div class="right">
<div class="textbox">
<span id="textbox'.$rows["itemID"].'">'. $rows["ItemValue"] .'</span>
</div>
<div class="footer">
<div class="status '. $status .'" id="status'.$rows["itemID"].'" name="'.$status.'"></div>
<span class="date" id="date'.$rows["itemID"].'">'.$rows["DueDate"].'</span>
<span class="category" id="category'.$rows["itemID"].'">'.ucfirst($rows2["CategoryName"]).'</span>
<button type="button" name="'. $rows["itemID"] .'" class="btn btn-info edit">Edit</button>
</div>
</div>
</div>';
}
?>
you need to register your events more globally:
$("body").on("click", "#submit", function(){
});
and
$("body").on("click", ".edit", function(){
});
You need to delegate as the element is getting created dynamically.
Change the below line:
$(".edit").click(function(){
to:
$(".edit").on('click', function(){
And the same applies for
$("#submit").click(function(){
to
$("#submit").on('click', function(){
Related
I've got a search bar that is returning proper results, except that it is including results from a column I don't want to be searched.
MySQL query (file name search2.php):
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$submitted_search = $_POST['search'];
}
$safe_search = '%' . $submitted_search . '%'; //I know it's not 'safe' yet-bound below!
$sqlSearch = "
SELECT tbl.title
, tbl.artists
, tbl.date_starting
, tbl.date_ending
, tbl.opening_date
, tbl.opening_time
, tbl.category
, tbl.cost
, tbl.place_decode_strip
, tbl.title_decode_strip
, tbl.artists_decode_strip
, place.site
, place.addr
, place.hours
, place.web
, place.admis
FROM tbl
JOIN place
ON tbl.place = place.site
WHERE CONCAT_WS(' || ', tbl.date_ending, tbl.opening_date, tbl.place_decode_strip,
tbl.title_decode_strip, tbl.artists_decode_strip,
place.aka)
LIKE ?
ORDER
BY date_ending DESC
";
$stmt = $conn->prepare($sqlSearch);
$stmt->bind_param("s", $safe_search);
$stmt->execute();
$data = $stmt->get_result();
$searchResultsNum = mysqli_num_rows($data);
if ($searchResultsNum === 0) {
echo "<h3>There are no results matching your search.</h3>";
} elseif ($searchResultsNum === 1) {
echo "<h3>There is 1 result matching “<i>" . $submitted_search . "</i> ”.</h3>";
} else {
echo "<h3>There are " . $searchResultsNum . " results matching “<i>" . $submitted_search . "</i> ”.</h3>";
}
if ($searchResultsNum > 0) {
// data of each row
while ($searchRow = $data->fetch_assoc()) {
$date = strtotime($searchRow["opening_date"]);
$sdate = strtotime($searchRow["date_starting"]);
$edate = strtotime($searchRow["date_ending"]); ?>
<section class="entry">
<article class="site-info">
<p class="site"><?php $web = $searchRow["web"];
echo "<a href='$web' target='_blank' rel='noreferrer'>" . $searchRow["site"]; ?></a>
</p>
<p class="site-add"><?php echo $searchRow["addr"]; ?></p>
<p class="site-hrs"><?php echo $searchRow["hours"]; ?></p>
</article>
<article class="event-info">
<p class="title"><?php echo $searchRow["title"]; ?></p>
<p class="artists"><?php echo $searchRow["artists"]; ?></p>
<?php if ($searchRow["date_starting"] != $searchRow["date_ending"]) {
?><p><?php
echo date("F j", $sdate) . " – ";
echo date("F j, Y", $edate); ?></p>
<p><?php
}
echo $searchRow["category"] . ": ";
echo date("F j", $date) . ", ";
echo $searchRow["opening_time"]; ?></p>
<?php if ($searchRow["cost"] !== null) { ?>
<p><?php echo $searchRow["cost"]; ?></p>
<?php } ?>
</article>
</section>
<?php }
}
?>
JavaScript:
const searchButton = document.getElementById('search-btn');
searchButton.addEventListener("click", stopRedirect);
function submitSearch() {
const searchInput = document.getElementById('searchInput').value;
// const searchResultId = document.getElementById('search-results');
if (!searchInput) {
document.getElementById('search-results').innerHTML = "Please enter search term."
} else if (searchInput == ' ') {
document.getElementById('search-results').innerHTML = "Please enter a valid search term."
} else if (searchInput == '%') {
document.getElementById('search-results').innerHTML = "Please enter a valid search term."
} else {
var formData = new FormData();
formData.append('search', searchInput);
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "../phpScripts/search2.php", true);
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
const response_data = xhttp.response;
document.getElementById('search-results').innerHTML = response_data; //this.response
}
}
}
xhttp.send(formData);
}
function stopRedirect(e) {
e.preventDefault();
}
HTML search form:
<aside class="search-field">
<form class="search-form" id="search-form" action="/phpScripts/search2.php" method="POST" role="search">
<input type="search" name="search" placeholder="Search all events"
id="searchInput" aria-label="Search through site content" />
<input type="submit" value="Submit" id="search-btn" onclick="submitSearch()" />
</form>
</aside>
When I search for < I get correct results from event_tbl.title (that is, it includes titles with HTML tags) but I don't want results from that column. I only want results from the decoded and stripped columns, tbl.title_decode_strip in this case.
Why is the query returning results from tbl.title? How can I limit the query to not include search (WHEN) results from tbl.title? I need to include tbl.title in the query because that is part of the HTML that gets returned in the AJAX. tbl.title isn't included in the WHEN part of the query, so I don't know why it is included in the results.
I'm building an online store for my sister and i'm struggling with removing specific item from cart ($_SESSION) when I click the X icon of product (onclick="").
<?php
if (empty($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
?>
<div class="cart-content d-flex">
<!-- Cart List Area -->
<div class="cart-list">
<?php
$subtotal = 0;
$livrare = 17;
$subtotal_modif = 0 . " Lei";
$object = new Produs();
$cartItems = $_SESSION['cart'];
foreach ($cartItems as $item):
$rows = $object->getRows("SELECT * FROM produs");
foreach ($rows as $row) {
//$subtotal += $row['pret_produs'];
if ($item['id'] == $row['id_produs']) {
$imagini = $object->getRows("SELECT * FROM imagini WHERE id_produs_imagine = ? LIMIT 1", [$row['id_produs']]);
$pret = $row['pret_produs'];
$pret_modif = str_replace('.', ',', $row['pret_produs']) . " LEI";
$pret_vechi = $row['pret_vechi_produs'];
$pret_redus_modif = str_replace('.', ',', $row['pret_vechi_produs']) . " LEI";
$subtotal = $subtotal + ($pret * $item['cantitate']);
$subtotal_modif = str_replace('.', ',', $subtotal) . " LEI";
?>
<!-- Single Cart Item -->
<div class="single-cart-item">
<a href="#" class="product-image">
<?php foreach ($imagini as $img) {
echo '<img src="'. $object->photoPath() . $img['nume_imagine'] .'" alt="">';
} ?>
<!-- Cart Item Desc -->
**<div class="cart-item-desc">
<span class="product-remove"><i onclick="removeItem('<?php $item['id']; ?>')" class="fa fa-close" aria-hidden="true"></i></span>**
<!-- <span class="badge">Mango</span> -->
<h6><?php echo $row['nume_produs']; ?></h6>
<p class="size">Marime: <?php echo $item['marime']; ?></p>
<p class="color">Cantitate: <?php echo $item['cantitate']; ?></p>
<p class="price"><?php echo $pret; ?></p>
</div>
</a>
</div>
<?php } }
endforeach;
?>
</div>
I'm thinking in doing something like this at the end of page but I don't know how to do it properly:
<script>
function removeItem(itemID) {
<?php unset($_SESSION['cart']['<script>itemID</script>']); ?>
}
</script>
I dont know how to combine PHP and JavaScript.
You can put this in the top of your PHP script:
if ( empty( $_SESSION['cart'] ) ) {
$_SESSION['cart'] = [];
}
if ( isset( $_POST['remove_item'] ) ) {
$itemID = $_POST['remove_item'];
if ( isset( $_SESSION['cart'][ $itemID ] ) ) {
unset( $_SESSION['cart'][ $itemID ] );
}
echo $itemID;
die();
}
// THE REST OF YOUR PHP CODE.
Give the container of the item a unique id based on the item's id:
<div class="single-cart-item" id="single-cart-item-<?php echo $item['id']; ?>">
<!-- --------------- -->
</div>
And this in your JS:
<script type="text/javascript">
function removeItem( itemID ) {
// make AJAX request to server to remove item from session.
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "cart.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("remove_item=" + itemID);
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var element = document.getElementById("single-cart-item-" + this.responseText);
if (element !== null) {
element.remove();
}
}
};
}
</script>
The function removeItem( itemID ) is making an AJAX call to your PHP script. It passes the item ID as a POST value. Replace cart.php with the correct path (URL to your cart page).
I have a page called events.php that lists past and upcoming events, using ajax to call on pastevents.php and upcomingevents.php, which both have forms that collect users' opinions on past events and whether they will attend future events; then a handle sends it to psql db.
Everything works except the first iteration of the looped form does not submit correctly. Instead of continuing onto pastevents-handle.php, it doesn't post and returns a get on events.php; so I see the user's response in the url bar, but it never gets to the db. I made a test page that didn't use ajax by copy-pasting all the code and that works, so it's definitely something to do with ajax, but neither me or my professor could find out what.
I don't know how to use jquery yet, so please answer with plain javascript.
Here's events.php:
<script>
//show past events
function showPastEvents(str) {
document.getElementById('pastevents').style.display = "block";
document.getElementById('hideoldbutton').style.display = "block";
var xhttp;
if (str == "") {
document.getElementById("pastevents").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("pastevents").innerHTML = this.responseText;
}
};
xhttp.open("POST", "pastevents.php?q="+str, true);
xhttp.send();
}
function hidePastEvents() {
document.getElementById('pastevents').style.display = "none";
document.getElementById('hideoldbutton').style.display = "none";
}
//show upcoming events
function showUpcomingEvents(str) {
document.getElementById('upcomingevents').style.display = "block";
document.getElementById('hidenewbutton').style.display = "block";
var xhttp;
if (str == "") {
document.getElementById("upcomingevents").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("upcomingevents").innerHTML = this.responseText;
}
};
xhttp.open("POST", "upcomingevents.php?q="+str, true);
xhttp.send();
}
function hideUpcomingEvents() {
document.getElementById('upcomingevents').style.display = "none";
document.getElementById('hidenewbutton').style.display = "none";
}
</script>
<!-- page content -->
<div class="content">
<h6>Past events</h6>
<form name="postpastevents" action=""/>
<div id="pastevents"></div>
<input type="button" onClick="hidePastEvents()" id="hideoldbutton" value="Hide" style="display:none;"/>
</form>
<input type="button" onClick="showPastEvents()" id="showoldbutton" value="Show past"/>
<br>
<br>
<!-- ####### -->
<h6>Upcoming events</h6>
<form name="postupcomingevents" action=""/>
<div id="upcomingevents"></div>
<input type="button" onClick="hideUpcomingEvents()" id="hidenewbutton" value="Hide" style="display:none;"/>
</form>
<input type="button" onClick="showUpcomingEvents()" id="shownewbutton" value="Show upcoming"/>
Here is pastevents.php (it's the same code for upcomingevents.php):
<?php
$conn = pg_connect ('dbname=xxxx') or die ('Connect failed ');
$query = "SELECT eventname, eventdate, location, eventdesc FROM events WHERE eventdate < current_date ORDER BY eventdate;";
$result = pg_query($query);
while ( $row = pg_fetch_assoc($result) ) {
$i = 0;
echo "<tr>"; //table row
foreach ($row as $key => $value) {
if ($i == 0) {
$eventname = $value;
}
if ($i == 1) {
$eventdate = $value;
}
$eventinfo = $value;
echo "<td>"; //1 column each loop
echo "$eventinfo";
if ($i == 1) {
echo date(" (l, F jS)", strtotime($eventdate));
}
echo "<br><br>";
echo "</td>";
$i++;
}
echo "<td>";//1 column while same event
?>
<div>
<form name="pasteventsurvey" action="pastevent-handle.php" method="post">
What did you think of the event?
<select name="pasteventopinion">
<option value="">(Choose one)</option>
<option value="good">Loved it!</option>
<option value="okay">Liked it</option>
<option value="bad">Needs improvement</option>
<option value="time">Time conflict</option>
<option value="NA">NA</option>
</select>
<input type="hidden" name="eventname" value="<?php echo $eventname; ?>">
<input type="submit" name="enter" value="Submit"><input type="reset" name="erase" value="Clear">
</form>
</div>
<?php
echo "</td>";
echo "</tr>"; //-table row
}
pg_close($conn);
?>
Here's pastevents-handle.php:
<?php
$conn = pg_connect ('dbname=xxxx') or die ('Connect failed ');
pg_query_params("INSERT INTO eventsurveypast(eventname, opinion) VALUES ($1, $2)", array($name, $opinion));
echo "email is $idkey, eventname is $name, pastopinion is $opinion";
pg_close($conn);
?>
(I edited a bit for space, ignore anything that isn't vital)
It is illegal to have a form inside another form.
Remove the outer form and everything should work fine, except you have another problem with the code.
The thing is i a have a page where my user post shows and on the post there is a connect button in form of form input. Each of the post has the posters id. I want it such that when a user clicks on the connect button the poster's id is INSERTED into the database.
The PHP
<?php
$sql = <<<EOF
SELECT COUNT(*) as count FROM programs;
EOF;
$ret = $db->querySingle($sql);
if ($ret == 0)
{
echo "<div class='no_prog'>No programs currently advertised</div>";
}
else
{
$rsql = <<<EOF
SELECT * FROM programs ORDER BY id DESC;
EOF;
$rret = $db->query($rsql);
while ($rrow = $rret->fetchArray(SQLITE3_ASSOC))
{
$banner = $rrow['banner'];
$banner_2 = $rrow['banner_2'];
$title = $rrow['sem_title'];
$spons = $rrow['sem_spons'];
$link = $rrow['sem_link'];
$company = $rrow['sem_comp'];
$brief = $rrow['sem_brief'];
$ad_id = $rrow['userid'];
$usql = <<<EOF
SELECT * FROM User WHERE ID = '$ad_id';
EOF;
$uret = $db->query($usql);
while ($urow = $uret->fetchArray(SQLITE3_ASSOC))
{
$ad_img = $urow['image'];
$ad_name = $urow['fname'];
echo "<div class=\"preview_prog\">
<div class='posted_by'>
<p><img src='$ad_img'></p>
</div>
<div class='ad_user_info'>
<div class='ad_info'>
<div class='ad_info_img'>
<img src='$ad_img'>
</div>
<div class='ad_info_name'>
<p>$ad_name</p>
</div>
<div class='ad_info_conn'>
<div class='ad_info_conn_btn'>
<div class='conn_img'>
<img src='images/connect.png'>
</div>
//TOP INSERT $ad_id TO DATABASE
<form action='connect_exec.php' method='post' id='connect_form' enctype='multipart/form-data'>
<input type='submit' name='connect' class='conn_text' id='connect' value='connect +'>
<!--<a href='user_connect.php?userid=$ad_id' class='conn_text' name='user_connect'>Connect +</a>-->
</form>
</div>
I have tried putting the form="action" in an external php file but its not getting the$ad_id. Most likely because it not a link
Action PHP
<?php
require_once ("db.php");
$db = new MyDB();
session_start();
if (isset($_POST['connect']))
{
$my_id = $_SESSION['log_id'];
$ad_id = (int)$_GET['userid'];
$rand_num = rand();
$hsql =<<<EOF
SELECT COUNT(hash) as count FROM connect WHERE (user_one = '$my_id' AND user_two = '$ad_id') OR (user_one = '$ad_id' AND user_two = '$my_id');
EOF;
$hret = $db->querySingle($hsql);
if ($hret == 1)
{
$response = "Your are already connected to '$ad_id'";
}
else
{
$csql =<<<EOF
INSERT INTO connect (user_one, user_two, hash) VALUES ('$my_id', '$ad_id', '$rand_num');
EOF;
$cret = $db->exec($csql);
if (!$cret)
{
$message = "Error connecting to '$ad_id'";
}
else
{
$message = "Successfully Connected to '$ad_id'";
}
}
}
?>
Please any advice on how i can upload the $ad_id to the database.
Note that am new to PHP and know little Ajax
try to add an hidden field within the form that you are creating in string with name "userid" which will have the id in its value that you want to receive in your action.php with $_GET['userid'] in replace this $_GET['userid'] with $_POST['userid']. You will get the userid
<?php
$sql = <<<EOF
SELECT COUNT(*) as count FROM programs;
EOF;
$ret = $db->querySingle($sql);
if ($ret == 0)
{
echo "<div class='no_prog'>No programs currently advertised</div>";
}
else
{
$rsql = <<<EOF
SELECT * FROM programs ORDER BY id DESC;
EOF;
$rret = $db->query($rsql);
while ($rrow = $rret->fetchArray(SQLITE3_ASSOC))
{
$banner = $rrow['banner'];
$banner_2 = $rrow['banner_2'];
$title = $rrow['sem_title'];
$spons = $rrow['sem_spons'];
$link = $rrow['sem_link'];
$company = $rrow['sem_comp'];
$brief = $rrow['sem_brief'];
$ad_id = $rrow['userid'];
$usql = <<<EOF
SELECT * FROM User WHERE ID = '$ad_id';
EOF;
$uret = $db->query($usql);
while ($urow = $uret->fetchArray(SQLITE3_ASSOC))
{
$ad_img = $urow['image'];
$ad_name = $urow['fname'];
echo "<div class=\"preview_prog\">
<div class='posted_by'>
<p><img src='$ad_img'></p>
</div>
<div class='ad_user_info'>
<div class='ad_info'>
<div class='ad_info_img'>
<img src='$ad_img'>
</div>
<div class='ad_info_name'>
<p>$ad_name</p>
</div>
<div class='ad_info_conn'>
<div class='ad_info_conn_btn'>
<div class='conn_img'>
<img src='images/connect.png'>
</div>
//TOP INSERT $ad_id TO DATABASE
<form action='connect_exec.php' method='post' id='connect_form' enctype='multipart/form-data'>
<input type='hidden' name='userid' value='$ad_id'/>
<input type='submit' name='connect' class='conn_text' id='connect' value='connect +'>
<!--<a href='user_connect.php?userid=$ad_id' class='conn_text' name='user_connect'>Connect +</a>-->
</form>
</div>
Action.php
<?php
require_once ("db.php");
$db = new MyDB();
session_start();
if (isset($_POST['connect']))
{
$my_id = $_SESSION['log_id'];
$ad_id = (int)$_POST['userid'];
$rand_num = rand();
$hsql =<<<EOF
SELECT COUNT(hash) as count FROM connect WHERE (user_one = '$my_id' AND user_two = '$ad_id') OR (user_one = '$ad_id' AND user_two = '$my_id');
EOF;
$hret = $db->querySingle($hsql);
if ($hret == 1)
{
$response = "Your are already connected to '$ad_id'";
}
else
{
$csql =<<<EOF
INSERT INTO connect (user_one, user_two, hash) VALUES ('$my_id', '$ad_id', '$rand_num');
EOF;
$cret = $db->exec($csql);
if (!$cret)
{
$message = "Error connecting to '$ad_id'";
}
else
{
$message = "Successfully Connected to '$ad_id'";
}
}
}
?>
I have a select with client names that is populated from a SQL database, that part works fine, but occasionally it is necessary to add a new client. So I want a button that displays a popup where the user can provide the new client name and have it added to the select as a new option. Below is the relevant code that I have tried. The problem is that when either button is pressed on the prompt it causes the form to submit and reloads the page. Thanks in advance.
<form action = "AddNewJob.php" method = "post">
...
<td><?php echo $dropdown3 ?><button onclick="myFunction()">Add new client</button>
<script>
function myFunction() {
var client = prompt("Please enter client name", "New client");
if ((client != null) && (!client.equals("New client"))) {
var select = document.getElementById("Client");
select.options[select.options.length] = new Option(client, client);
document.getElementById('newclientfield').value = client;
}
}
</script></td>
...
<p><input type="hidden" id="newclientfield" value="" /></p>
<p align="center"><input type="submit" value="Submit" name="btnAdd"></p>
</form>
$dropdown3 is the select that is created in PHP from the SQL database
EDIT:
Here is the code for $dropdown3:
$Clients = array();
$result = mysqli_query($link, "SELECT Name FROM tblClients");
$i = 0;
$rownum = mysqli_num_rows($result);
while ($i < $rownum){
mysqli_data_seek($result, $i);
$row = mysqli_fetch_row($result);
$Clients[] = $row[0];
$i++;
}
$dropdown3 = "<select size=\"1\" name=\"Client\" id=\"Client\">";
$i = 0;
while($i < count($Clients)){
$dropdown3 .= "\r\n<option value = '" . $Clients[$i] . "'>" . $Clients[$i] . "</option>";
$i++;
}
$dropdown3 .= "\r\n</select>";
That part works fine.
This is the final working code for the button that requests user input and then adds the option to the select (as well as a hidden field for POST purposes so it can be added to the database).
<button type="button" onclick="myFunction()">Add new client</button>
<script>
function myFunction() {
var client = prompt("Please enter client name", "New client");
if ((client != null) && (client != "New client")) {
var select = document.getElementById("Client");
select.options[select.options.length] = new Option(client, client);
document.getElementById('newclientfield').value = client;
select.selectedIndex=select.options.length - 1;
}
}
</script>