I am an angular newbie using the multiselect directive from isteven.
I wrote a test case, which works fine from the HTML in the root folder, but when I incorporated it into my app, none of the drop-downs are visible.
There are no console.log error messages.
I bundled the HTML and controller into the same file.
The "myApp.controller('MainCtrl', function ($scope, $http)" does not get executed although the "var myApp = angular.module( "myApp", [ "isteven-multi-select" ]);" does.
<html data-ng-app="myApp" id="myApp" lang="en">
<head>
<title>Writer's Tryst - Enablers Form</title>
<link type="text/css" href="css/enablers.css" rel="stylesheet" />
<link rel="stylesheet" href="css/isteven-multi-select.css">
</head>
<body data-ng-controller="MainCtrl">
<div class="container center_div">
<!--<form id="form-writers" class="form-horizontal well">-->
<img id="img-enablers" src="#" alt="images" />
<form id = "form-enablers" class="form-horizontal well">
<h1>Enablers</h1>
<label for="work-type" class="fixed50">Type:</label>
<p id="work-type"
data-isteven-multi-select
data-input-model="worktype"
data-output-model="outputWorktype"
data-button-label="icon name"
data-item-label="icon name"
data-tick-property="ticked"
></p>
<label for="form-type" class="fixed50">Form:</label>
<p id="form-type"
data-isteven-multi-select
data-input-model="formtype"
data-output-model="outputFormtype"
data-button-label="name"
data-item-label="name"
data-tick-property="ticked"
></p>
<p>For an explanation of the genres s hown here, see <a target="_blank" href="https://en.wikipedia.org/wiki/List_of_genres">List of genres</a><br/></p>
<label for="genres" class="fixed50">Genres:</label>
<p id="genres"
data-isteven-multi-select
data-input-model="genres"
data-output-model="outputGenres"
data-button-label="name"
data-item-label="name"
data-tick-property="ticked"
></p>
<label for="accepted-media" class="fixed50">Accepted Media:</label>
<p id="accepted-media"
data-isteven-multi-select
data-input-model="acceptedMedia"
data-output-model="outputMedia"
data-button-label="icon name"
data-item-label="icon name"
data-tick-property="ticked"
></p>
<p> <label for="special-instructions" class="fixed50">Special Instructions</label>
<textarea id ="special-instructions" name="special-instructions">
</textarea>
</p>
<p>For a limited time, enablers can use this site for <span style="color: #f00; font-weight:bold">FREE</span>. We reserve the right to change this policy without notice.</p>
<div id="recaptcha-elements"></div>
<div class="form-group">
<button type="submit" id="enablers-search" class="btn btn-default glyphicon glyphicon-search"> Search</button>
</div>
<input id="userid" name="userid" type="hidden" />
</form>
</div>
<form id="writers-list">
<p>To request a manuscript, click the checkbox beneath the thumbs-up icon.</p>
<div id="table-list"></div>
</form>
<script src="js/isteven-multi-select.js"></script>
<script src="js/enablers.js"></script>
<script src="js/recaptcha.js"></script>
<script>
var myApp = angular.module( "myApp", [ "isteven-multi-select" ]);
myApp.controller('MainCtrl', function ($scope, $http) {
alert("got here");
$scope.worktype = [
{ icon: "<img src=img/icons/smile-mask.png />", name: "Fiction", ticked: false },
{ icon: "<img src=img/icons/frown-mask.png />", name: "Non-Fiction", ticked: false }
];
$scope.formtype = [];
var data = {};
data.action = 'multiselect-forms';
ajax('post', 'php/enablers.php', data, formsSuccess, 'Error retrieving multiselect forms data: ');
function formsSuccess(data) {
console.log(data);
$scope.formtype = eval(data);
}
$scope.genres = [];
data.action = 'multiselect-genres';
ajax('post', 'php/enablers.php', data, genresSuccess, 'Error retrieving multiselect forms data: ');
function genresSuccess(data) {
console.log(data);
$scope.genres = eval(data);
}
$scope.acceptedMedia = [
{ icon: "<img src=img/icons/email.png />", name: "Mail", ticked: false },
{ icon: "<img src=img/icons/pdf.png />", name: "PDF File", ticked: false }
];
/*
$http({
method: "POST",
url: "php/enablers.php",
params: data,
contentType: 'text'
}).then(function mySucces(response) {
console.log(response.data);
// $scope.formtype = response.data;
}, function myError(response) {
$scope.FORMTYPE = response.statusText;
});
*/
})
</script>
</body> s
</html>
Notice, I resorted to using jQuery Ajax because angular kept insiting on JSON, even though the header from the PHP interace specified content-type of text/plain as well as the http call specifiing contentType = 'text'
PHP
<?php
require_once 'dbconnect.php';
function isEmpty($str) {
return strlen(trim($str)) == 0;
}
function buildInStmt($array)
{
if (is_array($array)) {
$in = implode(',', $array);
} else $in = "'" . $array . "'";
return $in;
}
function multiselectGenres()
{
try {
$dbh = connect2DB();
$stmt = $dbh->prepare("SELECT ID, Genre FROM Genres ORDER BY Genre");
if (!$stmt->execute()) {
echo "\nPDOStatement::errorCode(): ";
print $stmt->errorCode();
print_r($dbh->errorInfo());
} else {
$select = "[";
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$genre = $row['Genre'];
$id = $row["ID"];
$select .= "{";
$select .= 'name: ';
$select .= '"' . $genre . '",';
$select .= 'ticked: false},';
}
$select = substr($select, 0, -1) . "]";
}
header("Content-Type: text/plain");
echo $select;
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
function multiselectForms() {
try {
$dbh = connect2DB();
$stmt = $dbh->prepare("SELECT ID, Form FROM Forms ORDER BY Form");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$select = "[";
foreach ($rows as $row) {
$id = $row['ID'];
$form = $row['Form'];
$select .= "{";
$select .= 'name: ';
$select .= '"' . $form . '",';
$select .= 'ticked: false},';
}
$select = substr($select, 0, -1) . "]";
header("Content-Type: text/plain");
echo $select;
} catch (PDOException $e) {
echo 'Database error: ' . $e->getMessage();
} catch (Exception $e) {
echo 'General failure: ' . $e->getMessage();
}
}
function search() {
try{
/*
if (!isset($_REQUEST["work-type"]) || isEmpty($_REQUEST["work-type"]))
throw new Exception('You must select a type of work.');
else {
$worktype = filter_var(trim($_REQUEST["work-type"]), FILTER_SANITIZE_STRING);
$worktype = htmlspecialchars_decode($worktype, ENT_QUOTES);
}
*/
manageEnablerData();
if (!isset($_REQUEST["userid"]) || isEmpty($_REQUEST["userid"])) {
throw new Exception('A user-id must be supplied.');
}
$userid = $_REQUEST["userid"];
if (!isset($_REQUEST["form-type"]) || empty($_REQUEST["form-type"])) {
throw new Exception('You must select a form type.');
}
$forms = buildInStmt($_REQUEST["form-type"]);
if (!isset($_REQUEST["genre"]) || empty($_REQUEST["genre"])) {
throw new Exception('You must select a genre.');
}
$genres = buildInStmt($_REQUEST["genre"]);
/*
if (!isset($_REQUEST["sub-genre"]) || isEmpty($_REQUEST["sub-genre"]))
throw new Exception('You must select a sub-genre.');
else {
$subgenre = filter_var(trim($_REQUEST["sub-genre"]), FILTER_SANITIZE_STRING);
$subgenre = htmlspecialchars_decode($subgenre, ENT_QUOTES);
}
*/
$dbh = connect2DB();
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("SELECT a.ID, a.Email, a.Name, w.Title, w.Filename FROM Writers w JOIN Accounts a ON a.ID = w.fkAccounts WHERE a.ID = :userid AND FormType IN($forms) AND Genre IN($genres)");
$stmt->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll();
$table = '<table><tr><th>Author</th><th>Title</th><th>Synopsis</th><th><img src="img/Thumb-up-icon.png" width="32" alt="thumbs-up" </th></tr>';
foreach ($rows as $row) {
$table .= "<tr><td>" . $row['Name'] . "</td><td>" . $row['Title'] . "</td><td>" . "<a href='uploads/" . $row['Filename'] . "' target=_blank>synposis file</a>" . "</td><td><input type='checkbox' id='request-manuscript' name='request-manuscript'" . "</td><td class='hidden'>" . $row['ID'] . "</td><td class='hidden'>" . $row['Email'] . "</td></tr>";
}
$table .= "</table>";
echo $table;
} catch (PDOException $e) {
echo 'Database error: ' . $e->getMessage();
} catch (Exception $e) {
echo 'General error: ' . $e->getMessage();
}
}
function manageEnablerData()
{ $si = ""; //special-instructions
if (isset($_REQUEST["special-instructions"]) && !isEmpty($_REQUEST["special-instructions"])) {
$si = filter_var(trim($_REQUEST["special-instructions"]), FILTER_SANITIZE_STRING);
$si = htmlspecialchars_decode($si, ENT_QUOTES);
}
if (!isset($_REQUEST["userid"]) || isEmpty($_REQUEST["userid"])) {
throw new Exception('A user-id must be supplied.');
}
$userid = $_REQUEST["userid"];
/*
if (!isset($_REQUEST["accepted-media"]) || empty($_REQUEST["accepted-media"])) {
throw new Exception('An accepted media must be entered.');
}
$acceptedMedia = buildInStmt($_REQUEST["accepted-media"]);
*/
$dbh = connect2DB();
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("INSERT Enablers(fkAccounts, SpecialInstructions) VALUES(:fka, :si) ON DUPLICATE KEY UPDATE fkAccounts=VALUES(fkAccounts), SpecialInstructions=VALUES(SpecialInstructions)");
$stmt->bindParam(':fka', $userid, PDO::PARAM_INT);
$stmt->bindParam(':si', $si, PDO::PARAM_STR);
$stmt->execute();
//need to handle AcceptedMedia
}
//var_dump($_REQUEST);exit();
if (!isset($_REQUEST['action']) || isEmpty($_REQUEST['action']))
throw new Exception('Programmer error: action not posted.');
else {
$action = $_REQUEST['action'];
switch($action) {
case 'search':
search();
break;
case 'select':
select();
break;
case 'multiselect-genres':
multiselectGenres();
break;
case 'multiselect-forms':
multiselectForms();
break;
default:
throw new Exception("Unknown action: " . $action);
break;
}
}
?>
If you decide I deserve a downvote, please help me to understand what I am doing wrong so that I may learn from my mistakes.
1. Why not work:
a). In your test case, you've put <body data-ng-controller="MainCtrl"> in your html, and this will call MainCtrl function.
b). In your app, you also have a MainCtrl, but you neither call in from html nor $routeProvider.when
Solutions:
1). The easiest way: do <body data-ng-controller="MainCtrl"> in your app, the same as your test case.
2). Put codes inside of MainCtrl into enablersController.If just need this select input model in page #/enablers.
Both are guesses, try and if any problems let me know.
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 am programming in HTML5, PHP and JavaScript. I am trying to use Ajax to do this: when I select one option on #productoSeleccionado appear the sizes of this products that is #tallaSeleccionada but I think that this code it's no fine. I believe that the code of function and call to data base it's fine.
I have imported the library jQuery-ajax. productoSeleccionado works good but when I select one of the options don't appear nothing in the select of tallaSeleccionada. I don't know how to put it.
<p>
<h3>Seleccione producto:</h3>
<select id="productoSeleccionado" name="producto">
<?php foreach ($productos as $producto) { ?>
<option value="<?php echo $producto["OID_P"]; ?>">
<?php echo $producto["CODIGO"] . "- " . $producto["CONCEPTO"]; ?>
</option><?php } ?>
</select>
</p>
<script type="text/javascript">
$("#productoSeleccionado").on("option", function () {
$.get("gestionar_Selects.php", {
productoSeleccionado: $('#productoSeleccionado').val()
},
function (data) {
$("#tallaSeleccionada").empty();
$("#tallaSeleccionada").append(data);
}
);
});
</script>
<p>
<h3>Seleccione talla:</h3>
<select id="tallaSeleccionada" name="talla"></select>
</p>
This code I think that is good is gestionar_Selects.php
<?php
function listarTallas($conexion, $productoSeleccionado)
{
try {
//Puedo poner en vez de * NOMBRE_TALLA probado
$stmt = $conexion->prepare('SELECT * FROM ASOC_LOCAL_PRODUCTO LEFT JOIN PRODUCTOS ON (ASOC_LOCAL_PRODUCTO.OID_P = PRODUCTOS.OID_P)'
. 'LEFT JOIN TALLAS ON (ASOC_LOCAL_PRODUCTO.OID_T = TALLAS.OID_T) LEFT JOIN LOCALIZACIONES ON (ASOC_LOCAL_PRODUCTO.OID_L = LOCALIZACIONES.OID_L) '
. ' WHERE PRODUCTO.OID_P =:W_OID_P ORDER BY STOCK_MINIMO');
$stmt->bindParam(':W_OID_P', $productoSeleccionado);
$stmt->execute();
return "";
} catch (PDOException $e) {
return $e->getMessage();
}
}
if (isset($_GET["producto"])) {
$conexion = crear_conexionBD()();
$resultado = listarTallas($conexion, $_GET["producto"]);
if ($resultado != NULL) {
foreach ($resultado as $talla) {
echo "<option value= "$talla["OID_T"]" > $talla["NOMBRE_TALLA"]</option>";
}
}
cerrar_conexionBD()($conexion);
unset($_GET["producto"]);
}
?>
Change your Javascript to use on('change').
<script type="text/javascript">
$("#productoSeleccionado").on('change', function () {
$.get("gestionar_Selects.php", {productoSeleccionado: $('#productoSeleccionado').val()}, function (data) {
$("#tallaSeleccionada").empty();
$("#tallaSeleccionada").append(data);
}
);
});
</script>
In your PHP
<?php
function listarTallas($conexion, $productoSeleccionado)
{
try {
//Puedo poner en vez de * NOMBRE_TALLA probado
$stmt = $conexion->prepare('SELECT * FROM ASOC_LOCAL_PRODUCTO LEFT JOIN PRODUCTOS ON (ASOC_LOCAL_PRODUCTO.OID_P = PRODUCTOS.OID_P)'
. 'LEFT JOIN TALLAS ON (ASOC_LOCAL_PRODUCTO.OID_T = TALLAS.OID_T) LEFT JOIN LOCALIZACIONES ON (ASOC_LOCAL_PRODUCTO.OID_L = LOCALIZACIONES.OID_L) '
. ' WHERE PRODUCTO.OID_P =:W_OID_P ORDER BY STOCK_MINIMO');
$stmt->bindParam(':W_OID_P', $productoSeleccionado);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); // get rows from DB
return $rows;
} catch (PDOException $e) {
return $e->getMessage();
}
}
if (isset($_GET["productoSeleccionado"])) {
$conexion = crear_conexionBD()();
$resultado = listarTallas($conexion, $_GET["productoSeleccionado"]);
if ($resultado != NULL) {
foreach ($resultado as $talla) {
echo '<option value="' . $talla["OID_T"] . '" > ' . $talla['NOMBRE_TALLA'] . '</option>';
}
}
cerrar_conexionBD()($conexion);
unset($_GET["productoSeleccionado"]);
}
?>
I am creating a commenting system. As of now, I am trying to return a comment posted, but only the new posted comment, using AJAX, with setInterval and parsing JSON data. I am not sure what I am doing wrong, but I am getting a synatax error: unexpected end of JSON input.
Does anyone see what I am doing wrong or if there is a better way of doing this?
HTML
<form action="" method="POST" id="comment-form">
<textarea id="home_comment" name="comment" placeholder="Write a comment..." maxlength="1000" required></textarea><br>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input id="comment-button" name="submit" type="submit" value="Post">
</form>
<div id="comment-container">
AJAX
function commentRetrieve(){
$.ajax({
url: "ajax-php/comment-retrieve.php",
type: "get",
success: function (data) {
// console.log(data);
if (data == "Error!") {
alert("Unable to retrieve comment!");
alert(data);
} else {
var array = JSON.parse(data);
$(array).each(function($value) {
if($('#comment-container').find('#comment-' + $value.id).length == 0) {
$('#comment-container').prepend($value.html);
}
});
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
console.log("error"); //otherwise error if status code is other than 200.
}
});
}
setInterval(commentRetrieve, 3000);
PHP
$user = new User();
//Get the last insert id
$select_comments_sql = "
SELECT c. *, p.user_id, p.img
FROM home_comments AS c
INNER JOIN (SELECT max(id) as id, user_id
FROM profile_img
GROUP BY user_id) PI
on PI.user_id = c.user_id
INNER JOIN profile_img p
on PI.user_id = p.user_id
and PI.id = p.id
ORDER BY c.id DESC
";
if ($select_comments_stmt = $con->prepare($select_comments_sql)) {
//$select_comments_stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$select_comments_stmt->execute();
$rows = $select_comments_stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$comment_id = $row['id'];
$comment_user_id = $row['user_id'];
$comment_username = $row['username'];
$home_comments = $row['comment'];
$comment_date = $row['date'];
$commenter_user_id = $row['user_id'];
$commenter_img = $row['img'];
$commenter_img = '<img class="home-comment-profile-pic" src=" '.$commenter_img.'">';
if ($home_comments === NULL) {
echo 'No comments found.';
} else {
$html = "";
$html .= '<div class="comment-post-box">';
$html .= $commenter_img;
$html .= '<div class="comment-post-username">'.$comment_username. '</div>';
$html .= '<div>'.$comment_date. '</div>';
$html .= '<div class="comment-post-text">'.$home_comments. '</div>';
$html .= '</div>';
array('id' => $comment_id, 'html' => $html);
}
}
}
Edit: image
I want to insert a "remove" button in each of these divs, so that the database's row and the div can be deleted using the remove button.
Number of divs vary according to the number of rows in the database.
It should appear as follows,
Showing data works just fine. But, delete (remove button) doesn't work.
PHP
function deleteUser($connection, $userID){ // this function calls within the "currentUsers" Function
$sql2 = "DELETE FROM users_table WHERE user_id = '$userID' ";
if (mysqli_query($connection, $sql2)) {
header("Location: main.php");
} else {
echo "Error! ";
}
}
function currentUsers($connection){
$sql1 = "SELECT * FROM users_table ";
$result1 = mysqli_query($connection, $sql1);
if(mysqli_num_rows($result1) > 0){
while($row = mysqli_fetch_assoc($result1)) {
$userID = $row['user_id'];
$name = $row['name'];
$country = $row['country'];
echo '<div>
<h3>'. $userID. " ". $name. " ". $country. '</h3>
<input type = "button" name = "removeButton" value = "Remove" method = "GET">
</div>';
if (isset($_GET['removeButton'])) {
deleteUser($connection, $userID);
}
}
}else{
echo "Currently there are no users!";
}
mysqli_close($connection);
}
currentUsers($connection);
?>
As the discussion from the comment, The following codes given.
Updated HTML:
<input type="button" name="removeButton" value="Remove" class="removeBtn">
Javascript:
var userID = "<?php echo $userID;?>";
$(".removeBtn").on("click", function(){
$.post("page.php", { userID : userID}, function(result){
if(result == "Success") window.location.href = "main.php";
else alert(result);
});
});
page.php
//need the database connection
$userID = $_POST['userID'];
$sql2 = "DELETE FROM users_table WHERE user_id = '$userID' ";
if (mysqli_query($connection, $sql2)) {
echo 'Success';
} else {
echo "Error! ";
}
If you want to remove the total div as well with the database field then use:
Javascript:
var userID = "<?php echo $userID;?>";
$(".removeBtn").on("click", function(){
var __this = $(this);
$.post("page.php", { userID : userID}, function(result){
if(result == "Success"){
__this.closest("div").remove();
window.location.href = "main.php";
}
else alert(result);
});
});
If you want to pass your $userID in each input then use:
<input data-userid = <?php echo $userID;?> type="button" name="removeButton" value="Remove" class="removeBtn">
Javascript
$(".removeBtn").on("click", function(){
var __this = $(this);
var userID = __this.attr("data-userid");
$.post("page.php", { userID : userID}, function(result){
if(result == "Success"){
__this.closest("div").remove();
window.location.href = "main.php";
}
else alert(result);
});
});
This is just an answer of your question, but you have to use this as you want. This may help you, try and let me know what happens.
The remove button doesnt work because you never get into deleteUser() method.
You cant just write
<input type = "button" name = "removeButton" value = "Remove" method = "GET">
as it was inside a form. For it to trigger, write it like this:
<form method="GET">
<input type = "submit" name = "removeButton" value = "<?php echo $userID;?>">
</form>
Then, when calling
deleteUser($connection, $_GET['removeButton']);
Hope this helps.
<?php
$connection = mysqli_connect('localhost', 'root', '', 'users');
function deleteUser($connection, $userID){ // this function calls within the "currentUsers" Function
$sql2 = "DELETE FROM users_table WHERE id = '$userID' ";
if (mysqli_query($connection, $sql2)) {
header("Location: main.php");
} else {
echo "Error! ";
}
}
function currentUsers($connection){
$sql1 = "SELECT * FROM maps ";
$result1 = mysqli_query($connection, $sql1);
if(mysqli_num_rows($result1) > 0){
while($row = mysqli_fetch_assoc($result1)) {
$userID = $row['id'];
$name = $row['name'];
$country = $row['country'];
echo '<div>
<h3>'. $userID. " ". $name. " ". $country. '</h3>
</div>';
}
}else{
echo "Currently there are no users!";
}
mysqli_close($connection);
}
if (isset($_GET['removeButton']))
{
deleteUser($connection, $_GET['removeButton']);
}
currentUsers($connection);
?>
Please see the scripts below. Onclick of Add gives an error when a php variable ($var)is used, however it will work with a number - i.e. if the line in index.php:
echo '<button id="1" onclick="company_add(\''.$var.'\');">Add</button>';
Is changed to something like:
echo '<button id="1" onclick="company_add(',57776,');">Add</button>';
What am I missing please?
Index.php:
<html>
<head>
<script type ="text/javascript">
function company_add(company_name) {
$.post('company_add.php', {company_name:company_name}, function(data) {
if (data == 'success'){
alert("Cool");
} else{
alert(data);
}
});
}
</script>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<?php
include 'connect.php'; //Generic connect file
$var = 'Name';
echo '<button id="1" onclick="company_add(\''.$var.'\');">Add</button>
<br/>';
?>
</body>
</html>
company_add.php:
<?php
include 'connect.php';
function company_exists($company_name) {
return (mysql_result(mysql_query("SELECT COUNT(`company_name`) FROM
`company` WHERE `company_name` = $company_name"), 0) == 0 ) ? false :
true;
}
function add_company($company_name){
mysql_query("INSERT INTO `company` (`id`, `company_name`) values ('',
".$company_name.")");
}
$company_name = $_POST['company_name'];
if (company_exists($company_name) === true) {
echo 'Company already added';
} else {
add_company($company_name);
echo 'success';
}
?>
Use that line like this:
echo "<button id='1' onclick='company_add('" . $var . "');'>Add</button>";
In case if you already have commas after and before the value of the $var you should trim it.
So use it like this:
$var = ltrim(",", $var);
$var = rtrim(", ", $var);
echo "<button id='1' onclick='company_add('" . $var . "');'>Add</button>";
And for your information yes you can even use a String instead of a Number too.
And UPDATE the functions:
function company_exists($company_name) {
$company_name = mysql_real_escape_string($company_name);
$query = "SELECT * FROM company WHERE company_name = '{$company}'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0) {
return true;
}else{
return false;
}
}
function add_company($company_name){
$company_name = mysql_real_escape_string($company_name);
$query = "INSERT INTO company (id, company_name) VALUES ('', '{$company_name}')";
return mysql_query($query);
}
If you are using id field of that company table as AUTO_INCREMENT then you can leave the id field NAME & VALUE in the INSERT Statement.
Like This in the add_company Function:
$query = "INSERT INTO company (company_name) VALUES ('{$company_name}')"