I am trying to see if a username has already been taken in a mysql database and it does not seem to want to work. Ideally it would show as I was typing on the form. Any help would be greatly appreciated as I do not see anything wrong with the code.
On my main page is the code for the jquery, javascript and html.
The corresponding page is testusername.php.
<script type="text/javascript">
$(document).ready(function() {
$('#feedback').load('testusername.php').show();
$('#username_input').keyup(function() {
$.post('testusername.php', { username:form.username.value },
function(result) {
$('#feedback').html(result).show();
});
});
});
</script>
<form name='form'>
<fieldset>
<legend>Test Form</legend>
Username: <br /><input type='text' id='username_input' name='username'></input>
</fieldset>
</form>
<div id = "feedback"></div>
testusername.php is:
<?php
include 'functions2.php';
?>
<?php
$username = mysql_real_escape_string($_POST['username']);
$query1a = mysql_query("SELECT * FROM users WHERE username='$username'");
$count = mysql_num_rows($query1a);
if ($count==0)
{
echo "Available";
}
else {
echo "Username exists";
}
?>
This script should work to handle your client side part, Assuming you have jQuery loaded to your pafe properly.
<script type="text/javascript">
$(document).ready(function() {
$('#username_input').keyup(function() {
$.post('testusername.php', { username: $(this).val() },function(result){
$('#feedback').html(result).show();
});
});
});
</script>
For the server side, dont use * in the query. You may use something like SELECT 1 FROM .... Also you may want to make sure you are not going to be a victim of SQL Injection.
Related
So I have all this code that works fine. But it only shows the table records when I start typing inside the search field. I want all the records to be visible by default the moment I open the page.
I know this has something to do with the keyup function but is there a way to have all the records be visible by default before I typed anything inside the search field?
AJAX Live Search/ Input Code
<input type="text" id="search">
<div class="table-container" id="output"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#search").keyup(function(){
$.ajax({
type:'POST',
url:'search.php',
data:{
name:$("#search").val(),
},
success:function(data){
$("#output").html(data);
}
});
});
});
</script>
PHP Code
$select = "SELECT * FROM info WHERE name LIKE '%".$_POST['name']."%'";
$result = mysqli_query($conn, $select);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "
//table code.. ";
}
I want it to work like how filter searches would work.
just write another ajax
$('#search').on('click',function(){
$.ajax({
type:'GET',
url:'searchAll.php',
success:function(data){
$("#output").html(data);
}
});
});
Then in searchAll.php file write your query php code.
NOTE: Use prepared statements or PDO to prevent SQL injections
In my test work, I want to send data to DB by pressing "Save" button and stay at the same page. But this button after sending data to DB opens /file.php and shown "Success".
I tried to solve the task by JS I found, but it doesn`t work.
$('#sub').click( function() {
$.post( $('myForm').attr('action'), $('#myForm :input').serializeArray(), function(info){ $('result').html(info);} );
clearInput();
});
$('myForm').submit(function() {
return false;
});
function clearInput() {
$('#myForm :input').each( function() {
$(this).val('');
});
}
<html>
<head>
<title>
OneTwoThree
</title>
</head>
<body>
<form id='myForm' action="db.php" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<button id="sub">Send</button>
</form>
<span id="result"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="script/myjs.js" type="text/javascript"></script>
</body>
</html>
Callable PHP file:
<?php
$conn = mysql_connect('localhost','root','');
$db = mysql_select_db('mytestbd');
$name = $_POST['name'];
$age = $_POST['age'];
$q = "INSERT INTO `post`(`number`, `sometext`) VALUES ('$age','$name')";
if(mysql_query($q))
echo "Success";
else
echo "Fail";
?>
Try this block of js which includes some changes and adjustments (noted below):
$(document).ready(function() { // ready wrapper (was missing in your code)
$('#sub').click( function(e) { // added 'e'
e.preventDefault(); // added to stop buttons default behavior
$.post( $('#myForm').attr('action'), // added '#' to id locator
$('#myForm').serialize(), // reduced to just serialize the form data
function(info){
$('#result').html(info); // added '#' to id locator
clearInput(); // moved clear form into success callback
}
);
});
$('#myForm').submit(function() { // added '#' for id locator
return false; // this submit handler is most likely
}); // not needed, but doesnt hurt
function clearInput() {
$('#myForm :input').each( function() {
$(this).val('');
});
}
});
PS Once you get the submission process working, you will want to switch your use of mysql_* functions to either mysqli or PDO (as mysql_ is depreciated in php 5.5x, and removed in php7+).
Then after you switch, look into Prepared Statements to safeguard from sql injection attacks.
Just use a include statement.
if(mysql_query($q))
echo "Success";
include('yourFileWithTheForm.php');
else
echo "Fail";
?>
I'm trying to create a comment system on my website where the user can comment & see it appear on the page without reloading the page, kind of like how you post a comment on facebook and see it appear right away. I'm having trouble with this however as my implementation shows the comment the user inputs, but then erases the previous comments that were already on the page (as any comments section, I'd want the user to comment and simply add on to the previous comments). Also, when the user comments, the page reloads, and displays the comment in the text box, rather than below the text box where the comments are supposed to be displayed. I've attached the code. Index.php runs the ajax script to perform the asynchronous commenting, and uses the form to get the user input which is dealt with in insert.php. It also prints out the comments stored in a database.
index.php
<script>
$(function() {
$('#submitButton').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
//this will add the new comment to the `comment_part` div
$("#comment_part").append(html);
}
});
});
});
</script>
<form id="comment_form" action="insert.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="userInput"/>
<input type="submit" name="submit" value="submit" id = "submitButton"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<div id='comment_part'>
<?php
$link = mysqli_connect('localhost', 'x', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
</div>
insert.php
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
mysqli_close($link);
//here you need to build your new comment html and return it
return "<div class='comment'>...the new comment html...</div>";
}
else{
die('comment is not set or not containing valid value');
}
The insert.php takes in the user input and then inserts it into the database (by first filtering and checking for bad words). Just not sure where I'm going wrong, been stuck on it for a while. Any help would be appreciated.
html() in your function replacing current html with your comment html, thats why u see only new comment. Change your method to append().
$("#comment_part").append(html);
Change this line
$("#comment_part").html(html);
to this
$("#comment_part").html('<div class="comment" >' + $('#userInput').val() + '</div>' + $("#comment_part").html()).promise().done(function(){$('#userInput').val('')});
Have a live search page as shown in livesearch.php below, when typing entries into the input box am not getting any results show under it. The html code and script in search.php are shown beelow.
search.php
<!DOCTYPE HTML>
<html>
<header>
<link href="css/main.css" rel="stylesheet" type="text/css">
<link href="css/search.css" rel="stylesheet" type="text/css">
</header>
<body>
<div id="searchContainer">
<div class="searchMainTitle">Search Schedules</div>
<div class="searchSubTitle">
<p>Enter any information you wish, this will search all schedule fields.</p>
</div>
<form role="form" method="post">
<input type="text" class="form-control" size="100%" placeholder="Enter Search Term(s) Here" id="keyword" />
</form>
<ul id="liveSearch"></ul>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#keyword').on('input', function() {
var searchKeyword = $(this).val();
if (searchKeyword.length >= 3) {
$.post('livesearch.php', { keywords: searchKeyword }, function(data) {
$('ul#liveSearch').empty()
$.each(data, function() {
$('ul#liveSearch').append('<li>' + this.title + '</li>');
});
}, "json");
}
});
});
</script>
</body>
</html>
The livesearch.php that is being referenced by the script is shown below
livesearch.php
<?php
session_start();
require 'dbconnect.php';
echo "Keyword: ".$_POST['keywords']."<br/><br/>";
$liveSearchArray = array();
if (!empty($_POST['keywords'])) {
$keywords = $connection->real_escape_string($_POST['keywords']);
$sql = "SELECT OWNER_SURNAME,OWNER_FIRSTNAMES,OWNER_TITLE FROM testucm_owners WHERE OWNER_SURNAME LIKE '%".$keywords."%'";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
echo "We Have A Result, There Are ".$result->num_rows." Rows";
while ($obj = $result->fetch_object()) {
$liveSearchArray[] = array('id' => $obj->OWNER_SURNAME, 'title' => $obj->OWNER_TITLE);
}
} else {
echo "No Matches";
}
}
echo json_encode($liveSearchArray);
mysqli_close($connection);
?>
If a manually add a value for keywords into the livesearch.php query I get the correct results, however no resutls display if I enter search terms via search.php. I have partially test this by putting an alert after var searchKeyword = $(this).val();, this shows the correct term as typed in however still no results showing.
I suspect the error may be with this line of code:
$('ul#liveSearch').append('<li>' + this.title + '</li>');
Either that or for some reason the $liveSearchArray is not being passed back to the script, however I'm unable to determine where the error lies or how to fix it. Any help would be greatly appreciated
Maybe you should check the php return data.
here:
echo "We Have A Result, There Are ".$result->num_rows." Rows";
see,the return data is not pure json.
I think that may be the key.
When you expect data for "json", you have to keep the return data is only json ,not anything else.Otherwise ,the ajax will get an parse error which is not displayed directly,and your "success" function will not be executed.And it seems like you don't get the data,but actually it's because you get the wrong format data.
It works like this:
I am trying to make a select have some pre-loaded options.
I have a php script that queries for these options, and I want to load them into the select on an html page.
My attempt right now..
HTML
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#usersList").click(function()
{
$.getJSON('states.php', function(data) {
$("#usersList").html(data.value);
});
});
});
</script>
</head>
<body>
<form>
Find Users in: <select id="usersList" name="usersList">
<input type="submit" name="search" value="Search" />
</form>
</body>
</html>
PHP
<html>
<head>
</head>
<body>
<?php
// Connects to your Database
mysql_connect("localhost","helloja2_Austin","mysql");
mysql_select_db("helloja2_Friends") or die(mysql_error());
$data = mysql_query("SELECT DISTINCT State FROM Clients ORDER BY State ASC")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
$ary[] =$info['State'];
}
mysql_close();
?>
</body>
</html>
My PHP works fine, but I am not sure how to get that information into my select.
All help appreciated!
First:
The html select-tag needs to get closed like this:
<select></select>
Next:
Your $ary isnt defined anywhere and it isnt returned anywhere
Use json_decode(); to return json
(and dont use any html head/body in your php file which outputs json)
Your json.php:
<?php
// Connects to your Database
mysql_connect("localhost","helloja2_Austin","mysql");
mysql_select_db("helloja2_Friends") or die(mysql_error());
$data = mysql_query("SELECT DISTINCT State FROM Clients ORDER BY State ASC")
or die(mysql_error());
$ary = Array();
while($info = mysql_fetch_array( $data ))
{
array_push($ary,$info["state"]);
}
mysql_close();
echo json_encode($ary);
?>
Next:
You need to append option tags to your select with jquery like this:
$(document).ready(function() {
$("#usersList").click(function()
{
$.getJSON('states.php', function(data) {
$.each(data,function(key,indata){
$("#usersList").append($("<option>",{
html : indata
}));
})});
});
});
Seems you have jquery library is missing. Please add it after the <head> tag and try:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
In the php, after mysql_close(). Add
print json_encode($ary);