delete of instant search content with the delete of keyword - javascript

so i have search function with jquery to display instantly the content of what i search it is simple one here is the code:
function searchq() {
var searchTxt = $("input[name='search']") .val();
$.post("search.php", {searchVal: searchTxt}, function(output){
$("#output").html(output);
});
}
I use php for backend
<?php
$nonavbar = '';
include "init.php";
$output = '';
if (isset($_POST['searchVal'])) {
$searchq = $_POST['searchVal'];
//$searchq = preg_replace("#[^0-9a-z]#i", "", $searchq);
$stmt3 = $con->prepare("SELECT * FROM novel WHERE NovelName LIKE '%$searchq%'");
$stmt3->execute();
$rows = $stmt3->fetchAll();
$count = $stmt3->rowCount();
if ($count == 0) {
$output = "there is no search results!";
}else{
foreach ($rows as $row) {
$fname = $row['NovelName'];
$output .= "<div>
<ul>
<li>" . $fname . "</li>
</ul>
</div>";
}
}
}
echo ($output);
?>
and this is the html form for search
<form action="index.php" method="post">
<input type="text" name="search" class="form-control" autocomplete="off" placeholder="search novelname.." onkeydown="searchq()">
</form>
<div id="output" class="searchresult"></div>
everythong is work fine but I need to add function for delete the result when user delete the keywords for search bar honstly i didnt know much about javascript but the search work fine andi need to add this function plz help and thank

Instead of onkeydown use onblur event
<input type="text" name="search" class="form-control" autocomplete="off" placeholder="search novelname.." onblur="searchq()">
To clear the output use the method like below,and same funtion will work for onkeydown as well, but it is better to use blur event instead of onkeydown.
function searchq() {
var searchTxt = $("input[name='search']").val();
if(!searchTxt) { $("#output").html(""); return; }
$.post("search.php", {searchVal: searchTxt}, function(output){
$("#output").html(output);
});
}

Related

PHP login and set cookie properly

I have never worked with $_COOKIES, and now I've been given the task to make it work.
I have been following a couple of tutorials online.
Found here: http://www.phpnerds.com/article/using-cookies-in-php/2
And then here:https://www.youtube.com/watch?v=Dsem42810H4
Neither of which worked for me.
Here is how my code ended up. I shortened it as much as I could.
Starting with the index.php page, which contains the initial login form:
<form role="form" action="index.php" method="post" id="loginForm" name="loginForm">
<input type="text" class="form-control" id="username" name="username"
value="<?php if(isset($_COOKIE['username'])) echo $_COOKIE['username']; ?>" />
<input type="password" class="form-control" id="password" name="password"
value="<?php if(isset($_COOKIE['password'])) echo $_COOKIE['password']; ?>"/>
<button type="button" id="loginSubmit" name="loginSubmit" class="btn btn-primary btn-block btn-flat">Sign In</button>
<input type="checkbox" id="rememberme"
<?php if(isset($_COOKIE['username'])){echo "checked='checked'";} ?> value="1" />
</form>
Here is the JavaScript used to send the form values:
$('#loginSubmit').on('click', function()
{
var username = $('#username').val();
var password = $('#password').val();
var rememberme = $('#rememberme').val();
// skipping the form validation
$.post('api/checkLogin.php', {username: username, password: password, rememberme:rememberme}, function(data)
{
// the data returned from the processing script
// determines which page the user is sent to
if(data == '0')
{
console.log('Username/Password does not match any records.');
}
if(data == 'reg-user")
{
window.location.href = "Home.php";
}
else
{
window.location.href = "adminHome.php";
}
});
});
Here is the processing script, called checkLogin.php. This is where I attempt to set the $_COOKIE:
<?php
include ("../include/sessions.php");
if(isset($_POST['username']) && isset($_POST['password']))
{
$username = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['username'])));
$password = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['password'])));
$rememberme = $_POST['rememberme'];
$select = "SELECT username, fullname, password FROM users WHERE username = '".$username."'";
$query = mysqli_query($dbc, $select);
$row = mysqli_fetch_array($query);
$dbusername = htmlentities(stripslashes($row['username']));
$dbfullname = htmlentities(stripslashes($row['fullname']));
$dbpassword = htmlentities(stripslashes($row['password']));
if(password_verify($password, $dbpassword))
{
// setting sessions here
$_SESSION['username'] = $username;
$_SESSION['fullname'] = $dbfullname;
// here is where I attempt to set the $_COOKIE
if(isset($remember))
{
setcookie('username', $_POST['username'], time()+60*60*24*365);
setcookie('password', $_POST['password'], time()+60*60*24*365);
}
else
{
setcookie('username', $_POST['username'], false);
setcookie('password', $_POST['password'], false);
}
echo $username; // this gets sent back to the JavaScript
mysqli_free_result($query);
}
else
{
// username/password does not match any records
$out = 0;
echo $out;
}
}
?>
So now that I have attempted to set the $_COOKIE, I can try to print it to the home page, like so:
<?php echo 'cookie ' . $_COOKIE["username"]; ?>
To which does not work, because all I see is the word 'cookie'.
Besides that, when I log out, I am hoping to see the login form already filled out, which is the overall task I have been trying to complete, but have been unsuccessful at doing so.

