I have a PHP and jQuery script that creates search result suggestions from a text box. However, when you type something in the text box, delete it and try making a different query, no suggestions are displayed. Why could this be?
Here is a copy of my webpage code:
<script type="text/JavaScript">
function lookup(inputString){
if (inputString.length==0){
$('#suggestions').hide();
} else{
$.post("suggestions.php",{
queryString: "" + inputString + ""},
function(data){
$('#suggestions').html(data);
});
}
}
</script>
<form>
<input type="text" size="30" onkeyup="lookup(this.value);">
<div id="suggestions"></div>
</form>
Here is a copy of my PHP code:
<p id="searchresults"><?php
$db=new mysqli('localhost','username','password','database');
if(isset($_POST['queryString'])){
$queryString=$db->real_escape_string($_POST['queryString']);
if(strlen($queryString)>0){
$query = $db->query("SELECT * FROM search s WHERE name LIKE '%" . $queryString . "%'");
if($query){
while ($result = $query ->fetch_object()){
echo '<a href="'.$result->name.'">';
$name=$result->name;
echo ''.$name.'';
}
}
}
}
?></p>
Thanks in advance, Callum
You hide but don't show again.
change your callback function to:
function(data){
$('#suggestions').html(data).show();
}
or a fadeIn() for added cuteness ;)
Add $('#suggestions').show() inside of your else statement.
Related
I need to make drop down list as a link to different pages. How do I do that using PHP, MySQL and HTML.
<?php
mysql_connect('localhost','root','');
mysql_select_db('test');
$sql="select first_name from users";
$result=mysql_query($sql);
echo "<select First_name=''>";
echo "<a href='index.html'>";
while($row=mysql_fetch_array($result)){
echo ":<option value='".$row['first_name']."'>".$row['first_name']."</option>";
}
echo"</a>";
echo"</select>";
?>
You can't use links on the option tag, in order to do that, you need to use javascript.
You can try to do something like this:
echo "<select name=\"First_name\" onchange=\"document.location='?'+this.value\">";
PHP is a server-side script and does not manipulate a page after a user has adjusted it. Like real time. Only javascript and others do that. PHP creates a page with what you want to see but if you need to change something bases on a dropdown use java. Here is a function that can do that. It unhides a div tag that can have your info you need.
<script type="text/javascript">
window.onload = function() {
var eSelect = document.getElementById('dropdown');
var divtag1 = document.getElementById('divtag1');
var divtag2 = document.getElementById('divtag2');
eSelect.onchange = function() {
if(eSelect.selectedIndex === 1) {
divtag1.style.display = 'block';
}
if(eSelect.selectedIndex === 2) {
divtag2.style.display = 'block';
}//or if you want it to open a url
if(eSelect.selectedIndex === 3) {
window.open("https://yourwebsite.com", "_NEW");
}
}
}
</script>
echo "<div id=\"divtag1\" style=\"display:none;\">/*your code*/
</div>";
echo "<div id=\"divtag2\" style=\"display:none;\">/*your code*/
</div>";
Okay people, what I am trying actually trying to achieve is, to create a chat box something similar to fb without refreshing the page. I have two tables in my database(phpmyadmin) where the first table, i store 2 users chat id(unique) and later save their message in another table so that i will be able to retrieve their chat history just by their unique id.
So I was able to send their Id(unique) by using get method to send the unique ID to the second div and then run through the database using php and display their conversation.
So how can i do it in ajax so that the page does not refreshes guys ? Some guide on that please ? I have been trying to google for it but i cant find a way simply because i do not know ajax much.
The purpose of me wanting it to not refresh the page is because i am using Jquery to hide and show the chat conversation. When the page refreshes, the conversation disappears. Im sorry if my explanation is not on point, hopefully somebody understands my problem and guide me in this :D
So here are my codes ...
This code is in my first div. It basically displays all the users who I have chatted with before...
<div>
<ul style="list-style-type: none;">
<?php
include 'connectDB.php';
//retrieve all the message history of yours from the PrivateMessage table
$query = "SELECT * FROM `messagecheck` WHERE `sender_a` = '$userId'
OR `sender_b` = '$userId';";
$result = mysqli_query($dbconnect,$query);
if(mysqli_num_rows($result) > 0)
{
//if exist, display the history
while($row = mysqli_fetch_assoc($result))
{
?>
<a href="Item_v1.php?msgId=<?php echo $row['exist']?>">
<li style="color:black; width:100%; padding-top:5px" >
<input id="IDValue" name="IDValue" value="<?php echo $row['exist']?>" >
<?php
//if the sender_a id is not my id, display the name
//if sender_a is my id, then display sender_b
//Because we dont want to see our name in the chat History
if($row['sender_a'] != $userId)
{
$senderName = $row['sender_a'];
include 'connectDB.php';
$nameSearch = "SELECT `fName`, `lName` FROM `register` WHERE `id`='$senderName';";
$Searchresult = mysqli_query($dbconnect,$nameSearch);
$Searchrow = mysqli_fetch_assoc($Searchresult);
echo $Searchrow['fName'] ." ". $Searchrow['lName'];
}
else
{
$senderName = $row['sender_b'];
include 'connectDB.php';
$nameSearch = "SELECT `fName`, `lName` FROM `register` WHERE `id`='$senderName';";
$Searchresult = mysqli_query($dbconnect,$nameSearch);
$Searchrow = mysqli_fetch_assoc($Searchresult);
echo $Searchrow['fName'] ." ". $Searchrow['lName'];
}
?>
</li>
</a>
<?php
}
}
?>
</ul>
</div>
So basically when i click the names which will be in the < li > tag, it should be posting the messages in another div(Which is the div below)...
<!-- //Message Content! -->
<div style="width:100%;max-height: 300;border: 2px solid #1F1F1F;overflow: auto;">
<?php
if($_GET)
{
$msgId = $_GET['msgId'];
}
if(!empty($msgId))
{
include 'connectDB.php';
$collectMsgQuery = "SELECT * FROM `privatemessage` WHERE `existing_id` = $msgId";
$MsgResult = mysqli_query($dbconnect, $collectMsgQuery);
if(mysqli_num_rows($MsgResult) > 0)
{
while($Msgrow = mysqli_fetch_assoc($MsgResult))
{
if($userId == $Msgrow['from_who']){
?>
<h4 class="ifMe"><span class="ifMeDesign"><?php echo $Msgrow['message'] ?></span></h4>
<?php
}else if ($userId == $Msgrow['to_who']) {
?>
<h4 class="notMe"><span class="notMeDesign"><?php echo $Msgrow['message'] ?></span></h4>
<?php
}
}
}
}
?>
</div>
P.S : I'm not really sure how to work with ajax so that is why i am posting it here. Any help would be great! Thanks in advance ! :D
Working with ajax, at the beginning, can be very frustrating. You should start with more simple task, simply to understand what you're working with.
Start with something like this, a simple request that send two numbers to the server and then alert the sum
ajax_request.php
<?php
$num1 = isset( $_GET[ "num1" ] ) ? $_GET[ "num1" ]: 0;
$num2 = isset( $_GET[ "num2" ] ) ? $_GET[ "num2" ]: 0;
echo $num1 + $num2;
index.html
<html>
<head>
<script src="jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function () {
$( "#calculate" ).click(function(e) {
e.preventDefault();
$.ajax({
url: 'ajax_request.php',
data: $( "#form" ).serialize(),
success: function( data ) {
alert( data );
},
error: function() {
alert( "Something went wrong" );
}
});
});
});
</script>
</head>
<body>
<form id="form">
Num1: <input type="text" name="num1" /><br />
Num2: <input type="text" name="num2" /><br />
<input type="submit" id="calculate" />
</form>
</body>
</html>
Open index.html (download the jQuery library), fill the two numbers and click the button.
You can test the "Something went wrong", simply put a wrong url (ajax_requestx.php instead of ajax_request.php).
From here, you can study "ajax" and "jQuery" to understand better how this work.
The concept is this: you stop the form to be sent (e.preventDefault()) and instead send the form in "asyncronous" way, making javascript send the request to the server without changing the page; in the "success" function you can analyze the string sent back from the server and do something with it. All done by javascript
I am new with AJAX and JQuery. I am trying to use it to call two PHP scripts. I found some examples online but just to call functions. I am just trying to call the scripts so it will load everything on my main PHP file that will then be display on the screen the results withouth refreshing the page.
Here is the fiddle example, it works if I put all my PHP scripts in one file : http://jsfiddle.net/vw4w3ay5/
thanks in advance, your help is very much appreciated!
main_php file (where I want to call my other PHP scripts):
<div id="map_size" align="center">
<script type="text/javascript">
/*I WANT TO CALL THE TWO SCRIPTS BEFORE EXECUTE THE FUNCTION BELOW*/
$(".desk_box").click( function() {
$(".station_info").hide(); // to hide all the others.
$("#station_info"+ $(this).attr('data') ).show();
});
</script>
display_desk.php (Script I want to call):
<?php
include 'db_conn.php';
//query to get X,Y coordinates from DB for the DESKS
$desk_coord_sql = "SELECT coordinate_id, x_coord, y_coord FROM coordinates";
$desk_coord_result = mysqli_query($conn,$desk_coord_sql);
//see if query is good
if($desk_coord_result === false) {
die(mysqli_error());
}
//didsplay Desk stations in the map
while($row = mysqli_fetch_assoc($desk_coord_result)){
//naming X,Y values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
//draw a box with a DIV at its X,Y coord
echo "<div class='desk_box' data='".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>id:".$id."</div>";
} //end while loop for desk_coord_result
mysqli_close($conn); // <-- DO I NEED TO INCLUDE IT HERE OR IN MY db_conn.php SINCE IM INCLUDING IT AT THE TOP?
?>
display_stationinfo.php(second script I want to call):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
while($row = mysqli_fetch_assoc($station_result)){
//naming values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
//display DIV with the content inside
echo "<div class='station_info' id='station_info".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>Hello the id is:".$id."</br>Section:".$sec_name."</br></div>";
}//end while loop for station_result
mysqli_close($conn); // <-- DO I NEED TO INCLUDE IT HERE OR IN MY db_conn.php SINCE IM INCLUDING IT AT THE TOP?
?>
What about? :
<div id="map_size" align="center">
<?php
echo "<script>";
include "display_desk.php";
include "display_stationinfo.php";
echo "</script>";
?>
<script type="text/javascript">
/*I WANT TO CALL THE TWO SCRIPTS BEFORE EXECUTE THE FUNCTION BELOW*/
$(".desk_box").click( function() {
$(".station_info").hide(); // to hide all the others.
$("#station_info"+ $(this).attr('data') ).show();
});
</script>
To be sure add $(document).ready(function(){
});
/EDIT/
Hum you want to use Ajax . did you try with :
$.post("yourURL.php",function(html){
/*here what you want to do*/
/*return of your script in html*/
});
I am having a bit of problems trying to show an information in a div tag using jQuery inside the PHP while loop.
My code looks like this:
$i=1;
while($pack = mysql_fetch_array($packs))
{
$pricepack = $price * $pack['refcount'];
$pricepack = number_format($pricepack,2);
if($users > $pack['refcount'] ) {
$contents .= "
<a class='refbutton' style='text-decoration:none;' onclick=\"document.rent.refs.value='{$pack['refcount']}';document.rent.submit(); return false;\" >{$pack['refcount']}</a>
<div id='refinfo' style='display:none;'>
<span style='font-size:18pt;font-weight:bold;' id='refprice'></span><br />
<span style='color:#D01F1E;'>You don't have enough funds for this package.</span>
</div>
<script type='text/javascript'>
$(document).ready(function() {
$('.refbutton').hover(
function() {
$('#refinfo').show();
$('#refprice').text(\"$\"+\"$pricepack\");
},
function() {
$('#refinfo').hide()
}
);
});
</script>
";
$i++;
}
}
The problem is that the code is generating a div next to each anchor element. This will cause this when the mouse hovers:
What I am trying to obtain is this on every button hover:
As you can see in the second picture, there isn't any design errors or mix-ups. How can I obtain this?
Thank you.
You need to start by cleaning up your code. You only need one refinfo div, and only one javascript block. The only thing in your loop should be the refbutton, and that tag should contain all the values needed for the javscript hover and click events to do their business. Look into HTML5 custom data attributes http://html5doctor.com/html5-custom-data-attributes/
Something more like this should work and provide a sounder basis on which to debug layout issues if any remain.
<?php
$i=1;
while($pack = mysql_fetch_array($packs)) {
$pricepack = $price * $pack['refcount'];
$pricepack = number_format($pricepack,2);
if($users > $pack['refcount'] ) {
$contents .= "
<a class=\"refbutton\" data-pricepack=\"{$pricepack}\" style=\"text-decoration:none;\" >{$pack['refcount']}</a>";
$i++;
}
}
?>
<div id="refinfo" style="display:none;">
<span style="font-size:18pt;font-weight:bold;" id="refprice"></span><br />
<span style="color:#D01F1E;">You don't have enough funds for this package.</span>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('.refbutton')
.bind('mouseover',function(event) {
$('#refinfo').show();
$('#refprice').text($(this).data("pricepack"));
})
.bind('click',function(event) {
document.rent.refs.value=$(this).text();
})
.bind('mouseout', function(event){
$('#refinfo').hide();
})
;
});
</script>
I have a function that prints out articles from my database and three links Edit , Add , Show/hide.
In the show/hide link i want to be able to hide/show that particular article.
How can i do that?
EDIT: I need to be able to hide/show articles in my backend page and it needs to stay hidden in the frontend page
function displaynews()
{
$data = mysql_query("SELECT * FROM news") // query
or die(mysql_error());
while ($info = mysql_fetch_array($data))
{
$id = $info['id'];
echo "<br>
<a href=Edit.php?id=$id>Edit</a></a>
<a href='addnews.php'> Add </a>
<a href='#'>Show/Hide</a><br><strong>" .
$info['date'] .
"</strong><br>" .
$info['news_content'] .
"<hr><br>"; // Print Articles and Date
}
}
You could use some Javascript and set the style attribute to display:none to hide, then display:block to show it again. Or use jQuery.
Use jquery.
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
</head>
show/hide
<div id="whatever">
Content
</div>
<script>
//Try these too
$('#whatever').hide();
$('#whatever').show();
$('#whatever').toggle();
</script>
Use following code:
PHP Code:
function displaynews()
{
$data = mysql_query("SELECT * FROM news") // query
or die(mysql_error());
while ($info = mysql_fetch_array($data))
{
$id = $info['id'];
echo "<div class="news"><br><a href=Edit.php?id=$id>Edit</a></a><a href='addnews.php'> Add </a><a href=hide.php>Show/Hide</a><br><strong>". $info['date']."</strong><br>". $info['news_content'] . "<hr><br></div>"; // Print Articles and Date
}
}
Javascript/jQuery Code (Don't forget to add jQuery in your page)
<script type="text/javascript">
$(document).ready(function(){
$(".news").click(function(){
$(this).toggle();
});
});
</script>