Ajax search results with on click result to download file - php

MY INDEX PAGE
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Some name</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<br />
<h2 align="center">Search by name</h2><br />
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Search</span>
<input type="text" name="search_text" id="search_text" placeholder="Enter model / search here" class="form-control" />
</div>
</div>
<br />
<div id="result"></div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
AND MY fetch.php PAGE
which is used to get data from the database tables and output results.
I also added if the result is > 50 it will ask to enter few more characters because if I don't add if result > 50 then my page took 20sec to display all data because my database table has 25000 entries.
<?php
$connect = mysqli_connect("localhost", "root", "PASSWORD", "DATABASE");
if(isset($_POST["query"]))
{
$search = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM files
WHERE Name LIKE '%".$search."%'
";
}
else
{
$query = "
SELECT * FROM files ORDER BY ID
";
}
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) < 500)
{
$output1 .= '
<div class="table-responsive">
<table class="table table bordered">
<div>
<th>Name</th>
<th>URL</th>
<th>Extension</th>
<th>Download</th>
</div>
';
while($row = mysqli_fetch_array($result))
{
$output2 .= '
<tr>
<td>'.$row["Name"].'</td>
<td>'.$row["URL"].'</td>
<td>'.$row["Extension"].'</td>
</tr>
';
}
if(mysqli_num_rows($result) > 0)
{
echo "$output1";
echo "$output2";
}
else
{
echo 'no results found';
}
}
else
{
echo 'Please enter few more charecters';
}
?>
I want href link for each of my results and on the click, it should download a file from ./"URL" column from a database table.
My database looks like this:
AND MY CURRENT PAGE IS http://mss1996.ddns.net:8008/files
I tried adding < a href=".$row["URL"]."> in outpur'array' but it destroys my page.

You should be able to easily add the URL field to form a valid URL if the contents of that field is indeed a valid URL. What I see missing form your code is http or https if it's an external link. If it's a relative link within the page then you're ok. Then add the </a> to close the link. So you'd form your table column like this:
echo '<td>' . $row["URL"] . '</td>';

Related

Is there any way in PHP to store $variable of $variable in session

I created a web-page,where you can search plant's scientific name. Type plant name in search_text it will give you results in search_result(live search like google and facebook search bar) . Ex: when you will type C in search input, in search result you will get C related search. Like C typed in search input, in search result it will start showing Cucumber(Cucumis sativus), Capsicum(Capsicum annuum), etc.
Now I want when you will click on Cucumber(Cucumis sativus) in search result, it have to direct to home.php/Cucumber . Or when user click on Capsicum(Capsicum annuum), it have to direct on home.php/Capsicum .
And on home.php in body tag I want to display plant name with their scientific name. And in para tag information related to plant search result.
index.php
<!DOCTYPE html>
<html>
<head>
<title>Search</title>
<style type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </style>
<style type="text/javascript">
function searchq() {
var searchTxt = $("input[name='search']").val();
$.get("search.php", {searchVal: searchTxt}, function(output) {
$("#output").html(output);
});
}
</script>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="search" id="myInput1" autocomplete="off"
placeholder="Search username..." onkeydown="searchq(); " />
<input type="submit" value=">>"/>
</form>
<br>
<div id="output"></div>
</body>
</html>
search.php
<?php
$con = mysqli_connect('localhost', 'root');
mysqli_select_db($con, 'plant');
$output = '';
if (isset($_GET['searchVal'])) {
$searchq = $_GET['searchVal'];
$sql = "select * from type where plant like '%$searchq%'";
$query = mysqli_query($con, $sql) or die("could not search");
$count = mysqli_num_rows($query);
if ($count == 0) {
$output = 'There is no serach result';
} else {
while ($row = mysqli_fetch_array($query)) {
$plantname = $row['plant'];
$sciencename = $row['species'];
$id = $row['id'];
$output .= '<div>' . $plantname . ' ' . $sciencename . '</div>';
}
}
}
echo '<a herf="home.php/">' . $output . '</a></div>';
?>
There are many ways of doing this
Passing the name of the plant as a GET param is not an option?
You could do
echo "<a href='home.php?plantname={$plantname}' target='_blank'>{$output}</a></div>";
As the response of your server, that would create the link and in home.php you retrieve the plant name with $_GET['plantname'].
in home.php you do
if(isset($_GET['plantname'])){
echo $_GET['plantname'];
}
Please correct this line in index.php
<style type="text/javascript">
with
<script type="text/javascript">