PHP stored procedure called and working, page reload doesn't show new data

I am calling a JS function using a form:
HTML form:
<form class="addBlock" method="post" name="addBlockForm">
<input type="image" id="addBlockBtn" name="addedBlock" src="images/addCassette.png" onclick="addBlock( <?php echo $rowSize + 1 ?>)">
<input type="hidden" name="specNum" value="<?= $_SESSION["specNum"] ?>">
</form>
Javascript function:
function addBlock(num) {
var form = document.forms['addBlockForm'];
var nb = document.createElement("input");
nb.type = "hidden";
nb.name = "NewBlockNum";
nb.value = ([num]);
form.appendChild(nb);
addBlock.submit();
}
Which submits the form, triggering the Php stored procedure and refreshes the page
PHP Stored procedure:
if($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['NewBlockNum'])) {
// run the stored procedure for adding a new block
$callSP_addBlock = "{ CALL AddBlockByID( ?, ?, ? ) }";
$accID = $row[12];
$spID = $row[13];
$nBlockNum = $rowSize + 1;
$ad_params = array(
array($accID,SQLSRV_PARAM_IN),
array($spID, SQLSRV_PARAM_IN),
array($nBlockNum, SQLSRV_PARAM_IN),
);
/* Execute the query. */
$stmt6 = sqlsrv_query( $conn, $callSP_addBlock, $ad_params);
header('Location: '.$_SERVER['PHP_SELF']);
if( $stmt6 === false ) {
echo "Error in executing statement 6.\n";
die( print_r( sqlsrv_errors(), true));
}
}
The order on the page is the Php, then the JS function definition, and then the html form.
Everything works, however the new added data does not display in the page.
The data display code (that lives after the JS function, but before the form) is this
PHP Data display code:
<?php
do {
if (isset($row[15])) {
$timeStamp = //date_format($row[15], 'Y-m-d h:i');
$printedLabel = 'Printed ';
$printedClass = 'printed';
} else {
$timeStamp = '';
$printedLabel = '';
$printedClass = '';
}
if (isset($row[14])) {
$numOfPieces = $row[14];
$piecesLabel = 'Pieces ';
} else {
$numOfPieces = '';
$piecesLabel = '';
}
echo '<div class="'.$printedClass.'cassetteDataRow">
'.$row[9].'<br>
<form action="#" class="printForm" method="post" name="printedCass"><br>
<input type="image" id="cassPrintBtn" name="cPrinted" src="images/cassetteIcon.png" onclick="cassPrint(1)"><br>
<input type="hidden" name="'.$row[0].'" value="'.$row[0].'"><br>
<input type="hidden" name="specNum" value="'.$specNum.'"><br>
<input type="hidden" name="BlockID" value="'.$row[10].'"><br>
</form><br/>
'.$numOfPieces.' '.$piecesLabel.'<br>
'.$printedLabel.' '.$timeStamp.'
<input type="image" id="cassInfoBtn" src="images/cassettePrintBtn.png" onclick="div_show('.$row[10].')">
</div> <br/>';
} while ($row = sqlsrv_fetch_array($stmt));
?>
I have tried moving the php for the stored procedure call below the form (didn't work),I tried form action to $_SERVER['PHP_SELF'] and location.reload(); (also didn't work).
Any advice is greatly appreciated.Thank you

Download brochure depends on the hidden field value

