I'm making a search system whereby the user enters data into a text area and when he presses 'enter', the search text is sent to the php search query via javascript so that the page doesn't have to reload.
Javascript:
<script type="text/javascript">
function search(str)
{
if (str=="")
{
document.getElementById("search").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{//IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{//IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("search").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","leaderboard.php?q="+str,true);
xmlhttp.send();
}
</script>
Text input:
<form>
<input type="text" value="search for user" onfocus="if
(this.value==this.defaultValue) this.value='';" onblur="if (this.value!==this.defaultValue) this.value='search for user';" id="search" name="search" style="background-color: white; color: black; border: 1px solid black; font-family: verdana; font-size: 9px; height: 20px; text-align: center;" onchange="search(this.value)">
</form>
PHP:
<?php
$con = mysql_connect('localhost', 'refrigerator', 'XXX');
mysql_select_db('refrigerator');
if($q=$_GET["q"]){
$sql="SELECT * FROM users WHERE username = '".$q."'";
$result = mysql_query($sql);
$User = array(); $Count = array(); $t=0; $i=0;
while($row = mysql_fetch_array($result)){
$User[] = $row['username']; $Count[] = $row['count'];
$t=mysql_num_rows($sql);
}
echo '<tr><td>' .$a. '</td><td>'.$row['username'].'</td><td>'.$row['count'].'</td></tr>';
mysql_close($con);
}
if ($q=!$_GET["q"]){
$User = array(); $Count = array(); $t=0; $i=0;
while($row = mysql_fetch_array($result)){
$User[] = $row['username']; $Count[] = $row['count'];
$t=13;
}
$User[] = $row['username']; $Count[] = $row['count'];
while($i<$t) {
$a = $i + 1;
echo '<tr><td>' .$a. '</td><td>'.$User[$i].'</td><td>'.$Count[$i].'</td></tr>';
$i++;
}
}
?>
The javascript definitely works up to the penultimate line, because the url changes to 'http://localhost/%5bclickphilia%5d/leaderboard.php?search=whatever was searched' but then nothing happens.
I'm very new to this so I might have made a blindingly obvious mistake so don't rule out that possibility :D
Thanks
EDIT:
Here is the full code for the table including the php:
<table border="0" cellspacing="15" padding="0" width="200">
<th><font color="#00FF00">Rank</font></th>
<th><font color="#00FF00">Username</font></th>
<th><font color="#00FF00">Score</font></th>
<?php
$con = mysql_connect('localhost', 'refrigerator', 'XXXX');
mysql_select_db('refrigerator');
if($q=$_GET["q"]){
$sql="SELECT * FROM users WHERE username = '".$q."'";
$result = mysql_query($sql);
$result=mysql_real_escape_string($result);
$User = array(); $Count = array(); $t=0; $i=0;
while($row = mysql_fetch_array($result)){
}
echo '<tr><td>' .$a. '</td><td>'.$row['username'].'</td><td>'.$row['count'].'</td></tr>';
mysql_close($con);
}
if ($q=!$_GET["q"]){
$User = array(); $Count = array(); $t=0; $i=0;
while($row = mysql_fetch_array($result)){
$User[] = $row['username']; $Count[] = $row['count'];
$t=13;
}
$User[] = $row['username']; $Count[] = $row['count'];
while($i<$t) {
$a = $i + 1;
echo '<tr><td>' .$a. '</td><td>'.$User[$i].'</td><td>'.$Count[$i].'</td></tr>';
$i++;
}
}
?>
</table>
I'm sure the inserting the php echo into the table works, because the event for if ($q=!$_GET["q"]) works fine. The data is entered into the table okay.
Well this line here:
document.getElementById("search").innerHTML=xmlhttp.responseText;
doesn't make sense to me. The "search" element is that <input> field. Setting that element's "innerHTML" property may do nothing at all to the page, because "text" input elements are "void" elements and have no content.
Maybe you've got a "search_results" table somewhere? If so, you may have some trouble updating the "middle" of a <table> like that, in IE at least. Try it however and you should be able to mess with that to come up with something.
edit — I'll re-state what I think the problem is: your PHP code seems to be putting together the response to the search in some sort of table form; it's creating <tr> and <td> elements. Those need to go into a <table> somewhere (actually technically a <tbody> but whatever). Exactly how, or even if, you want to refine that, I can't say. What you might try however is to add this to your page:
<div id='search_results'>Results Go Here</div>
and put it just somewhere where it'll show up. Then change your "search()" function so that wherever you're setting "innerHTML", change the "id" you search for to "search_results".
I'm assuming you want to implement a kind of autocomplete.
I think this line:
document.getElementById("search").innerHTML=xmlhttp.responseText;
should be:
document.getElementById("search_result").value=xmlhttp.responseText;
You need to have a search_result table, as Pointy pointed out.
In case you are interested in going the jQuery route, this would be your new code:
function search(str){
if (str != "")
$.get("leaderboard.php", {q : str}, function(r){
$("#search_result").html(r);
});
}
If you want to use the Enter key, I would (again) recommend jQuery because you can accomplish this with a few lines of code, instead of several more with pure JavaScript.
Wow. Hard to know where to begin.
I think you're going to get more help if you give us more of an idea of what you're trying to accomplish. I'm thinking you're trying to build an inline search?
If your URL is changing then the form is getting submitted somehow. Since you're using AJAX that's probably not what you want. Add onSubmit="return false;" to the form element. That may solve your immediate problem. (though I'm not sure that onChange will work right cross browser. See #2)
Look at jQuery for AJAX and for DOM manipulation. It's a lot easier than what you're trying to build it using the native tools.
Your query won't work and it's a security problem. Right now anyone can send SQL commands in your q parameter and depending on permissions probably do whatever they want with your database. Look at mysql_real_escape_string() or better yet look at a database framework that uses place holders such as PDO. As for the query itself you're only going to find people with the exact match. You probably want to use LIKE rather than equals.
Related
I have a page, index.php, with <select> <options> which act as filters. Through Ajax, information is retrieved from an SQL database and echoed into a <div> on the same page. One of the fields that is echoed contains the URL to another page such as a1701.php. Thus far, everything works perfectly.
However, rather than having the URL displayed, I would like the content of the page e.g. a1701.php to be displayed in the same way it would be if I had used <?php include 'a1701.php' ?>.
I have read a lot of posts on SO but haven't found any describing this situation (maybe I am looking for the wrong thing in which case please advise). Following the advice of other partially-related posts, I have tried several things including:
using absolute rather than relative links with $_SERVER['DOCUMENT_ROOT']
include 'a1701.php'; vs echo "<?php include 'a1701.php'; ?>"
using < instead of < etc.
reloading specific <div>s (I haven't actually tried this because I can't figure out what code I would have to put where to make it work.)
I have tried more than one URL and have checked that each one is correct.
index.php
<script>
function filterQuestions() {
var selectCount = document.getElementsByTagName("select").length;
var str = [];
for (var i = 0; i < selectCount; i++) {
if (document.getElementsByTagName("select")[i].value != "") {
str[i] = document.getElementsByTagName("select")[i].name+"="+document.getElementsByTagName("select")[i].value;
}
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("questionList").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","filter.php?"+str.join("&"),true);
xmlhttp.send();
}
</script>
<select name="branch" onchange="filterQuestions()">
<option value="All">All branches</option>
<option value="Number">Number</option>
<option value="Trigonometry">Trigonometry</option>
</select>
<select name="topic" onchange="filterQuestions()">
<option value="All">All topics</option>
<option value="sinrule">Sine Rule</option>
<option value="cosrule">Cosine Rule</option>
</select>
filter.php
<?php
$branch = $_GET["branch"];
$topic = $_GET["topic"];
if($branch != "All") {
$wherefilter[] = "branch = '".$branch."'";
}
if($topic != "All") {
$wherefilter[] = "topic = '".$topic."'";
}
$where = join(" AND ", $wherefilter);
if($where != NULL) {
$where = " WHERE $where";
}
mysqli_select_db($link,"generator");
$sql="SELECT question_name, url FROM questions".$where;
$result = mysqli_query($link,$sql);
echo "<table>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['question_name'] . "</td>";
echo "<td>" . $row['url'] . "</td>";
echo "</tr>";
$pagelink = $row['url'] . '.php'; /* URL is correct */
echo"<br>";
echo $pagelink;
echo"<br>";
echo "<?php include '" . $pagelink . "'; ?>";
echo "<br>";
echo "<?php include '" . $pagelink . "'.php; ?>"; /* doesn't work */
include $pagelink; /* doesn't work */
}
echo "</table>";
mysqli_close($link);
?>
a1701.php
contains the content I want included. I have tried including other content too.
Is there a way to achieve what I am after? Am I heading in the right direction?
I can think of 2 ways to accomplish this.
If the PHP file is always on the same server and is part of the web app, just include it. You would have to do some checking and validation to ensure that the file is there etc.
If the URL points to anywhere on the internet, insert it as an iframe.
Solution 1 (everything is local)
Assuming there is some function called getPhpFileName that returns the name of the PHP file. You need the actual name of the php file, not the url pointing to it. The file is read directly from the file system, not through the web server.
$phpFile = getPhpFileName($row['url']);
if ( file_exists($phpFile) ) {
#include $phpFile;
}
example1.php (this is the file to be included)
<div>Hello Example1</div>
Solution 2 (iframe)
In this case, the iframe is returned and the browser will be responsible for getting the output from the url and inserting it on the page.
<iframe src="<?=$row['url']?>"></iframe>
EDITED: with new code after help from Sgt AJ.
Ok, so I am learning all the time, but since my coder stopped coding for our website, I am now having to learn PHP fully myself.
And I see all the time the coding where my coder made function calls inside other function calls.
So first of all the setup, we have a file for pretty much 95% of all functions in our site. That functions file basically has about 40-50 functions in it.
So I'm asking if someone can explain to me how is this possible to call a function inside another which works in the below instance, but when I try replicate it, it doesn't work? displays no data when I try to echo out the $user_info?
Like for example this function below: So Sgt AJ helped me solve the user avatar issue, so that will be removed from this question!
function showComments($v)
{
$mysqli = db_connect();
$v = mysqli_real_escape_string($mysqli,$v);
$sql = "SELECT * FROM `cl45-tbn_dir`.`comments` WHERE `v` = ? ORDER BY `id` ASC";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s",$v);
$stmt->execute();
$result = $stmt->get_result();
while ($myrow = $result->fetch_assoc()) {
if ($myrow['post_approved']==1){
$user_info = getUserInfo($myrow['poster_id']);
if ($user_info['user_avatar_type']==1) {
$avatar = "https://www.tubenations.com/forum/download/file.php?avatar=".$user_info['user_avatar'];
} else {
$avatar = "https://www.tubenations.com/forum/styles/Flato%20-%20LightBlue%20-%20Main%20Style/theme/images/no_avatar.gif";
}
echo '<div class="comment">
<div class="avatar">
<a href="https://www.tubenations.com/users.php?id='.$myrow['poster_id'].'">
<img src="'.$avatar.'" />
</div>
<div class="name"><a class ="myaccount'.$user_info['group_id'].'" href="https://www.tubenations.com/users.php?id='.$myrow['poster_id'].'">'.$user_info['username'].'</a></div>
<div class="date" title="report this post">'.date("d M Y",$myrow['post_time']).'<form action="" class="flag" method="post"><button type="submit" value="'.$myrow['id'].'" name="vote" id="votebutton" alt="vote"><img src="/images/flag.png" alt="report this post!" /></button></form></div>
<p>'.stripslashesFull(clean($myrow['post_text'])).'</p>
</div>';
}
}
$stmt->close();
$mysqli->close();
}
As you can see, there is a line where it calls another function getUserInfo, $user_info = getUserInfo($myrow['poster_id']); that is another function inside this file, and that basically connects to our forum database and gets data.
But when I try to replicate this method by using this type of call within another, it doesn't work.
So basically what I was trying to play with was trying to make a function for displaying X users data with this below function
function getYouTubeInfo($page)
{
#$id = $_GET['id'];
print_r ($userdata['user_id']);
echo $myrow['user_id'];
echo $userdata['user_id'];
$db_link = mysqli_connect ('localhost', 'HIDDEN', 'HIDDEN', 'HIDDEN');
if ( !$db_link )
{
die('following error occured: '.mysqli_error());
}
$query = "SELECT user_id, yt_channelTitle, channel_id FROM points WHERE channel_id IS NOT NULL AND yt_channelTitle IS NOT NULL ORDER BY channel_id DESC;";
if($result = mysqli_query($db_link, $query)){
echo "";
$i = -1;
$objectsPerPage = 14;
$show_records = FALSE;
while ($row = $result->fetch_assoc())
{
if (!isset($_SESSION['last_slide'])) { $_SESSION['last_slide'] = $row['channel_id']; }
if ($row['channel_id'] == $_SESSION['last_slide']) { $show_records = TRUE; }
if ($show_records)
{
$i = $i+1;
if ($i > $objectsPerPage) { $_SESSION['last_slide'] = $row['channel_id']; echo 'BREAK: ', $row['channel_id']; break; }
$page = abs(floor($i/$objectsPerPage));
$youtube_info = $row;
$userdata = getUserInfo($row['user_id']);
if ($userdata['user_avatar_type']==1) {
$avatar = "/forum/download/file.php?avatar=".$userdata['user_avatar'];
} else {
$avatar = "/images/no_image.png";
}
if (($i/$objectsPerPage)==$page)
{
if ($page !=0) {
echo "</div></div>";
}
echo '<div class="cslide-slide">
<div class="slideTitles">Youtube Users Slide '.$page.'</div>
<div class="sections grouped">';
}
echo '
<div class="cols span_1_of_2">
<div class="memberTitles">'.$youtube_info['yt_channelTitle'].''.$i.';</div>
<div class="memberPicture"><img src="'.$avatar.'" title="Tube Nations Profile Picture" alt="Tube Nations Profile Picture"/></div>
<div class="memberTwitter"><div class="g-ytsubscribe" data-channelid="'.$youtube_info['channel_id'].'" data-layout="full" data-count="default" data-onytevent="onYtEvent"></div></div>
</div> ';
}
}
echo '</div></div>';
}
mysqli_free_result($result);
echo $_SESSION['last_slide'];
session_destroy();
mysqli_close($db_link);
}
So basically in the page in question, youtube.php, I just echo this getYouTubeInfo function.
This function I need to try get the users profile pictures that are in the forum database which is from the getUserInfo($id).
Also on a side note, I also can not work out how to re arrange the $i and $objectsPerPage variables and if statements so I can then use the $page inside the query LIMIT $page; because at the moment the page crashes with no limit, so I have had to put limit to 16 for now.
I use a jQuery slide script for displaying X per slide, so if I can just somehow work out how to make the query further down after the variables and if statements for the page stuff or get any help, I would appreciate it.
EDIT UPDATED REPLY: So now the problem is it now displays X per slide/page, but it now displays a gap after 8 results are displayed when it shows 10, but with a gap, and then on the the next slide button isn't showing up? so Sgt AJ said we need to somehow connect it to the jquery?, so I now will add a tag for jquery. (But can i say a big thanks to Sgt AJ for his help, really appreciate it) :)
Wow, you've got several things going on here.
First, your query right now says LIMIT 0;, which means you should get zero rows returned. Are you getting data back from this query??
Second, to get the page and items per page working right, you could go with something like this:
In your loop, keep your i=i+1 line
Add this if:
if ($i == $objectsPerPage)
{
++$page;
i = 1;
}
This will increment the page counter once the page is full, then reset the item count for the next page.
I just wanted to add more to my question, I think now the answer is with AJAX, so I think I need to somehow make the cslide jquery code recall the getYoutubeInfo($page) function
the jquery code for the cslide is this:
(function($) {
$.fn.cslide = function() {
this.each(function() {
var slidesContainerId = "#"+($(this).attr("id"));
var len = $(slidesContainerId+" .cslide-slide").size(); // get number of slides
var slidesContainerWidth = len*100+"%"; // get width of the slide container
var slideWidth = (100/len)+"%"; // get width of the slides
// set slide container width
$(slidesContainerId+" .cslide-slides-container").css({
width : slidesContainerWidth,
visibility : "visible"
});
// set slide width
$(".cslide-slide").css({
width : slideWidth
});
// add correct classes to first and last slide
$(slidesContainerId+" .cslide-slides-container .cslide-slide").last().addClass("cslide-last");
$(slidesContainerId+" .cslide-slides-container .cslide-slide").first().addClass("cslide-first cslide-active");
// initially disable the previous arrow cuz we start on the first slide
$(slidesContainerId+" .cslide-prev").addClass("cslide-disabled");
// if first slide is last slide, hide the prev-next navigation
if (!$(slidesContainerId+" .cslide-slide.cslide-active.cslide-first").hasClass("cslide-last")) {
$(slidesContainerId+" .cslide-prev-next").css({
display : "block"
});
}
// handle the next clicking functionality
$(slidesContainerId+" .cslide-next").click(function(){
var i = $(slidesContainerId+" .cslide-slide.cslide-active").index();
var n = i+1;
var slideLeft = "-"+n*100+"%";
if (!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-last")) {
$(slidesContainerId+" .cslide-slide.cslide-active").removeClass("cslide-active").next(".cslide-slide").addClass("cslide-active");
$(slidesContainerId+" .cslide-slides-container").animate({
marginLeft : slideLeft
},250);
if ($(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-last")) {
$(slidesContainerId+" .cslide-next").addClass("cslide-disabled");
}
}
if ((!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-first")) && $(".cslide-prev").hasClass("cslide-disabled")) {
$(slidesContainerId+" .cslide-prev").removeClass("cslide-disabled");
}
});
// handle the prev clicking functionality
$(slidesContainerId+" .cslide-prev").click(function(){
var i = $(slidesContainerId+" .cslide-slide.cslide-active").index();
var n = i-1;
var slideRight = "-"+n*100+"%";
if (!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-first")) {
$(slidesContainerId+" .cslide-slide.cslide-active").removeClass("cslide-active").prev(".cslide-slide").addClass("cslide-active");
$(slidesContainerId+" .cslide-slides-container").animate({
marginLeft : slideRight
},250);
if ($(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-first")) {
$(slidesContainerId+" .cslide-prev").addClass("cslide-disabled");
}
}
if ((!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-last")) && $(".cslide-next").hasClass("cslide-disabled")) {
$(slidesContainerId+" .cslide-next").removeClass("cslide-disabled");
}
});
});
// return this for chainability
return this;
}
}(jQuery));
I also tweaked the code that Sgt AJ helped me with again, By adding a session_destroy() just before the closing brace. And also a few other bits, because I noticed that when you refreshed the page over and over, it just loaded the next 14 results, instead of the same first 14 results, so the actual code and logic seems to be working. so it is basically now down to we need to find a way to use AJAX and recall the function from the onclick event of the next/previous buttons.
I'm currently having 2 pages that is "index.php", "retrieve_search_forklift.php" and "search_forklift.php".
I try to passing the "txtSearch" input from index.php using jQuery $.post method to "retrieve_search_forklift.php" for execute the select query and echo the $output.
In "search_forklift.php" will use a function to load the "retrieve_search_forklift.php" when page is load and display the $output in a table.
Index.php
$('#txtSearch').keydown(function(e) {
var code = (e.keyCode || e.which);
if((code == 13)){
txtSearch = $('#txtSearch').val();
$.post('php/retrieve_search_forklift.php',{
txtSearch : txtSearch
},
function(data){
//alert(data);
window.location.replace("search_forklift.php");
})
}
});
Retrieve_search_forklift.php
<?php
require('../database_connection.php');
if($txtSearch = $_POST['txtSearch']){
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT f_brand, f_ftype, f_image, f_code, f_description, f_sale, f_rental FROM tblforkliftdetail WHERE f_brand='Toyota'";
$result = mysqli_query ($mydatabase, $query);
$counter = 0;
while($info = mysqli_fetch_array( $result ))
{
if( $counter % 3 == 0 )
$output .= "<tr>";
$output .= "<td style='background-color:yellow; '><img src=".$info['f_image'] ." width=210px height=210px ></img></p></td>";
$output .= "<td style='background-color:black;'>";
$output .= "</td>";
if( $counter % 3 > 1)
$output .= "</tr>";
$counter++;
}
echo $output;
}
#mysqli_close($mydatabase);
?>
Search_forklift.php
$(document).ready(function(){
loadsearchtblForklift();
});
function loadsearchtblForklift(){
$('#tblsearchForklift').load('php/retrieve_search_forklift.php');
}
<table id="tblsearchForklift">
<tbody>
</tbody>
</table>
I shall simplify this.
You are making a request from A to B; then asking C to show the data that B has generated earlier. This boy, is not possible unless you store the data of B somewhere(DB/file system).
why?
A --> B is a separate request and C --> B is separate. The server does not know that it has to store the data for future request use. You have to change the approach to fulfill this logic.
My Suggestion -
Discard 'Search_forklift.php' and directly show the results in the 'index.php' page directly.
changed index.php file
$('#txtSearch').keydown(function(e) {
var code = (e.keyCode || e.which);
if((code == 13)){
txtSearch = $('#txtSearch').val();
$.post('php/retrieve_search_forklift.php',{
txtSearch : txtSearch
},
function(data){
$('#tblsearchForklift').html(data);
})
}
});
<table id="tblsearchForklift">
<tbody>
</tbody>
</table>
Or, store the result of 'Retrieve_search_forklift.php' in a txt file or into a CLOB column in database with a session key and retrieve it using the same key to display in the 'Search_forklift.php'.
This approach shall ensure that, the person after you who is going to curse everyday of their life maintaining it. May be you yourself may do that after an year or two. :) Don't get me wrong here. but i just want to make you understand the way web and programming life works.
EDIT: reading again, i got another approach (bad) idea. You can do this in one more way.
Once your ajax call in index.php is returned, POST the results to the 'Search_forklift.php' page and in there just say
<table id="tblsearchForklift"><?php echo $_POST[results]; ?></table>
So I am having an issue with re-populating data into a dropdown box after the form is submitted with Ajax. This is to remove an object from the dropdown, the initial script works fine, its just getting the new data and populating. My PHP script builds a JSON array to output to Ajax for parsing but when I check the PHP script the only thing that returns is }.
PHP Code:
$jasonData = "{";
include_once("../php_includes/db_connect.php");
$sql = "SELECT * FROM orginfo";
$user_query = mysqli_query($db_connect, $sql);
$count = mysqli_num_rows($user_query);
for($i = 0; $i < $count; $i++){
$rows = mysqli_fetch_array($user_query);
$id = $rows["id"];
$orgname = $rows["orgname"];
$orgphone = $rows["orgphone"];
$jasonData .= '"option'.$id.'":{ "id":"'.$id.'","orgname":"'.$orgname.'","orgphone":"'.$orgphone.'" },';
}
$jsonData = chop($jsonData, ",");
$jsonData .= "}";
echo $jsonData;
AJAX Code:
function getorgs(){
var getorgs = ajaxObj("POST", "engine.php");
getorgs.onreadystatechange = function() {
if(ajaxReturn(getorgs) == true) {
var remresponse = JSON.parse(getorgs.responseText);
alert (remresponse);
}
}
getorgs.send("getorgs");
}
I have been building this off of several tutorials kind of piece meal along with things I have already learned and am using. The current lack of sanitation is because of testing, want to make sure things are working and then add it in to narrow down any issues.
Any help would be appreciated.
Thanks in advance for taking a look.
Try the following:
<?php
header('Content-Type: application/json;charset=UTF-8');// this line must reside on top (before any output)
$jasonData = array();
$user_query = mysqli_query($db_connect, 'SELECT*FROM`orginfo`');
while ($row = mysqli_fetch_assoc($user_query)) {
array_push($jasonData, $row);
}
echo json_encode($jasonData, JSON_FORCE_OBJECT);
mysqli_close($db_connect);
Let me know if the above doesn't work out!
Let me start off by saying while I'm pretty good with PHP and HTML, I don't know much about javascript/jquery. I also apologize if this has been answered before, but I haven't had much luck finding anything in the search.
I'm working on a project where we have a form of undetermined size that I want to build some autocomplete functionality into. The form fields and necessary div's are being named using a counter as you can see in the code below.
$set_b = 'upl_band'.$count;
$sugbox = $set_b."sug";
$autobox = $set_b."auto";
echo "<div><input type=text name='$set_b' size=25 id='$set_b' onkeyup='bandlookup(this.value,'$set_b');' onblur='bandfill();'></div>";
echo "<div class='suggestionsBox' id='$sugbox' style='display: none;'><img src='upArrow.png' style='position: relative; top: -12px; left: 30px;' alt='upArrow' /><div class='suggestionList' id='$autobox'> </div></div>";
I'm trying to pass the main value - $set_b into my javascript onkeyup. However, somewhere along the line I'm losing my values. If I setup my form with concrete id's this code works fine, but when I make my id's variable I'm getting lost. My javascript is below. The post call to band.php is my lookup script.
function bandlookup(bandString, boxName) {
if(bandString.length == 0) {
// Hide the suggestion box.
var s = boxName+"sug";
$("#"+s).hide();
} else {
var su = boxName+"sug";
var suauto = boxName+"auto";
$.post("band.php", {queryString: ""+bandString+"", inputName: ""+boxName+""}, function(data){
if(data.length >0) {
$("#"+su).show();
$("#"+suauto).html(data);
}
});
}
} // lookup
function bandfill(thisValue, boxName) {
var s = boxName+"sug";
$("#"+boxName).val(thisValue);
setTimeout("$('#'+s).hide();", 200);
}
and band.php
$db = new mysqli('localhost', 'yourUsername', 'yourPassword', 'yourDatabase');
if(!$db) {
// Show error if we cannot connect.
echo 'ERROR: Could not connect to the database.';
} else {
// Is there a posted query string?
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
$box = $_POST['inputName'];
// Is the string length greater than 0?
if(strlen($queryString) >0) {
$query = $db->query("SELECT band_name,band_id FROM upl_band WHERE band_name LIKE '$queryString%' LIMIT 10");
if($query) {
// While there are results loop through them - fetching an Object (i like PHP5 btw!).
while ($result = $query ->fetch_object()) {
// Format the results, im using <li> for the list, you can change it.
// The onClick function fills the textbox with the result.
echo '<li onClick="bandfill(\''.$result->band_name.'\',\''.$box.'\');">'.$result->band_name.'</li>';
}
} else {
echo 'ERROR: There was a problem with the query.';
}
} else {
// Dont do anything.
} // There is a queryString.
} else {
echo 'There should be no direct access to this script!';
}
}
My problem could be with the post call in the javascript, but I'm more leaning towards me improperly dealing with the variable variable names as an id tag.
Your string is broken, try this:
echo "<div><input type=text name='$set_b' size=25 id='$set_b' onkeyup=\"bandlookup(this.value,'$set_b');\" onblur='bandfill();'></div>";