Autocomplete textbox to use in a form

i'm trying to create an autocomplete box for a form.
Basically what I want to achieve is a textarea field that allows me to search the database for names belonging to a table and add them to a table through a form.
I managed to create this, but it allows me to search only one name at a time, while I would need to look for more names to add to the same textarea.
Basically I have a textarea and this must give me the possibility to insert more names:
name1
name2
...
Where each name is chosen from the drop-down menu that is created. In this way I could go to insert more "names" in the database.
auto_complete.php
<!DOCTYPE html>
<html>
<head>
<title>Autocomplete TextBox</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<style>
ul{
background-color:#eee;
cursor:pointer;
}
li{
padding:12px;
}
</style>
</head>
<body>
<br /><br />
<div class="container" style="width:500px;">
<form method="post" action="insert_db.php">
<h3 align="center">Box Text</h3><br />
<label>Enter Name</label>
<br> <textarea name="nominativo" rows="5" cols="30" placeholder="Name Surname" id="nominativo" class="form-control"" ></textarea><br>
<input type="submit" value="Invia">
<div id="nominativoList"></div>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#nominativo').keyup(function(){
var query = $(this).val();
if(query != '')
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#nominativoList').fadeIn();
$('#nominativoList').html(data);
}
});
}
});
$(document).on('click', 'li', function(){
$('#nominativo').val($(this).text());
$('#nominativoList').fadeOut();
});
});
</script>
search.php
<?php
$conn = mysqli_connect("localhost", "root", "123456789", "Personale");
if(isset($_POST["query"]))
{
$output = '';
$query = "SELECT * FROM Squadra WHERE Nominativo LIKE '%".$_POST["query"]."%'";
$result = mysqli_query($conn, $query);
$output = '<ul class="list-unstyled">';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '<li>'.$row["Nominativo"].'</li>';
}
}
else
{
$output .= '<li>Country Not Found</li>';
}
$output .= '</ul>';
echo $output;
}
?>
insert_db.php
<?php
$conn = mysqli_connect("localhost", "root", "123456789", "Personale");
$nominativo = $_POST['nominativo'];
$sql = "INSERT INTO Prenotazione (Nominativo) VALUES ('$nominativo')";
$result = mysqli_query($conn,$sql);
?>
In your opinion how can i do??
Thank you for your attention and for your time.

How to insert into MySQL HTML Form data?