I have an html website and using brochure download option with form. I have many forms for every project. I need only one form that downloads the brochure depends on the hidden input value of the project.
jQuery(".form-js-pop-vedam").submit(function () {
var thisform = jQuery(this);
jQuery('.required-error',thisform).remove();
var pmail = jQuery("#pmail").val();
var pphone = jQuery("#pphone").val();
var psubject = jQuery("#psubject").val();
var data = {'pmail':pmail,'pphone':pphone,'psubject':psubject}
if (pmail == "") {
jQuery("#pmail").after('<span class="form-description required-error">Required field.</span>');
}else {
jQuery("#pmail").parent().find('.required-error').remove();
}
if (pphone == "") {
jQuery("#pphone").after('<span class="form-description required-error">Required field.</span>');
}else {
jQuery("#pphone").parent().find('.required-error').remove();
}
if ( pmail != "" && pphone != "" ) {
jQuery.post("contact_us_pop-vedam.php",data,function (result) {
if (result == "done") {
thisform.prepend("<div class='alert-message success-amairo'><i class='icon-ok'></i><p><span>Vedam brochure was sent to your mail. Thank you!</span></p></div>");
jQuery("#pmail").val("");
jQuery("#pphone").val("");
}
});
}
return false;
});
<form class="form-style form-js-pop-vedam" action="contact_us_pop-vedam.php" method=post>
<input type="hidden" name="psubject" id="psubject" value="Brochure Download from Vedam Page">
<div class="col-md-6" ><input type=email class=required-item id=pmail name=pmail value="" aria-required=true placeholder="Your Email*"></div>
<div class="col-md-6 " ><input class=required-item aria-required=true id=pphone name=pphone value="" placeholder="Your Phone*"></div>
<div class="col-md-6 " ><input name=submit type=submit value="Download Now >" class="submit_buttom buttonColor-side" id="Brochure_Download"></div>
</form>
<!-- language: lang-php -->
<?php
function clean_text($text='') {
$text = trim($text);
$text = strip_tags($text);
$text = addslashes($text);
$text = htmlspecialchars($text);
return $text;
}
if (!$_POST) {
die();
}else {
if (empty($_POST["pphone"]) && empty($_POST["pmail"]) ) {
echo "all_empty";
}else if (empty($_POST["pmail"])) {
echo "empty_mail";
}else if (empty($_POST["pphone"])) {
echo "empty_phone";
}else {
// edit this only :)
$your_email = "me#myweb.com";
$pmail = clean_text($_POST["pmail"]);
$pphone = clean_text($_POST["pphone"]);
$psubject = clean_text($_POST["psubject"]);
$subject = "$psubject";
$headers = "From: leads#website.in" . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8'. "\r\n";
$msg = "New Brochure Download \n<br />";
$msg .= "Email : \t $pmail \r\n<br />";
$msg .= "Phone : \t $pphone \r\n<br />";
echo "done";
$done = #mail($your_email, $subject, $msg, $headers);
}if($done)
{
if(($pmail)) {
$headerRep = "From: Website <info#website.in>";
$subjectRep = "Greetings from website!";
$messageRep = "Hi, \n\r
Thanks for showing interest in our property \n\r";
$messageRep .="You can download the brochure here http://www.example.in/pdf/brochure.pdf";
#mail($pmail, $subjectRep, $messageRep, $headerRep);
}
}
}
?>
<!-- end snippet -->
Lets talk generally about word (hidden) .. We have 2 cases
1st case: the input with type="hidden" you can use a selector like this
in css
input[type="hidden"]{}
and in js
$('input[type="hidden"]') // you can use .val() or .attr() depending on data you want from it
to check if the form has input with type hidden
if($('form').find('input[type="hidden"]').length > 0){ // in submit event use $(this).find instead if $('form').find
// yes this is input with type hidden here
}else{
// no input with type hidden here
}
and while you said (depends on the hidden input value) you can check that with
if($('form').find('input[type="hidden"]').val() == 'something'){ // in submit event use $(this).find instead if $('form').find
// type input hidden value = something
}else{
// type input hidden value not = something
}
2nd case: :hidden and :visible and that's about element is visible or not which I don't think you will need it here

Uncaught ReferenceError: output is not defined when using jQuery $.post() in file file

