MySQL query search includes results from wrong column - javascript

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.

Related

Combine PHP with Javascript to remove item from cart

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

PHP running AJAX script works only once

I have this strange issue, happening to my PHP script, On page load the AJAX script runs and also after the second time the AJAX script runs it works and sends data to PHP, but i seem to not understand why the PHP script doesn't process the incoming POST request the second time it is sent in when i clean the input text box and type again, i get a blank response.My code for more expatiation.
index.php :
<input type="text" onkeyup="searchmedia(this)" placeholder="Search for seller with UNIQUE ID or Name.">
<div id="resut" style="margin-top:-24px!important;">
//where the ajax result is returned
</div>
<div style="margin-top:-24px!important;" id="normal">
//bla bla data here
</div>
<div id="hui" style="display:none;"><img src="../ajax5.gif">
</div>
<script>
function searchmedia(e) {
var tuq = $(e).val();
if (tuq == "") {
$('#resut').hide();
$('#normal').show();
$('#hui').hide();
} else {
$('#normal').hide();
$('#hui').show();
$.ajax({
type: 'POST',
url: 'sellersmessageajax.php',
data: {tuq: tuq},
timeout: 5000,
cache: false,
success: function (r) {
//console.log(r);
$('#resut').html(r);
$('#normal').hide();
$('#hui').hide();
},
error: function () {
alert("Could not search, reload the page and try again.");
$('#normal').show();
$('#hui').hide();
}
});
}
}
</script>
sellersmessageajax.php :
<?php include('../connect.php'); ?>
<?php
if (isset($_POST['tuq']))
{
$term = $_POST['tuq'];
$term = mysqli_real_escape_string($con,
$term); //WHEN I ALERT HERE THE SECOND TIME I SEE THE INPUT TEXT DATA THAT CAME IN BUT PLEASE CHECK AFTER THE **FOREACH**
$condition = '';
$query = explode(" ", $term);
foreach ($query as $text)
{
$condition .= "name LIKE '%" . mysqli_real_escape_string($con,
$text) . "%' OR reign_uniqeer LIKE '%" . mysqli_real_escape_string($con, $text) . "%' OR ";
}
//WHEN I ALERT HERE I GET NOTHING
$condition = substr($condition, 0, -4);
$zobo = "ORDER BY name";
$sql_query = "SELECT * FROM sellers_login WHERE " . $condition . $zobo;
$result = mysqli_query($con, $sql_query);
if (mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_array($result))
{
$v_ida = $row['id'];
$v_namea = $row['name'];
$v_reign_uniqeera = $row['reign_uniqeer'];
?>
<div style="border-bottom:0.1px solid #eee;padding-bottom:20px;margin-top:20px;">
<a class="zuka" title="<?php echo $v_ida ?>" id="<?php echo $v_ida ?>"
style="color:#666;text-decoration:none;outline:none!important;cursor:pointer;">
<b style="color:blue;"><?php echo $v_namea ?></b>
<br/>
<div style="height:auto;max-height:30px;">
<b>UNIQUE ID :</b> <b style="color:red;"><?php echo $v_reign_uniqeera ?></b>
</div>
</a>
</div>
<?php
}
}
else
{
?>
<h1 class="zuka" style="text-align:center;margin-top:20%;"> No result found.</h1>
<?php
}
}
?>
Second time after clearing the data result set to hide. second time data is returning but it's hide
Add this line in ajax success block
$('#resut').show(); // Add this line
you are sending the var tuq wrongfully. Try this:
data : {"tuq": tuq}

How to check the ajax response for errors list

