Auto suggestion search result error in PHP - javascript

I am trying to implement search with auto suggestion in my script but unfortunately I am unable to understand why it is not giving values. I have created two files. One is HTML which has JavaScript functions and some HTML in to and the other one is PHP. Can you please help me to find out what problem is with the code which is not able to display records in the text box?
File: index.html
<!DOCTYPE html>
<script src="jquery-1.11.2.min.js"></script>
<script type="text/JavaScript">
function lookup(inputString){
if (inputString.length==0){
$('#suggestions').hide();
} else{
$.post("suggestions.php",{
queryString: "" + inputString + ""},
function(data){
$('#suggestions').html(data).show();
});
}
}
</script>
<html>
<form>
<input type="text" size="30" onkeyup="lookup(this.value);">
<div id="suggestions"></div>
</form>
<head lang="en">
<meta charset="UTF-8">
<title>Sandbox Page</title>
</head>
<body>
</body>
</html>
File: suggestions.php
<p id="searchresults"><?php
$db=new mysqli('localhost','root','','RateList');
if(isset($_POST['queryString'])){
$queryString=$db->real_escape_string($_POST['queryString']);
if(strlen($queryString)>0){
$query = $db->query("SELECT * FROM RateList.VoipRoutes" . $queryString);
if($query){
while ($result = $query ->fetch_object()){
echo '<a href="'.$result->name.'">';
$name=$result->name;
echo ''.$name.'';
}
}
}
}
?></p>

Your SQL query is malformed. If I type "kittens" into the text box, the SQL query will be:
SELECT * FROM RateList.VoipRouteskittens

Related

PHP/jQuery Instant Search Not Working

I'm trying out a tutorial to learn how to do instant search with PHP/jQuery. I can't seem to find why this code won't work. This search was working before when I had the PHP in the same file as the index, but when I moved it to another file, it stopped working. I keep getting this console error message with each keystroke: ReferenceError: Can't find variable: $_POST. Any help would be deeply appreciated.
index.php file
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset-utf-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function searchkey() {
var searchTxt = $("input[name='search']").val();
$_POST("search.php", {searchVal: searchTxt}, function(output) {
$("#output").html(output);
});
}
</script>
<title>Search</title>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="search" placeholder="Search for members..." onkeyup="searchkey();">
<input type="submit" value="Search">
</form>
<div id="output"></div>
</body>
</html>
search.php file (same location as index.php)
<?php
$connection = mysqli_connect('localhost','root','root','LBD');
$output='';
if(isset($_POST['searchVal'])){
$searchkey= $_POST['searchVal'];
$searchkey=preg_replace("#[^0-9a-z]#i", "", $searchkey);
$query = mysqli_query($connection,"SELECT * FROM members WHERE ownerName LIKE '%$searchkey%' OR companyName LIKE '%$searchkey%'") or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output="There was no search result!";
}
else{
while($row=mysqli_fetch_array($query)){
$oName=$row['ownerName'];
$cName=$row['companyName'];
$output .='<div>'.$oName.'<br/>'.$cName.'</div>';
}
}
}
echo ($output);
?>
Looks like you've used the PHP $_POST in your script..
Try to use:
$.POST
Try this
$.ajax({
url: "search.php",
type: 'POST',
data: {
searchVal: searchTxt
},
})
.done(function(output) {
$("#output").html(output);
});

How do I display a JavaScript alert using my PHP variables?

