I have a problem with Json pars, I have seen tons of users had this problem I saw them all but I couldn't understand where my error is in my code! Sorry if this is duplicate!
First file index.html:
This is in the head section of the file:
<script type="text/javascript">
function ajax_json_data(){
var databox = document.getElementById("databox");
var field1 = document.getElementById("field1").value;
var results = document.getElementById("results");
var x = new XMLHttpRequest();
x.open( "POST", "test.php", true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
x.onreadystatechange = function() {
if(x.readyState == 4 && x.status == 200){
databox.innerHTML = "";
var d = JSON.parse(x.responseText);
for(var o in d){
if(d[o].title){
results.innerHTML = "";
databox.innerHTML += '<p>'+d[o].title+'<br />';
databox.innerHTML += ''+d[o].cd+'</p>';
}
}
}
}
x.send("limit=4&field1="+field1);
results.innerHTML = "requesting...";
}
</script>
This is in the body section of the file:
<form id="form" method="post" onSubmit="return false;">
<textarea id="field1" name="field1" placeholder="Input some text here..."></textarea>
<input type="submit" id="submit" name="submit" value="Submit" onClick="ajax_json_data();">
</form>
<div id="results"></div>
<div id="databox"></div>
<script type="text/javascript">ajax_json_data();</script>
The second file test.php:
<?php header("Content-Type: application/json");
if (isset($_POST['field1']) && $_POST['field1'] != "") {
$field1 = $_POST['field1'];
require_once("db_conx.php");
$sqlString = "INSERT INTO test_ajax (title) VALUES ('$field1')";
$query = mysqli_query($db_conx, $sqlString) or die (mysqli_error());
}
if(isset($_POST['limit'])){
$limit = preg_replace('#[^0-9]#', '', $_POST['limit']);
require_once("db_conx.php");
$i = 0;
$jsonData = '{';
$sqlString = "SELECT * FROM test_ajax ORDER BY creationdate DESC LIMIT $limit";
$query = mysqli_query($db_conx, $sqlString);
while ($row = mysqli_fetch_array($query)) {
$i++;
$id = $row["id"];
$title = $row["title"];
$cd = $row["creationdate"];
$cd = strftime("%B %d, %Y", strtotime($cd));
$jsonData .= '"article'.$i.'":{"id":"'.$id.'","title":"'.$title.'","cd":"'.$cd.'"},';
}
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
}
?>
And mysqli table has an id, a title and a timestamp, I have tested the data in JSONLint and it's completely valid...Maybe some details that I give it's not necessary but nevermind... So it returns this error: SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data ... var d = JSON.parse(x.responseText); Any help would be appreciated! Thanks in advance!
Found the problem..the problem was that my host provider send me some code together with my json response so the response from json was invalid..! Thank you for your feedback!
Related
I am attempting to build a basic higher or lower game in javascript and insert the results into a table in mysql. After that I am attempting to display the top ten results. Currently I have a rough outline of the game that functions with but am stuck on how to pass the three java script variables to php to insert. I looked up a method of doing this in Ajax an attempted to implement but have not had success yet.
<!DOCTYPE html>
<html>
<?php
session_start();
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
print $username;
}
?>
<body onload="random()">
<p>Welcome to the higher or lower game</p>
<p>Please enter a guess betweeen 1 and 100</p>
<form id="userGuess">
<input id="ui" type="text" name="UserInput" value="">
</form>
<br>
<br><br>
higher or lower
<br><br>
<p id="demo"></p>
<p id="status"></p>
<p id="rand"></p>
<p id="nan"></p>
<button onclick="comparison()">Submit</button>
<button onclick="reset()">Reset</button>
<script>
var numGuess = 0;
var userIn;
var randNum = 0;
var status;
var method;
//var nan;
function comparison(){
//isnan and parseint
userIn = document.getElementById("ui").value;
//suserIn = parseint(userIn);
//if(isnan(parseint(userIn)){
// nan = "true"
//}
//else{
// nan = "false"
//}
if(userIn == randNum){
//User wins
status = "Correct"
method = "submitScore";
getData({method:"submitScore", score:numGuess, username:username});
window.location = 'http://icarus.cs.weber.edu/~ka14804/3750/A1/results.php'
}
else if(userIn < randNum){
//output higher
status = "Higher"
numGuess++;
}
else if(userIn > randNum){
//output lower
status = "Lower"
numGuess++;
}
document.getElementById("status").innerHTML = status;
document.getElementById("demo").innerHTML = userIn;
document.getElementById("rand").innerHTML = randNum;
document.getElementById("nan").innerHTML = nan;
document.getElementById("nan").innerHTML = numGuess
;
//compare random number to user input. Output higher, lower or match.
}
function reset(){
random();
numGuess = 0;
}
function random() {
randNum = Math.floor((Math.random() * 100) + 1);
}
function getData(obj,callback){
$.ajax({
url: 'resulta.php',
type: 'GET',
dataType: "json",
data: obj
}).done(function(data) {
if(callback != null)
callback(data);
});
}
</script>
</body>
</html>
results.php
<?php
class Results {
public $data;
public $success = true;
public $errorMessage;
}
$func = $_GET["method"];
$obj = new Results();
switch ($func) {
case "getHighScores":
$conn = new mysqli('localhost','','','');
if (!$conn->connect_errno) {
$high = "SELECT * FROM HighScores ORDER BY Score LIMIT 10";
$scores = $conn->query($high);
$arr = array();
while ($row = $scores->fetch_assoc()){
$arr[] = $row;
}
$obj->data = $arr;
echo json_encode($obj);
}
break;
case "submitScore":
$userName = $_GET["username"];
$score = $_GET["score"];
$conn = new mysqli('localhost','','','');
if (!$conn->connect_errno) {
$query = "INSERT INTO HIGHSCORES VALUES('" . $userName . "', '" . $score . "')";
$conn->query($query);
}
break;
default:
echo "Invalid method";
break;
}
?>
Trying to build a commenting system. Were comments are posted with AJAX. With comment count with Pagination. I have success achieving both, but putting them together is another story. I have tried doing 2 ajax calls. One for getting records from the database and showing pagination. The other call for recording records to the database.
// this is the first ajax call to to get the results and show pagination buttons
<script>
function request_page(pn){
var two = <?php echo $img_id; ?>;
var showmax = <?php echo SHOWMAX; ?>; // results per page
var totalpages = <?php echo $totalpages; ?>;
//controls for pigmintation
var pagination_controls = document.getElementById("pagination_controls");
var results_box = document.getElementsByClassName(two)[0];
params = 'showmax=' + showmax + '&totalpages=' + totalpages + '&pn=' + pn + '&img_id=' + two;
request = new ajaxRequest()
request.open("POST", "response5.php", true)
request.setRequestHeader("Content-type",
"application/x-www-form-urlencoded")
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
results_box.innerHTML =
this.responseText
}
else alert("Ajax error: No data received")
}
else alert( "Ajax error: " + this.statusText)
}
}
request.send(params)
function ajaxRequest()
{
try
{
var request = new XMLHttpRequest()
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
return request
}
var paginationCtrls = "";
// Only if there is more than 1 page worth of results give the user pagination controls
if(totalpages != 1)
{
if( pn > 1){
paginationCtrls += '<button onclick="request_page('+(pn-1)+')"><</button>';
}
paginationCtrls += ' <b>Page '+pn+' of '+totalpages+'</b> ';
if (pn != totalpages) {
paginationCtrls += '<button onclick="request_page('+(pn+1)+')">></button>';
}
}
pagination_controls.innerHTML = paginationCtrls;
}
</script>
<script> request_page(<?php echo $totalpages; ?>); </script>
/// the response
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$curPage = (int) sanitizeString($_POST['pn']);
$showmax = (int) sanitizeString($_POST['showmax']);
$totalpages = (int) sanitizeString($_POST['totalpages']);
$z = (int) sanitizeString($_POST['img_id']);
if ($curPage < 1) {
$curPage = 1;
} else if ($curPage > $totalpages) {
$curPage = $totalpages;
}
$offset = ($curPage-1) * $showmax;
// var_dump($showmax);
$one = $showmax;
$getcomments = "SELECT I.comment, I.created, U.user_pic_path, U.user_id, U.username, G.file_name
FROM users U
INNER JOIN img_comment I
ON I.img_id = ?
LEFT OUTER JOIN gallery G
ON G.img_id = U.user_pic_path
WHERE I.user_id = U.user_id
ORDER BY UNIX_TIMESTAMP(created) ASC
LIMIT ?, ?";
$stmt = $pdo->prepare($getcomments);
$stmt->bindParam(1, $z, PDO::PARAM_INT);
$stmt->bindParam(2, $offset, PDO::PARAM_INT);
$stmt->bindParam(3, $one, PDO::PARAM_INT);
$stmt->execute();
//fetch resuls
while ($row = $stmt->fetch()){
echo "<div class='chat-entry users person triggerProfile'>";
$bulls = get_web_path($row['user_pic_path']);
if(isset($row['file_name']))
{
$done32 = "http://localhost/new11/users/{$row['username']}/thumbs/{$row['file_name']}";
}else
{
$done32 = 'http://localhostnew11/users/noimage.jpg';
}
$bulls = get_web_path($row['file_name']);
echo "<a class='head users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>
<img class='imgcom' src='$done32'>
</a>
<div class='body'>
<div class='basic'>
<span class='username'>
<a class='users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>{$row['username']} </a>
</span>
</div>
<div class='message'>{$row['comment']}
</div>
</div>
</div>";
}
}
////ajax call # 2 is triggered when ever the comment form is submitted
<div>
<form method='post' id="form<?php echo $img_id; ?>" name="<?php echo $img_id; ?>">
<textarea class='lake' name='one' placeholder="Comment" id='<?php echo $img_id; ?>'></textarea>
<input id="submit" onclick="showUser(document.getElementById(<?php echo $img_id; ?>).value, <?php echo $img_id; ?>);" type="button" value="Submit">
</form>
</div>
//// the ajax call function
function showUser(a, b){
name = a;
two = b;
yes = "form" + two;
params = 'name1=' + name + '&two1=' + two;
request = new ajaxRequest()
request.open("POST", "response10.php", true)
request.setRequestHeader("Content-type",
"application/x-www-form-urlencoded")
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
document.getElementsByClassName(two)[0].innerHTML =
this.responseText
}
else alert("Ajax error: No data received")
}
else alert( "Ajax error: " + this.statusText)
}
}
request.send(params)
function ajaxRequest()
{
try
{
var request = new XMLHttpRequest()
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
return request
}
document.getElementById(yes).reset();
return false;
}
The response
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
define('SHOWMAX', 5);
$q = sanitizeString($_POST['name1']);
$z = sanitizeString($_POST['two1']);
$b = sanitizeString($_SESSION['user_id']);
$sql = 'INSERT INTO img_comment (img_id, comment, user_id)
VALUES(:img_id, :comment, :user_id)';
// prepare the statement
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':img_id', $z, PDO::PARAM_INT);
$stmt->bindParam(':comment', $q, PDO::PARAM_STR);
$stmt->bindParam(':user_id', $b, PDO::PARAM_INT);
$stmt->execute();
$OK = $stmt->rowCount();
$getCount = 'SELECT COUNT(*) FROM img_comment WHERE img_id ='. $z;
// submit query and store result as $totalPix
$total = $pdo->query($getCount);
$totalCount = $total->fetchColumn();
// var_dump($totalCount);
$total = (int)$totalCount;
$totalpages = (int) ceil($total/ SHOWMAX);
$offset = ($totalpages-1) * SHOWMAX;
$one = SHOWMAX;
if($totalCount > 0){
$getcomments = "SELECT I.comment, I.created, U.user_pic_path, U.user_id, U.username, G.file_name
FROM users U
INNER JOIN img_comment I
ON I.img_id = ?
LEFT OUTER JOIN gallery G
ON G.img_id = U.user_pic_path
WHERE I.user_id = U.user_id
ORDER BY UNIX_TIMESTAMP(created) ASC
LIMIT ?, ?";
$stmt = $pdo->prepare($getcomments);
$stmt->bindParam(1, $z, PDO::PARAM_INT);
$stmt->bindParam(2, $offset, PDO::PARAM_INT);
$stmt->bindParam(3, $one, PDO::PARAM_INT);
$stmt->execute();
while ($row = $stmt->fetch()){
echo "<div class='chat-entry users person triggerProfile'>";
$bulls = get_web_path($row['user_pic_path']);
if(isset($row['file_name']))
{
$done32 = "http://localhost/new11/users/{$row['username']}/thumbs/{$row['file_name']}";
}else
{
$done32 = 'http://localhostnew11/users/noimage.jpg';
}
$bulls = get_web_path($row['file_name']);
echo "<a class='head users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>
<img class='imgcom' src='$done32'>
</a>
<div class='body'>
<div class='basic'>
<span class='username'>
<a class='users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>{$row['username']} </a>
</span>
</div>
<div class='message'>{$row['comment']}
</div>
</div>
</div>";
}
}
}
i have a form like this:
<?php
include '../db/baza.php';
?>
<?php include 'vrh.php' ?>
<div id="stranica">
<div id="stranicaOkvir">
<form action="dodaj_sliku_obrada.php" method="POST" enctype="multipart/form-data" id="upload" class="upload">
<fieldset>
<legend>Dodaj sliku</legend>
<?php $upit = "SELECT kategorija_ID, kategorija_naziv FROM kategorije ORDER BY kategorija_ID ASC";
$ispis = mysql_query($upit) or die(mysql_error());
$blok_ispis = mysql_fetch_assoc($ispis);
$ukupno = mysql_num_rows($ispis); ?>
<p><strong>Obavezno odaberite kategoriju kojoj slika pripada</strong></p>
<p> <select name="kategorija" id="kategorija">
<?php do { ?>
<option value="<?php echo $blok_ispis['kategorija_ID']; ?>"> <?php echo $blok_ispis['kategorija_naziv']; ?></option>
<?php } while ($blok_ispis = mysql_fetch_assoc($ispis)); ?>
<?php mysql_free_result($ispis);?>
</select>
</p>
<input type="file" id="file" name="file[]" required multiple>
<input type="submit" id="submit" name="submit" value="Dodaj sliku">
<div class="progresbar">
<span class="progresbar-puni" id="pb"><span class="progresbar-puni-tekst" id="pt"></span></span>
</div>
<div id="uploads" class="uploads">
Uploaded file links will apper here.
<script src="js/dodaj_Sliku.js"></script>
<script>
document.getElementById('submit').addEventListener('click',function(e){
e.preventDefault();
var f = document.getElementById('file'),
pb = document.getElementById('pb'),
pt = document.getElementById('pt');
app.uploader({
files: f,
progressBar: pb,
progressText: pt,
processor: 'dodaj_sliku_obrada.php',
finished: function(data){
var uploads = document.getElementById('uploads'),
uspjesno_Dodano = document.createElement('div'),
neuspjelo_Dodavanje = document.createElement('div'),
anchor,
span,
x;
if(data.neuspjelo_Dodavanje.length){
neuspjelo_Dodavanje.innerHTML = '<p>Nazalost, sljedece nije dodano: </p>';
}
uploads.innerText = '';
uploads.textContent = '';
for( x = 0; x < data.uspjesno_Dodano.length; x = x + 1){
anchor = document.createElement('a');
anchor.href = '../slike/galerija/' + data.uspjesno_Dodano[x].file;
anchor.innerText = data.uspjesno_Dodano[x].name;
anchor.textContent = data.uspjesno_Dodano[x].name;
anchor.target = '_blank';
uspjesno_Dodano.appendChild(anchor);
}
for( x = 0; x < data.neuspjelo_Dodavanje.length; x = x + 1){
span = document.createElement('span');
span.innerText = data.neuspjelo_Dodavanje[x].name;
span.textContent = data.neuspjelo_Dodavanje[x].name;
neuspjelo_Dodavanje.appendChild(span);
}
uploads.appendChild(uspjesno_Dodano);
uploads.appendChild(neuspjelo_Dodavanje);
},
error: function(){
console.log('Ne radi!');
}
});
});
</script>
<script>
</script>
</div>
</fieldset>
</form>
</div>
</div>
<?php include 'dno.php' ?>
The .js looks like this
var app = app || {};
(function(o){
"use strict";
//Privatne metode
var ajax, getFormData, setProgress;
ajax = function(data){
var xmlhttp = new XMLHttpRequest(), uspjesno_Dodano;
xmlhttp.addEventListener('readystatechange', function(){
if(this.readyState === 4){
if(this.status === 200){
uspjesno_Dodano = JSON.parse(this.response);
if(typeof o.options.finished === 'function'){
o.options.finished(uspjesno_Dodano);
}
} else {
if(typeof o.options.error === 'function'){
o.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress', function(event){
var percent;
if(event.lengthComputable === true){
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source){
var data = new FormData(), i;
for(i = 0; i < source.length; i = i + 1){
data.append('file[]', source[i]);
}
data.append('ajax', true);
data.append('kategorija', o.options.kategorija);
return data;
};
setProgress = function(value){
if(o.options.progressBar !== undefined){
o.options.progressBar.style.width = value ? value + '%' : 0;
}
if(o.options.progressText !== undefined){
o.options.progressText.innerText = value ? value + '%' : '';
o.options.progressText.textContent = value ? value + '%' : '';
}
};
o.uploader = function(options){
o.options = options;
if(o.options.files !== undefined){
ajax(getFormData(o.options.files.files));
}
}
}(app));
On the process.php part i want to listen the option value from select
"<select name="kategorija" id="kategorija">"
on the process.php when i
<?php
$kategorija = $_POST['kategorija'];
echo echo $kategorija;
?>
i alwasy get a 0 value, so what i am doing wrong? The file[] processing is working fine, but can't get it to work with a addtional variable.
You don't need to echo echo $kategorija; It should be echo $kategorija; If this causes an issue, which it might, try var_dump($kategorija) to view the contents of the variable.
Also, you're including your js throughout the page, this should be refactored and included properly in the head. The php should not be in the form of the document, it should be contained outside and included like you are doing with '../db/baza.php'; Finally, look into using PDO to connect to your db.
What I'm trying to do is to allow students answer questions and see each vote after each question and then the teacher can push the next question. The votes will then be entered into the database which I can use to produce a chart. I currently have the student answering questions but I'm having problem on stopping the next question from coming so the poll vote can show and how to show the vote before the next question comes.
This gets the questions from the database:
function getQuestion(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function(){
if (hr.readyState==4 && hr.status==200){
var response = hr.responseText.split("|");
if(response[0] == "finished"){
document.getElementById('status').innerHTML = response[1];
}
var nums = hr.responseText.split(",");
document.getElementById('question').innerHTML = nums[0];
document.getElementById('answers').innerHTML = nums[1];
document.getElementById('answers').innerHTML += nums[2];
}
}
hr.open("GET", "questions.php?question=" + <?php echo $question; ?>, true);
hr.send();
function post_answer(){
var p = new XMLHttpRequest();
var id = document.getElementById('qid').value;
var url = "userAnswers.php";
var vars = "qid="+id+"&radio="+x();
p.open("POST", url, true);
p.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
p.onreadystatechange = function() {
if(p.readyState == 4 && p.status == 200) {
document.getElementById("status").innerHTML = '';
alert("Your answer was submitted"+ p.responseText);
var url = 'quiz.php?question=<?php echo $next; ?>';
window.location = url;
}
}
p.send(vars);
document.getElementById("status").innerHTML = "processing...";
}
On a different php file:
require_once 'core/init.php';
$arrCount = "";
if(isset($_GET['question'])){
$question = preg_replace('/[^0-9]/', "", $_GET['question']);
$output = "";
$answers = "";
$q = "";
$connection = mysqli_connect('localhost', 'root', '', 'alsp');
$sql = mysqli_query($connection,"SELECT id FROM questions");
$numQuestions = mysqli_num_rows($sql);
if(!isset($_SESSION['answer_array']) || $_SESSION['answer_array'] < 1){
$currQuestion = "1";
}else{
$arrCount = count($_SESSION['answer_array']);
}
if($arrCount > $numQuestions){
unset($_SESSION['answer_array']);
header("location: start-quiz.php");
exit();
}
if($arrCount >= $numQuestions){
echo 'finished|<p>There are no more questions. Please enter your username and submit</p>
<form action="userAnswers.php" method="post">
<input type="hidden" name="complete" value="true">
<input type="text" name="username">
<button class="btn btn-action" type="submit" value="finish">Submit</button>
</form>';
exit();
}
$singleSQL = mysqli_query($connection,"SELECT * FROM questions WHERE id='$question' LIMIT 1");
while($row = mysqli_fetch_array($singleSQL)){
$id = $row['id'];
$thisQuestion = $row['question'];
$type = $row['type'];
$question_id = $row['question_id'];
$q = '<h2>'.$thisQuestion.'</h2>';
$sql2 = mysqli_query($connection,"SELECT * FROM answers WHERE question_id='$question' ORDER BY rand()");
while($row2 = mysqli_fetch_array($sql2)){
$answer = $row2['answer'];
$correct = $row2['correct'];
$answers .= '<label style="cursor:pointer;"><input type="radio" name="rads" value="'.$correct.'">'.$answer.'</label>
<input type="hidden" id="qid" value="'.$id.'" name="qid"><br /><br />
';
}
$output = ''.$q.','.$answers.',<span id="btnSpan"><button onclick="post_answer()"class="btn btn-action">Submit</button></span>';
echo $output;
}
}
I'm guessing rather than have a submit button that takes you to the next page, after clicking on a radio button, the vote should show and then the teacher can push the next question. That's were the main issue is.
Hi Guys I have this search from that takes a search term matches it with a table.field and in php it searches all matching data.
I want to add autocomplete to it, can anyone PLEASE assist?
Here is the HTML FORM
<form action="'.$_SERVER['REQUEST_URI'].'" method="post">
<input type="text" id="searchThis" name="searchThis" placeholder="search" value="" size="14" />
<select name="searchItems" id="searchItems">
<optgroup value="Vehicles" label="Vehicles">Vehicles
<option value="vehicles.Make">Make</option>
<option value="vehicles.model">Model</option>
<option value="vehicles.RegNumber">Registration Number</option>
<option value="vehicles.licenseExpireDate">License Expire Date</option>
</optgroup>
<optgroup value="Owners" label="Owners">Clients
<option value="owners.OwnerName" label="" >Name</option>
<option value="owners.mobile">Mobile Number</option>
</optgroup>
</select>
<input type="submit" id="doSearch" name="Search" value="Search" />
</form>
<ul id="result">
</ul>
There is the JS
<script src="js/jquery-1.8.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
var $j = jQuery.noConflict();
(function($j){
$j(document).ready(function (){
$j("#searchThis").keyup(function()
{
var searchThis = $j('#searchThis').val();
var searchItems = $j('#searchItems').val();
var dataString = {'searchThis': searchThis,'searchItems':searchItems};
if(searchThis!='')
{
$j.ajax({
type: "POST",
url: "doAutocomplete_search.php",
data: dataString,
dataType: "html",
cache: false,
success: function(data)
{
$j("#result").html(data).show();
}
});
}return false;
});
$j("#result").live("click",function(e){
var clicked = $j(e.target);
var name = clicked.find('.name').html();
var decoded = $j("<div/>").html(name).text();
$j('#searchThis').val(decoded);
});
$j(document).live("click", function(e) {
var clicked = $j(e.target);
if (! clicked.hasClass("search")){
$j("#result").fadeOut();
}
});
$j('#searchid').click(function(){
$j("#result").fadeIn();
});
});
})($j);
And the PHP
function implement($cxn,$searchThis, $field) {
$show = "";
//Item to be searched
$srchThis = strip_tags(trim($searchThis));
//[0]= table , [1]=field to search
$srchStack = explode('.',$field);
$gtData = "SELECT * FROM ".$srchStack[0]." WHERE ".$srchStack[1]." like '%|{$srchThis}|%'";
//or die(mysqli_error($cxn))
if($selectc = mysqli_query($cxn,"SELECT * FROM {$srchStack[0]} WHERE {$srchStack[1]} LIKE '{$srchThis}%' OR {$srchStack[1]} LIKE '%{$srchThis}%'")) {
$srchData = array();
$rows = mysqli_fetch_row($selectc);
echo $rows;
//if() {, MYSQL_ASSOC
//echo var_dump($srchData);
$show .= '
<table style="border:2px solid #0000">';
//foreach($srchData as $fields=>$data) {
for($s=0; $s < $rows && $srchData = mysqli_fetch_assoc($selectc);$s++) {
if($srchStack[0] == 'vehicles' && $fields == 'RegNumber') {
$dataItem = $data;
$editTbl = 'Vehicles';
$link = 'href="index.php?list=vehicles&&tbl='.$srchStack[0].'&&item='.$dataItem.'"';
} elseif($srchStack[0] == 'vehicles' && $fields == 'Make') {
$dataItem = $data;
$editTbl = 'vehicles';
$link = 'href="index.php?list=vehicles&&tbl='.$srchStack[0].'&&item='.$dataItem.'"';
}
$show .= '<tr><td><a '.$link.'>'.$data.'</a></td></tr>
';
}
$show .= '</table>';
return $show;
} else {
$show .= "There are no entries in the database...<br>".mysqli_error($cxn);
return $show;
}
//}
}
echo implement($cxn, $_POST['searchThis'], $_POST['searchItems']);
$cxn->close();
Hi Guys so i had to do some refactoring, realized it was more the PHP MySQL code.
Here is the refactored PHP code
//Item to be searched
$srchThis = strip_tags(trim($searchThis));
//[0]= table , [1]=field to search
$srchStack = explode('.',$field);
$gtData = "SELECT * FROM ".$srchStack[0]." WHERE ".$srchStack[1]." like '%|{$srchThis}|%'";
//or die(mysqli_error($cxn))
if($selectc = mysqli_query($cxn,"SELECT * FROM {$srchStack[0]} WHERE {$srchStack[1]} LIKE '{$srchThis}%' OR {$srchStack[1]} LIKE '%{$srchThis}%'")) {
//$srchData = array();
$rows = mysqli_num_rows(#$selectc) or die(mysqli_error($cxn).'<br>No Rows returned...');
if($rows > 0) {//, MYSQL_ASSOC
//$link = ''; $l_c = 0;
$show .= '<table style="border:2px solid #0000">';
for($c = NULL;$c != $rows && $srchData = mysqli_fetch_assoc($selectc); $c++) {
foreach($srchData as $fields=>$data) {
if($fields == $srchStack[1]) {
$dataItem = $data;
$editTbl = $srchStack[0];
$show .= '<tr><td>'.$dataItem.'</td></tr>';//$a_json_row($dataItem);
//$show .= $link[$c];$link[$c]
}
}
}
$show .= '</table>';
return $show;
} else {
$show .= "There are no entries in the database...<br>".mysqli_error($cxn);
return $show;
}
Of-course the JS code still needs some more work but this greatly improved the results...
Hope this help someone...