So I am using ajax and php to 'create a post' which allows you to upload images along with text. Currently I have the php working to check if the post has any content and if it has an image, and validating everything. However the problem is when I get a response I am prepending it to the post feed, but this makes it so that when there is an error it also prepends it to the feed. What I would like to do is append the errors to a separate div called errors.
Here is my php (I'm just starting with php and if something is wrong or could have been done easier with less work, please let me know.)
<?php
require_once('../dbconnect.php');
include_once( INCLUDES_PATH .'functions.php');
$body = $_POST["body"];
$image = 'image';
$user_id = $_SESSION['user_id'];
if( empty($_FILES[$image]['name']) ){
$has_image = 0;
}else{
$has_image = 1;
}
$postEmpty = 0;
if( empty($_FILES[$image]['name']) && empty($body) ){
$postEmpty = 1;
die();
}
// validate post
if( $postEmpty == 0 && !empty($body) ){
$cleanBody = clean_input($body);
}
// validate image (if any)
if( $has_image == 1 ){
//check if directory exist if not create it
if (!file_exists(HOME_PATH ."users/user_".$user_id)) {
mkdir(HOME_PATH ."users/user_".$user_id, 0777, true);
}
if (!file_exists(HOME_PATH ."users/user_".$user_id."/posts")) {
mkdir(HOME_PATH ."users/user_".$user_id."/posts", 0777, true);
}
//Set file upload path
$path = "../users/user_".$user_id."/posts/"; //with trailing slash
//Set max file size in bytes
$max_size = 2000000;
//Set default file extension whitelist
$whitelist_ext = array('jpeg','jpg','png','gif');
//Set default file type whitelist
$whitelist_type = array('image/jpeg', 'image/jpg', 'image/png','image/gif');
// Create an array to hold any output
$errors = array();
// Get filename
$file_info = pathinfo($_FILES[$image]['name']);
$name = $file_info['filename'];
$ext = $file_info['extension'];
//Check file has the right extension
if (!in_array($ext, $whitelist_ext)) {
$errors[] = "Invalid file Extension";
}
//Check that the file is of the right type
if (!in_array($_FILES[$image]["type"], $whitelist_type)) {
$errors[] = "Invalid file Type";
}
//Check that the file is not too big
if ($_FILES[$image]["size"] > $max_size) {
$errors[] = "File is too big";
}
//If $check image is set as true
if (!getimagesize($_FILES[$image]['tmp_name'])) {
$errors[] = "Uploaded file is not a valid image";
}
//Create full filename including path
if ($random_name) {
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$errors[] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
} else {
$newname = $name.'.'.$ext;
}
//Check if file already exists on server
if (file_exists($path.$newname)) {
$errors[] = "A file with this name already exists";
}
if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
}
// if no errors:
// upload image (if any) and retrieve filename
if( $imageError == 1 ){
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
die();
}
}else{
//Create full filename including path
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$errors[] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
//Check if file already exists on server
if (file_exists($path.$newname)) {
$errors[] = "A file with this name already exists";
}
if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
die();
}
}
if (move_uploaded_file($_FILES[$image]['tmp_name'], $path.$newname)) {
$uploadSuccesfull = 1;
}else {
$errors[] = "Server Error!";
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
die();
}
}
}
}
// if no errors:
// save post (with filename if any); if it fails, delete image (if any)
if( $has_image == 1 ){
$query = "INSERT INTO posts
(user_id, body, image, has_image, date)
VALUES
('$user_id', '$body', '$newname', '$has_image', now())";
}else{
$query = "INSERT INTO posts
(user_id, body, has_image, date)
VALUES
('$user_id', '$body', '$has_image', now())";
}
$result = $db->query($query);
// send response
//check to make sure the user was added
if( $db->affected_rows == 1 ){
$user_id = $_SESSION['user_id'];
$post_id = $db->insert_id;
$query = "SELECT post_id, body, image, has_image
FROM posts
WHERE post_id = $post_id
LIMIT 1";
$result = $db->query($query);
if($result->num_rows == 1){
$row = $result->fetch_assoc();
}
$queryuser = "SELECT *
FROM users
WHERE user_id = $user_id
LIMIT 1";
$resultuser = $db->query($queryuser);
if($resultuser->num_rows == 1){
$rowuser = $resultuser->fetch_assoc();
}
if(!empty($row['avatar'])){ $userpic = $row['avatar']; }else{ $userpic = HOME_URL . 'img/avatar.jpg'; }
if($row['has_image'] == 1){
?>
<article class="post">
<div class="post-head cf">
<a class="userpic" href=""><img src="<?php echo $userpic ?>" alt="<?php echo $rowuser['username'] ?>"></a>
<a href="" class="username">
<?php echo $rowuser['username']; ?>
</a>
</div>
<img src="users/user_<?php echo $rowuser['user_id'] ?>/posts/<?php echo $row['image']; ?>" alt="">
<div class="post-body">
<div class="post-options">
<a class="likes" href="">156 likes</a>
</div>
<p>
<a class="username" href="">
<?php echo $rowuser['username'] ?>
</a>
<?php echo $row['body'] ?>
</p>
<hr />
<div class="cf">
<a class="like hide-text" href="javascript:;">Like This Post</a>
<form action="" class="comment">
<input type="text" placeholder="Add a comment">
</form>
</div>
</div>
</article>
<?php }else{ ?>
<article class="post no-img">
<div class="post-head cf">
<a class="userpic" href=""><img src="<?php echo $userpic ?>" alt="<?php echo $rowuser['username'] ?>"></a>
<a href="" class="username">
<?php echo $rowuser['username'] ?>
</a>
</div>
<div class="post-body">
<p>
<a class="username" href="">
<?php echo $rowuser['username'] ?>
</a>
<?php echo $row['body'] ?>
</p>
<div class="post-options">
<a class="likes" href="">1 like</a>
</div>
<hr />
<div class="cf">
<a class="like hide-text" href="javascript:;">Like This Post</a>
<form action="" class="comment">
<input type="text" placeholder="Add a comment">
</form>
</div>
</div>
</article>
<?php }
}else{
echo 'There was a database error';
}
die();
Here is my ajax call
$.ajax({
type: "post",
url: "includes/create-post.php",
data: new FormData(this),
processData: false,
contentType: false,
error: function (response) {
console.log(response);
},
success: function (response) {
$('section.feed').prepend(response);
$('article.post p').each(function () {
$(this).html(linkHashtags($(this).html()));
});
$('article.post p').each(function () {
$(this).html(linkatsymbols($(this).html()));
});
revealPosts();
}
});
For the die() you can simply put the statement die out of foreach like this:
if( $imageError == 1 ){
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
}
die();
}
.
.
.
.
.
.
if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
}
die();
}
if (move_uploaded_file($_FILES[$image]['tmp_name'], $path.$newname)) {
$uploadSuccesfull = 1;
}
else {
$errors[] = "Server Error!";
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
}
die();
}
But since you want to display the errors in some other element, you need a way to check whether the output you are receiving is an error. So try replacing your code with this:
// if no errors:
// upload image (if any) and retrieve filename
if( $imageError == 1 ){
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}
else{
//Create full filename including path
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$errors[] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
//Check if file already exists on server
if (file_exists($path.$newname)) {
$errors[] = "A file with this name already exists";
}
if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}
if (move_uploaded_file($_FILES[$image]['tmp_name'], $path.$newname)) {
$uploadSuccesfull = 1;
}
else {
$errors[] = "Server Error!";
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}
}
}
And in your AJAX success call do something like this:
success: function (response) {
var obj = JSON.parse(response);
var errorCode = obj.responseCode;
var errorSet = obj.items;
if(errorCode == 0) {
$.each(errorSet, function(i, v) {
console.log('<li>'+v+'</li>');
}
}
//Your rest of the code
BTW, its better if you separate your code from your design.

Why is my angularjs multiselect interface not working?

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.

Ajax status received but not applying next steps

I have a comment system in which user comments and through ajax it validates the data and sent to .php page. The problem is it receives the status=1 but does not apply the else if Ajax code. I am stuck here. Any suggestions or help will be highly regarded.
AJAX
<script type="text/javascript">
$(document).ready(function() {
$("#submit_comment").click(function() {
var proceed = true;
$(" #comment_form textarea[required=true]").each(function(){
$(this).css('border-color','');
if(!$.trim($(this).val())){ //if this field is empty
$(this).css('border-color','red'); //change border color to red
proceed = false; //set do not proceed flag
}
});
if(proceed)
post_data = {
'user_email' : $('input[name=email]').val(),
'pid' : $('input[name=productid]').val(),
'msg' : $('textarea[name=comment]').val()
};
$.post('comments.php', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error">'+response.text+'</div>';
}
else if(response.status && response.type != 'error')
{
output = '<div class="success">'+response.text+'</div>';
$(response.html).hide().insertBefore('#comment_form').slideDown();
$(" #comment_form textarea[required=true]").val('');
$("#comment_form #comment_body").slideUp();
}
$("#comment_form #comment_results").hide().html(output).slideDown();
}, 'json');
});
//reset previously set border colors and hide all message on .keyup()
$("#comment_form input[required=true], #comment_form textarea[required=true]").keyup(function() {
$(this).css('border-color','');
$("#result").slideUp();
});
});
</script>
Form
<?php
include "comment.php";
$comments = array();
$result = mysqli_query($con,"SELECT * FROM comments where product_id='$id' ORDER BY dt LIMIT 5");
while($row = mysqli_fetch_assoc($result))
{
$comments[] = new Comment($row);
}
?>
<?php
foreach($comments as $c){
echo $c->markup();
}
?>
</div>
<?php
}
}
?>
<div class="form-style" id="comment_form">
<div id="comment_results"></div>
<div id="comment_body">
<input type="hidden" name="email" id="email" value="<?php echo $email?>">
<input type="hidden" name="productid" id="productid" value="<?php echo $pid?>" />
<label for="field5"><span>Comment: <span class="required">*</span></span>
<textarea name="comment" id="comment" class="textarea-field" required="true"></textarea>
</label>
<label>
<span> </span><input type="submit" id="submit_comment" value="Submit"">
</label>
</div>
</div>
comment.php
<?php
class Comment
{
private $data = array();
public function __construct($row)
{
$this->data = $row;
}
public function markup()
{ $d = &$this->data;
// Converting the time to a UNIX timestamp:
$d['dt'] = strtotime($d['dt']);
// Needed for the default gravatar image:
return '
<div class="comment">
<div class="name">'.$d['email'].'</div>
<div class="date" title="Added at '.date('H:i \o\n d M Y',$d['dt']).'">'.date('d M Y',$d['dt']).'</div>
<p>'.$d['body'].'</p>
</div>
';
}
}
?>
comments.php
<?php
include("db/db.php");
include "comment.php";
if($_POST)
{
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$user_name = filter_var($_POST["user_email"], FILTER_SANITIZE_STRING);
$pid = filter_var($_POST["pid"], FILTER_VALIDATE_INT);
$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
$arr = array();
//additional php validation
if(strlen($message)<3){ //check emtpy message
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
mysqli_query($con,"INSERT INTO comments(email,body,product_id) values('$user_name','$message','$pid')");
$arr['dt'] = date('r',time());
$arr['id'] = mysql_insert_id();
$res=mysqli_query($con,$query);
$arr = array_map('stripslashes',$arr);
$insertedComment = new Comment($arr);
if(!$res)
{
$output = json_encode(array('type'=>'error', 'text' => 'Cannot recieve your comment.'));
die($output);
}else{
$output= json_encode(array('type'=>'message', 'text' => 'Hi '.$user_name .' Thank you for your review','status'=>1,'html'=>$insertedComment->markup()));
echo $output;
die($output);
}
}
?>

Categories

Resources