I am trying to bring up a javascript alert with my variables from php. My upload.php file so far is:
<?php
if(isset($_POST['btn-upload']))
{
$pic = rand(1000,100000)."-".$_FILES['pic']['name'];
$pic_loc = $_FILES['pic']['tmp_name'];
$folder="uploaded_files/";
if(move_uploaded_file($pic_loc,$folder.$pic))
{
?><script>alert('File successfully uploaded.\n![File Upload]('+window.location.href+')');
</script><?php
}
else
{
?><script>alert('Sorry, error while uploading file. Please try again');</script><?php
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Photo Uploader for use in markdown</title>
</head>
<body>
<h2>Photo Uploader & Markdown generator</h2>
<p>Click 'Choose file' to choose the file to be uploaded. The filename should appear. Then click 'upload'. <br>A popup should show you what to copy and paste.</p>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="pic" />
<button type="submit" name="btn-upload">upload</button>
</form>
</body>
</html>
I then have my html code which looks like (only the relevant part included):
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="pic" />
<button type="submit" name="btn-upload">upload</button>
The purpose of this script is to upload a picture to a server and then display the markdown code for the user to use that image. I am aiming to output the following if the file uploads correctly:
![Alternative Text](http://www.example.com/folder/photo.jpg)
I have tried the following:
<?php
if(isset($_POST['btn-upload']))
{
$pic = rand(1000,100000)."-".$_FILES['pic']['name'];
$pic_loc = $_FILES['pic']['tmp_name'];
$folder="uploaded_files/";
if(move_uploaded_file($pic_loc,$folder.$pic))
{
?><script>alert('File successfully uploaded.\n![File Upload]('+window.location.href+.$folder.'/'.$pic.')');</script><?php
}
else
{
?><script>alert('Sorry, error while uploading file. Please try again');</script><?php
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Photo Uploader for use in markdown</title>
</head>
<body>
<h2>Photo Uploader & Markdown generator</h2>
<p>Click 'Choose file' to choose the file to be uploaded. The filename should appear. Then click 'upload'. <br>A popup should show you what to copy and paste.</p>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="pic" />
<button type="submit" name="btn-upload">upload</button>
</form>
</body>
</html>
This results in a working webpage that uploads the file but does not show the js alert.
I have also tried the following:
<?php
if(isset($_POST['btn-upload']))
{
$pic = rand(1000,100000)."-".$_FILES['pic']['name'];
$pic_loc = $_FILES['pic']['tmp_name'];
$folder="uploaded_files/";
<script>var folder = "<?php echo $folder ?>";</script>
<script>var pic = "<?php echo $pic ?>";</script>
if(move_uploaded_file($pic_loc,$folder.$pic))
{
?><script>alert('File successfully uploaded.\n![File Upload]('+window.location.href+folder+'/'+pic+')');</script><?php
}
else
{
?><script>alert('Sorry, error while uploading file. Please try again');</script><?php
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Photo Uploader for use in markdown</title>
</head>
<body>
<h2>Photo Uploader & Markdown generator</h2>
<p>Click 'Choose file' to choose the file to be uploaded. The filename should appear. Then click 'upload'. <br>A popup should show you what to copy and paste.</p>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="pic" />
<button type="submit" name="btn-upload">upload</button>
</form>
</body>
</html>
This results in an http error 500
Any advice?
Many thanks,
You can create a function in php and call it where ever you need to call alert.
Function :
function alertMsg($str) {
print("<script>alert('$str')</script>");
}
And call in php as
//string
alertMsg("Success");
//php variable
$alertMsg = "Some alert message";
alertMsg($alertMsg);
//even you can concatenate both
alertMsg("This is an alert. ".$alertMsg);
Hope this helps.
Thanks.
In both attempts you're trying to mix PHP, HTML, and JavaScript as though they were all the same language. They are not. From the perspective of any one of them, code in another one of them is nothing but a string. They can't directly share variables and logic.
See how this line:
alert('File successfully uploaded.\n![File Upload]('+window.location.href+.$folder.'/'.$pic.')');
is attempting to use PHP code (both the variables and the syntax) directly in JavaScript. This is simply resulting in syntax errors in your JavaScript, which your browser's development console is pointing out to you. Instead, enclose the PHP code in <?php ?> tags and echo the result:
alert('File successfully uploaded.\n![File Upload]('+window.location.href+'<?php echo $folder.'/'.$pic ?>'+')');
The second attempt has the same problem, you're putting HTML/JavaScript directly in your PHP:
$folder="uploaded_files/";
<script>var folder = "<?php echo $folder ?>";</script>
This is resulting in PHP syntax errors, which your PHP logs are telling you about (as well as the 500 Internal Server Error you're getting).
PHP code needs to be in <?php ?> tags. Always. So this would be something like:
$folder="uploaded_files/";
?>
<script>var folder = "<?php echo $folder ?>";</script>
<script>var pic = "<?php echo $pic ?>";</script>
<?php
if(move_uploaded_file($pic_loc,$folder.$pic))
Note also that in HTML/JavaScript you don't need a <script> tag for every line of JavaScript code. You can have multiple lines of code in a single <script> element.
Using variable PHP in JS
<?php
if (isset($_POST['btn-upload'])) {
$pic = rand(1000,100000)."-".$_FILES['pic']['name'];
$pic_loc = $_FILES['pic']['tmp_name'];
$folder = "uploaded_files";
if (move_uploaded_file($pic_loc, $folder . '/' . $pic)) { ?>
<script>
alert("File successfully uploaded! " +
"\n" +
location.hostname +
"<?php echo '/' . $folder . '/' . $pic; ?>");
</script>
<?php
} else { ?>
<script>alert("Sorry, error while uploading file. Please try again");</script>
<?php
}
}
?>
location.hostname = $_SERVER['HTTP_HOST'] // localhost

How to handle google recaptcha with jquery?

i need a little info on google recaptcha. I want to grab the value of "g-recaptcha-response" that compares in the captcha.php file i inserted below in my jquery file and then send it to the captcha.php file using jquery $.post() method. I apologize if this is duplicate but i really cannot find someone with my same problem ;)
THE HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="AlterVista - Editor HTML"/>
<script src='https://www.google.com/recaptcha/api.js'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="handle_spam.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<div class="g-recaptcha" data-sitekey="6Lf8LxIUAAAAALg93pw24l53KTeqrIwl7kUY-opk"></div>
<button id="go">Register</button>
</body>
</html>
THE PHP
<?php
$captcha=$_POST['g-recaptcha-response'];
echo $captcha;
if(!$captcha){
echo 'You must verify yourself';
exit;
}
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=6Lf8LxIUAAAAACB9iqeOermR-rPOW0zcWRfoetBO&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false)
{
echo 'abort_all';
}else
{
echo 'success';
}
?>
THE JS
$(document).ready(function(){
$('#go').click(function(){
send=$('')
$.post('captcha.php',function(data){
alert(data);
});
});
});
Use this
<div class="g-recaptcha" data-callback="captchaCallback" data-sitekey="...">
and provide the function:
function captchaCallback(response) {
alert(response);
}

Increase URI length limit or change the code for transferring big text

I installed Apache2 server on linux Mint system to do some web development. I have a code where there is a text in <pre> tag. The php code makes a link to edit the text by transferring all text into edit page <textarea>.
The text transfers in URI. Well, as Apache has a URI length limit, I don't know how to transfer large amount of text.
I searched and found out that there is a way to change this limit, but I couldn't find out where it is set. Also I read that it is not good to use long URIs.
So, I have to either increase the URI length limit or change my code. I haven't figured out how, though. This is the piece of page where text is (story.php, stored in $s variable):
<!DOCTYPE html>
<?php session_start() ?>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="main.css">
<title>The story</title>
<style>
#story{border: darkolivegreen; border-style: solid ;border-width: 3px; padding: 10px }
pre{white-space: pre-wrap}
span{padding-right: 8px}
</style>
</head>
<body>
<?php
include "navigation.php";
$id=$_GET['id'];
//ar_dump($id);
$mysql=new mysqli("",databaseuser,databasepassword,database);
$set=$mysql->query("select title,story,creator,dateCreated,identifier from Stories where identifier='$id'");
if( $set==false) echo $mysql->error;
$record=$set->fetch_array();
//var_dump($record);
if($record)
{
$t=$record['title'];
//check
$s=htmlspecialchars_decode($record['story']);
$c=$record['creator'];
$time=$record['dateCreated'];
$storyid=$record['identifier'];
echo "<h1 id='heading'>$t</h1>";
echo "<h2>By $c on $time</h2>";
echo "<pre id='story' on>$s</pre>";
if(isset($_SESSION[username]))
$user=$_SESSION[username];
$q="SELECT class FROM Accounts WHERE identifier='$user'";
$result=$mysql->query($q);
$group;
if($res)
{
$group=$result->fetch_array()[0];
}
if(($user==$c && $group==users2) or $group==admins or $group==overseers)
{
$s=urlencode($s);
$link='editstory.php?sid='.$storyid.'&text='.$s;
echo "<a href='$link'>Edit</a>";
//echo "<button data-storyid='$storyid' data-story='$s' onclick=''>Edit</button> ";
echo "<button data-storyid='$storyid' onclick='deleteStory(this)'>Delete</button>";
}
This is the page where text transfers into (editstory.php):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Editing</title>
<link rel="stylesheet" href="main.css"
</head>
<body>
<?php
$storyid=$_GET['sid'];
$text=$_GET['text'];
$text=urldecode($text);
echo "<textarea id='text' rows='33' cols='200'>$text</textarea>
<button data-sid='$storyid' onclick='updatestory(this)'>Save</button>
"
?>
<script>
function updatestory(button) {
var sid=button.getAttribute('data-sid')
var text=document.getElementById('text')
var value=text.value;
console.log(text.value)
var request=new XMLHttpRequest()
request.onreadystatechange=function () {
if(request.readyState==4)
{
window.location='story.php?id='+sid;
console.log(request.responseText)
}
}
request.open('POST','updatestory.php',true)
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send('sid='+sid+'&text='+value)
}
</script>
</body>
</html>
There should be no reason to tamper with URI length.
You should instead send the story text data as HTTP POST message body, and the submission could be inside HTML form element.
See W3 PHP5 Form Handling
I couldn't figure out how to change my code, so I've increased URI length for now.

ajax form not finding javascript function

I can't seem to figure out what I'm doing wrong with this no matter how many things I try. I've looked through Google for a related issue but found nothing specific. Hopefully someone can help me.
The script runs through a external .js file calling a list of music albums, then listing the song of the album chosen via ajax. The user can then edit of delete the songs. Everything works fine until I submit the edited information through a form. When I click the submit button I get a web developer error "updateSong is not a function"
Here's the form:
<?php
include("database.php");
$song = $_GET['song'];
$query = "SELECT * FROM song INNER JOIN genre ON song.gID = genre.gID INNER JOIN album ON song.alID = album.alID WHERE sID = '$song'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
echo ("
<form action='#' method='POST' name='updateSong' onSubmit='updateSong(\"$song\")'>
<input name='songName' type='text' value='$row[songName]' />
<input type='text' id='genreSearch' name='genre' alt='Genre Search' onkeyup='searchSuggest();' autocomplete='off' value='$row[genreName]'/>
<div id='genre_search_suggest'></div>
<input name='songURL' type='text' value='$row[songUrl]' />
<input name='sID' type='hidden' value='$row[sID]' />
<input name='Submit' type='Submit' value='Update Song' />
</form>
");
}
?>
Here's the javascript:
function updateSong(sID) {
if(ajax) {
var song = sID;
alert("2");
ajax.open('get', './song_update.php' + encodeURIComponent(sID));
alert("3");
ajax.onreadystatechange = function() {
handleResponse(ajax);
}
ajax.send(null);
return false;
}
}
//EDIT//
Here's the page it's loaded into. I removed the unnecessary stuff around what this question is dealing with.
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<link href="artistPageStyle.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="javascripts/artistAjax.js"></script>
</head>
<body>
<div id="mediaPlayerBox">
<div id="artistAlbumList">
<?php
$query = "SELECT * FROM `album` INNER JOIN artist ON album.aID = artist.aID WHERE artist.LoginKey = '$token'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
echo ("<div id='artistAlbumBox'><div id='artistAlbum'><a href='#' onclick='loadAlbum($row[alID])'><img src='$row[albumCover]' width='75px' height='75px' border='0px' ></a></div><div id='artistAlbumLabel'>$row[albumName]</div></div>");
}
?>
</div>
</div>
</body>
</html>
Shouldn't it be: onSubmit='updateSong("$song")'?
try doing onSubmit='return updateSong($song)'
It's saying it is not a function because it isn't loaded, are you loading the external script in the display page at all?

Categories

Resources