I have a dynamic search which uses jQuery and a PHP search file to dynamically show the results below. I just changed my log in scripts and sessions; now i am having issues with a search bar that searches through the members in a DB. When I was going through the testing I see that on each keyUp the jQuery function runs properly but there is some sort of issue inside of my search.php file. It seems like there is no $userCount or $userCount = 0 because it will display "There Were No Search Results"which only happens when it equals $userCount== 0
Here are the parts of my index.php
<script type="text/javascript">
function searchUserQ(){
var searchTxt = $("input[name='userSearch']").val();
if (searchTxt == '') {
// $.post("includes/search.php", {searchVal:searchTxt},
// function(output){
// $("#userResults").html(output);
// });
}else{
$.post("includes/search.php", {searchVal:searchTxt},
function(output){
$("#userResults").html(output);
});
console.log(output);
}
}
</script>
<form class="editUser" action="index.php" method="post">
<h1>Search For Employee</h1>
<input type="text" name="userSearch" id="userSearch" placeholder="Search For Employee By First Or Last Name | Press Space To View All Employees" onkeyup="searchUserQ();" />
<submit type="submit" />
div id="userResults">
</div>
</form>
and here is my search.php file
<?php
// this file connects to the database
include("connect.inc.php");
if(isset($_POST['searchVal'])){
// turn that the user searched into a varible
$searchQ = $_POST['searchVal'];
// delete any symbols for security
$searchQ = preg_replace("#[^0-9a-z]#i", "", $searchQ);
$output = "";
// Search through these columns inside the main database
$userSearchQuery = mysql_query("SELECT * FROM dealerEmployees WHERE
firstName LIKE '%$searchQ%' or
lastName LIKE '%$searchQ%'
");
// count the number of results
$userCount = mysql_num_rows($userSearchQuery);
if($userCount == 0){
// $output = "There Were No Search Results";
}else{
while($row = mysql_fetch_array($userSearchQuery)){
// define dynamic varibles for each loop iteration
$id = $row['id'];
$firstName = $row['firstName'];
$lastName = $row['lastName'];
$address = $row['address'];
$phone = $row['phone'];
$email = $row['email'];
$passwordQ = $row['password'];
$permission = $row['permission'];
$photo = "images/" . $row['profilePhoto'];
$output .= "<li><div class='employeeSearch' style=\"background: url('$photo'); width: 75px; height: 75px\"></div><h6>" . $firstName . "</h6>" . " " . "<h6>" . $lastName . "</h6><a href='#' class='employee' data-firstName='$firstName' data-lastName='$lastName' data-address='$address' data-phone='$phone' data-email='$email' data-password='$passwordQ' data-permission='$permission' data-id='$id'>Select Employee</a></li>";
}
}
}
echo $output;
Any suggestions why this is happening?
The reason for the error in the title is that you have console.log(output) outside the callback function. This has two problems: First, the variable output is not in scope; second, it runs immediately, not after the AJAX call returns. Move it into the callback:
function searchUserQ(){
var searchTxt = $("input[name='userSearch']").val();
if (searchTxt != '') {
$.post("includes/search.php", {searchVal:searchTxt},
function(output){
console.log(output);
$("#userResults").html(output);
});
}
}

How to use AJAX to display the data retrieved by html-don?

I have 3 files: index.html, parse.php, profile.html
index.html: It has a form, where I give the link of profile.html and with the html-dom parsing in parse.php, I should get all the data on the same page, i.e index.html.
I am new to AJAX and did not use it till now.
How should I go through on doing the operation?
index.html:
<form action="parse.php" method="post" id="myForm">
Name: <input type="text" name="uurl"><br>
<input type="submit">
</form>
parse.php:
require 'simple_html_dom.php';
$url = $_POST['uurl'];
$html = file_get_html($url);
foreach ($html->find("span[class=full-name]") as $key => $name){
echo $name."<br>";
}
script:
<script>
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
</script>
index.html:
<form action="parse.php" id="myform" method="post">
Name: <input type="text" name="uurl" id="uurl"><br>
<input type="button" value="" >
</form>
<ul class="results"></ul>
Include jquery script tag, and add the following javascript code:
$(document).ready(function() {
$('#myform button').on('click', function() {
$.getJSON('/parse.php', { uurl: $('#uurl').val() }).done(function(a) {
var html = '';
if (a.results && a.results.length > 0) {
for (var i in a.results) {
html += '<li>' + a.results[i] + '</li>';
}
} else {
html += '<li class="error">No Results Found</li>';
}
$('ul.results').html(html);
});
});
});
In parse.php:
require 'simple_html_dom.php';
$url = $_POST['uurl'];
$results = array();
$html = file_get_html($url);
foreach ($html->find("span[class=full-name]") as $key => $name){
$results[] = $name;
}
echo json_encode(array('results' => $results));
So technically you aren't even using AJAX. Ajax is based on javascript and I don't see any javascript in your code.
Also, from what I understand, you don't need any PHP code to do what you're trying to.
Here is how you would do it. This would be the HTML.
<form action="parse.php" method="post">
Name: <input type="text" name="uurl" id="uurl"><br>
<input type="submit" id="submit-form">
</form>
<div id="container">
</div>
And then you would need this javascript:
var $url = $('#uurl');
var $button = $('#submit-form');
var $container = $('#container');
$button.on('submit', function(evt){
evt.preventDefault(); //to prevent the default form submission.
$.get($url.val(), function(response){
$container.html(response);
})
});
I have used jQuery for clarity, but it definitely not required.

Categories

Resources