I checked a lot of articles and I don't understand it how to insert data into a MySQL table. What is wrong? I guess that my Ajax request is already wrong.
I would be happy to get help!!!
I did not write programs since 20 years. My coding is for sure not good, but I need to get it running.
Any help would be very appreciated!
The code that follows does not INSERT INTO and does not UPDATE. Why?
Here is the source:
articles.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head>
<meta charset="UTF-8" />
<title>SoB - Administration</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/scroll.js"></script>
<script type="text/javascript" src="js/producttemplate.js"></script>
<script type="text/javascript" src="js/jquery.js" ></script>
<style type="text/css">.buttonarea: (\a)</style>
<script type="text/javascript">
<!--
var js_string;
document.getElementById("recordWrite").disabled = true;
var lastPreviousNext = "";
var date = new Date();
var mysqlDateTime;
var yyyy = date.getFullYear();
var mm = date.getMonth() + 1;
var dd = date.getDate();
var hh = date.getHours();
var min = date.getMinutes();
var ss = date.getSeconds();
mysqlDateTime = yyyy + '-' + mm + '-' + dd + ' ' + hh + ':' + min + ':' + ss;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// No submit by onclick
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
elem = document.getElementById('buttonID');
function stop(e) {
e.preventDefault(); // browser - don't act!
e.stopPropagation(); // bubbling - stop
return false; // added for completeness
}
elem.addEventListener('click', stop, false);
// this handler will work
elem.addEventListener('click', function() { alert('I still work') }, false);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function jsRecordInsertWrite()
{
document.getElementById('formheadline').innerHTML = 'Article Database - I save the new item';
document.getElementById("recordWrite").disabled = true;
js_articles[0]=""; // set auto increment id to NULL
// ... the AJAX request is successful
var updatePage = function (response) {
alert("insert record successful");
};
// ... the AJAX request fail
var printError = function (req, status, err) {
alert("insert record failed");
};
// Create an object to describe the AJAX request
var ajaxOptions = {
url: 'writearticle.php',
dataType: 'json',
success: updatePage,
error: printError
};
// Initiate the request!
$.ajax(ajaxOptions);
}
// -->
</SCRIPT>
</head>
<body class="page page-id-11505 page-template-default" onload="jsRecordCurrent();">
<div id="page-wrap">
<?php
include('includes/header.html');
?>
<div id="container-main">
<div id="main-content">
<div class="post" id="post-11505">
<title>SoB - Administration</title>
<div class="entry">
<form id="form_articles" method="post" action="<?= $_SERVER['PHP_SELF'] ?>" name="form_articles">
<table border="0" cellpadding="0" cellspacing="5">
<tr>
<td align="right">
<span style="padding-right:20px">Item</span>
</td>
<td>
<input id="Item" name="Item" type="text" maxlength="100" size="25"/>
</td>
</tr>
<tr>
<td align="right">
<span style="padding-right:20px">Item Category</span>
</td>
<td>
<input name="ItemCategory" type="text" maxlength="100" size="25" />
</td>
</tr>
<tr id="buttonarea">
<td align="right" colspan="2">
<hr noshade="noshade" />
<input id="recordInsertWrite" type="button" name="recordInsertWrite" value=" Save New Record " onclick="jsRecordInsertWrite()" />
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
<div id="aside">
</div>
</div> <!-- End of main container -->
</div><!-- END Page Wrap -->
</body>
</html>
writearticle.php
<?php
$link = mysql_connect('test.test.com:3306', 'admin0', 'star1star1star0');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('sob', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
// Escape user inputs for security
$ID = mysql_real_escape_string($_POST['ID']);
$Item = mysql_real_escape_string($_POST['Item']);
$ItemCategory = mysql_real_escape_string($_POST['ItemCategory']);
if('$ID' == '')
{
$sql = "INSERT into articles values(NULL,'$Item','$ItemCategory')";
$query = mysql_query($sql);
if(!$query)
{
echo '<script type="text/javascript">alert("error");</script>';
}
else
{
echo '<script type="text/javascript">alert("ok");</script>';
}
}
else
{
$sql = "UPDATE articles SET Item='$Item',ItemCategory='$ItemCategory')";
$query = mysql_query($sql);
if(!$query)
{
echo '<script type="text/javascript">alert("update error");</script>';
}
else
{
echo '<script type="text/javascript">alert("update ok");</script>';
}
}
?>

How can i retrieve multiple values into my jquery form from php?

Basically i want a form that retrieves the value 1 or 0 to see whether an email exists within the form, and i also want to retrieve the name of the 'username' column which is on the same row as the email.
Here is the javascript/php script ( i start here ) :
http://pastebin.com/zB0Umyyb
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
$("#tabs").tabs();
});
</script>
<script type="text/javascript">
$(document).ready(function() {
//the min chars for username
var min_chars = 3;
//result texts
var characters_error = 'Minimum amount of chars is 3';
var checking_html = 'Checking...';
//when button is clicked
$('#check_email_availability').click(function(){
//run the character number check
if($('#email').val().length < min_chars){
//if it's bellow the minimum show characters_error text
$('#email_availability_result').html(characters_error);
$(checking_html).hide();
}else{
//else show the cheking_text and run the function to check
$('#email_availability_result').html(checking_html);
check_availability();
$(checking_html).hide();
}
});
});
//function to check username availability
function check_availability(){
//get the username
var email = $('#email').val();
//use ajax to run the check
$.post("check_email.php", { email: email },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
$('#email_availability_result').html('<span class="is_available"><b>' +email + '</b> is Available</span>');
}else{
//show that the username is NOT available
$('#email_availability_result').html('<span class="is_not_available"><b>' +email + '</b> has already been refered</span>');
}
});
}
</script>
</head>
<body style="font-size:62.5%;">
<?
require ("config/config.php");
$result = mysql_query('select * from refer where email = "user#example.com" AND referred = "true"');
$row = mysql_fetch_array($result);
$usercheck = $row['username'];
?>
<div id="tabs">
<ul>
<li><span>Refer</span></li>
<li><span>Referal History</span></li>
<li><span>Rewards</span></li>
</ul>
<div id="fragment-1">
<form>
<p>Minecraft User:
<input type='text' id='username'>
</p>
<p>Email Address:
<input type='text' id='email'> <input type='button' id='check_email_availability' value='Check Availability'>
</p>
</form>
<script>
$(document).ready(function() {
$("button").button();
});
</script>
<button> Refer! </button>
</br>
<div id='username_availability_result'></div>
</br>
<div id='email_availability_result'></div>
</div>
<div id="fragment-2">
<table border="1">
<tr>
<th>User</th>
<th>Referal Request</th>
</tr>
<tr>
<td>MrMan121</td>
<td>Pending</td>
</tr>
<tr>
<td>olimoli123</td>
<td>Accepted</td>
</tr>
</table>
</div>
<div id="fragment-3">
Rewards include:
dadadad.
</div>
</div>
</body>
</html>
And here is the php script it talks to:
http://pastebin.com/tQppn84s
<?php
//connect to database
require ("config/config.php");
//get the username
$email = mysql_real_escape_string($_POST['email']);
//mysql query to select field username if it's equal to the username that we check '
$result = mysql_query('select email from refer where email = "'. $email .'" AND referred = "true"');
$row = mysql_fetch_array($result);
$usercheck = $row['username'];
//if number of rows fields is bigger them 0 that means it's NOT available '
if(mysql_num_rows($result)>0){
//and we send 0 to the ajax request
echo 0;
}else{
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo 1;
}
?>
and $usercheck should check for the username.
You just need to change the formatting of the response, and modify how it's handled on receipt. For instance, instead of just echo 0; you could do something like (I wasn't sure how you wanted username used, so that was just a guess)
echo '{"available":false, "username":"'.$usercheck.'"}';
then, in your HTML page, you would
$.post("check_email.php", { email: email },
function(result){
response=jQuery.parseJSON(result);
//if the result is 1
if(response.available){
//show that the username is available
$('#email_availability_result').html('<span class="is_available"><b>' +email + '</b> is Available</span>');
}else{
//show that the username is NOT available
$('#email_availability_result').html('<span class="is_not_available"><b>' +email + '</b> has already been referred by user '+response.username+'</span>');
});
and, for the IS available case, you'd
echo '{"available":true}';

How can I use jQuery to submit a form using Ajax and then get the output of the page it submitted to?

I'm learning PHP and JavaScript, and I'm building a blogging platform. I'm working on the comment system. I want to check if the name field matches any users in the database, and if it does, then I want to display a message that the name is taken.
Here's the page that contains the form. (fullpost.php)
<!DOCTYPE html>
<html>
<?php
include ('functions.php');
connectDB();
$id = $_GET['id'];
$result = queryDB('SELECT * FROM posts WHERE id='.$id);
$post = mysql_fetch_array($result);
?>
<head>
<title><?php echo $post['title']; ?> - SimpleBlog</title>
<link rel="stylesheet" href="style.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.microsoft.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".commentform").validate();
});
</script>
</head>
<body>
<div id="header">
SimpleBlog
</div>
<div id="wrapper">
<?php
//post found, display it
if (mysql_num_rows($result) >0) {
echo '<div class="post">';
echo '<div class="postheader">';
echo '<h1>'.$post['title'].'</h1>';
echo '<h5>by '.$post['author'].' at '.$post['date'].' in '.$post['category'].'</h5>';
echo '</div>';
echo '<p>'.$post['fullpost'].'</p>';
echo '</div>';
//display comments form
?>
<div id="commentform">
<form action="commentsubmit.php" method="POST" class="commentform"/>
<?php
//if not logged in, display a name field
if (!loggedIn()) {
echo '<label for="author">Name: </label><br />';
echo '<input type="text" name="author" class="required"/><br />';
}
?>
<label for="comment">Comment: </label><br />
<textarea type="text" name="comment" class="required"></textarea><br />
<input type="hidden" value="<?php echo $id; ?>" name="postid"/>
<input type="submit" name="submit" Value="Submit" id="sendbutton" class="button"/>
</form>
</div>
<?php
}
else {
//no posts found
echo "That post doesn't exist!";
}
$result = queryDB('SELECT * FROM comments WHERE postid='.$id.' ORDER BY date DESC');
$numcomments = mysql_num_rows($result);
//comments found, display them
if (mysql_num_rows($result) >0) {
if (mysql_num_rows($result) == 1) {
echo '<h5>'.$numcomments.' Comment:</h5>';
}
if (mysql_num_rows($result) > 1) {
echo '<h5>'.$numcomments.' Comments:</h5>';
}
while($comment = mysql_fetch_array($result)) {
echo '<h6> by '.$comment['author'].' on '.$comment['date'].'</h6>';
echo '<p>'.$comment['text'].'</p>';
}
}
else {
//no comments found
echo '<h4>No comments</h4>';
}
?>
</div>
</body>
</html>
Here's the page it submits to. (commentnew.php)
<?php
//creates a new comment
include('functions.php');
//form submitted
if (isset($_POST['submit'])) {
//set $author if not logged in
if(!loggedIn()) {
//check if username is taken
connectDB();
$result = queryDB("SELECT * FROM users WHERE username='".$_POST['author']."'");
if (mysql_num_rows($result) > 0) {
die('That name is taken!');
}
else {
//username is not taken
$author = mysql_real_escape_string($_POST['author']);
}
}
else {
//user is logged in, set author to their username
$author = $_SESSION['username'];
}
//$author is set, submit
if (!empty($author)) {
$postid = mysql_real_escape_string($_POST['postid']);
$comment = mysql_real_escape_string($_POST['comment']);
$date = mysql_real_escape_string(date("Y-m-d")." ".date("H:i:s"));
queryDB('INSERT INTO comments (postid,date,author,text) VALUES ("'.$postid.'","'.$date.'","'.$author.'","'.$comment.'")');
echo 'Comment Sent!';
}
}
?>
I tried using $.ajax in the script tags, but it seems to do nothing. Can I get an example of how to properly use it? How do I get it to pull the message from commentnew.php? Am I going about checking for the username the wrong way? Should I be using jQuery's validation plugin somehow?
in general:
var form = $("form.commentform");
$.post(form.attr('action') , form.serialize(), function(data) {
alert("Response: " + data);
});
Try this
$("form.commentform").submit(function(e){
e.preventDefault();
$.post({
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(reponse){
//here response will contain whatever you send from the server side page
}
});
}):
Look into jquery ajax function. That's what I use. http://api.jquery.com/jQuery.ajax/

Categories