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:
Related
EDIT:
SOLVED. Thank you all for help. :)
EDIT:
Your suggestions worked. The problem now is that after the first find and displaying the found result, the found set stays the same no matter what i try to find next. Even after restarting the browser. Is it possible that the found data stays somewhere in server cache and is displayed as a result?
I'm trying to send data from the form using jquery to php file process it there and then display the result from it.
After pressing the submit nothing happens. There are no errors in the console.
Everything worked before i added jquery but after that i don't see any result.
My HTML:
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<form id="my_form">
Imie: <br/> <input name="name" id="firstname" type="text" /><br />
<input id="submit_form" type="submit" value="Submit">
</form>
<div id="update_div"></div>
<script>
var submit_button = $('#submit_form');
submit_button.click(function() {
var var_name = $('firstname').val();
var update_div = $('#update_div');
console.log('zmienna var_name ' + var_name);
console.log('zmienna update_div ' + update_div);
$.ajax({
type: 'GET',
url: 'test.php',
data: var_name,
success: function(response){
update_div.html(response);
}
});
});
</script>
</body>
</html>
My PHP:
<?php
require 'db_handler.php';
$criterion_name = $_GET['name'];
$query = $fm->newFindCommand("OFERTY tabela");
$query->addFindCriterion('kontrahent_opiekun', "=" . $criterion_name);
$result = $query->execute();
if(FileMaker::isError($result)){
echo($result->getMessage());
return;
}
$i = 0;
// Get array of found records
$records = $result->getRecords();
foreach ($records as $record) {
echo $record->getField('_kp_oferta') . " - ";
echo $record->getField('kontrahent_Skrot') . " - ";
echo $record->getField('kontrahent_opiekun') . '</br>';
$i++;
}
echo $i . " Pozycje";
?>
I am trying to import a json array from a php script in JavaScript but every time the request fails and the xhr.responseText return the html code of the template of the html template associated to it. I am using xampp.
php code:
<?php
// This script is meant to display the data from Insight sensors DB
include('includes/motebymote.html');
if ($_SERVER['REQUEST_METHOD'] == 'POST'){//Use the post method as a request method to the server
require('mysqli_connect.php');//Give information on which database to use
if(!empty($_COOKIE["mote_ID"]) || !empty($_COOKIE["std"]) || !empty($_COOKIE["end"])){
//Setting variables
$moteID=$_COOKIE["mote_ID"];
$start=$_COOKIE["std"];
$end=$_COOKIE["end"];
if(preg_match("/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/", $start) || preg_match("/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/", $end)) {
if(isset($moteID) && isset($start) && isset($end)){
//Building the query
$q="SELECT date_time, modality, value FROM sensor_data WHERE mote_id = $moteID and date_time BETWEEN '$start' and '$end'";
$r = #mysqli_query ($dbc, $q);//Doing the request
$numRow = mysqli_num_rows($r);
if ($r && $numRow>0){
//echo "<p>There are $numRow data points associated to mote$moteID</p><br>";
//echo"<table align ='center' width ='70%' cellpadding='4'><tr><th>Date&Time</th><th> Sensor Type</th><th> Value</th></tr>";
$moteArray = array();
while($data = mysqli_fetch_array($r, MYSQLI_BOTH)){
//echo "<tr align ='center'><td>" .$data['date_time']. "</td><td>" .$data['modality']. "</td><td>" .$data['value']. "</td></tr>";
$moteArray[] = $data;
}
//echo"</table>";
$JSONMoteArray = json_encode($moteArray);
echo $JSONMoteArray;
}
else if ($numRow==0){
echo "<h1>Sorry there are no data available</h1>
<p>There are no data available for mote$moteID</p>";
}
else{//Give an error message if the query fails
echo '<h1>System Error</h1>
<p class="error">We could not record your order due to a system error. We apologize for any inconvenience.</p>';
}
}
}
else {
echo "<h1> Wrong date format</h1>
<p>Please input the starting date in a yyyy-mm-dd format</p>";
}
}
else{
echo "<h1> Wrong input</h1>
<p> Please make sure that the mote is properly selected and that the start and end dates are entered in yyyy-mm-dd format</p>";
}
mysqli_close($dbc); //close the database
}
exit(); //exits the script
?>
<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="utf-8">
<title> Motes Data</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="js/mote.js" async></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body><br>
<form action="motebymote.php" method="post">
<p>Please input a mote number: <input type="text" name="moteNo" id="moteNo"></p>
<p> Please input a starting date (yyyy-mm-dd):<input type="text" name="stDate" id="stDate"></p>
<p> Please input an end date (yyyy-mm-dd):<input type="text" name="endDate" id="endDate"></p>
<p><input type="submit" name="submit" value="submit" id="submit"/></p>
<p><input type="submit" name="display" value="display" id="display"/></p>
<div id="columnchart_material" style="width: 800px; height: 500px;"></div>
</form>
</body>
</html>
var but = document.getElementById("submit"); //Looking for the submit button
if(but){ //if the button is clicked activate the event listener
but.addEventListener("click", moteIDDate);
}
//This function goes to fetch the different values and store them with cookies //to allow motebymote.php to use them
function moteIDDate(){
var moteID = $('#moteNo').val();
document.cookie="mote_ID = " + moteID + ";time()+3600";
var start = $("#stDate").val();
document.cookie = "std="+start+";time() 3600";
var end = $("#endDate").val();
document.cookie= "end="+ end+";time() 3600";
};
var jsonData = $.ajax({
url: "http://localhost/Insight/mote2/motebymote.php",
type:"GET",
cache: false,
dataType: "json",
success: function(xhr){
console.log(xhr.responseText);
},
error: function(xhr){
console.log(xhr.responseText);
}
});
The php code has "if...== POST"
your javascript ajax call is sending a "GET"
I am not an expert at php just a newbie so not sure what to do.What I am trying to do is to keep on saving the result I am getting from the textboxThis is the textbox and shirt,color and price is the result I am getting from the table and keep on displaying it on my page. The picture for the textbox is attached. I want to keep on storing the new result I get from the table and also keep displaying the old one. I hope its clear what I am trying to do. My code has three files the main file products.php has the following code
<!DOCTYPE html>
<html>
<head>
<title>Products</title>
<p> Scan the Barcode of the Product </p>
<link href="mystyle.css" rel="stylesheet">
</head>
<body>
<input type="text" name="enter" required id="item" style="text-align:centre" placeholder=" Barcode ID" autofocus />
<div id="item-data"></div>
<script src="js/jquery-2.2.0.min.js"></script> <!--jquery link-->
<script src="js/global.js"></script> <!--linking event file-->
</body>
</html>
while code for global.js is
$(function(){
//press enter on text area..
$('#item').keypress(function (event) {
var key = event.which;
if(key == 13) // the enter key code
{
var item = $('input#item').val(); // retreiving the value from the item
if ($.trim(item) != ''){ //send this to php file but if its empty or spaces(trim) are there dont send it//
$.post('ajax/name.php',{id:item}, function(data){ //using post method sending to the father(name.php), sending the data through the file item
$('div#item-data').append(""+data+"</br>"); // grabing the data and displaying it
});
}
$('#item').val('');
}
});
});
and the third file my name.php file consists of the following code
<?php
require '../db/connect.php';
$id= $_POST['id']; // your post variable
$sql = "SELECT BarcodeID, shirts, price FROM clothes WHERE BarcodeID=".mysqli_real_escape_string($con,$id);
$result = mysqli_query($con,$sql) or die(mysqli_error($con));
if(mysqli_num_rows($result)>0)
{
while($row = $result->fetch_assoc())
{
echo " " . $row["BarcodeID"]. " shirt color: " . $row["shirts"]. " price: " . $row["price"];
}
}
else
{
echo "ID not found, Please Scan again";
}
mysqli_close($con);
?>
This issue was solved by using append function in the javascript. Check in the global.js file.
I'm trying to see whether a particular name I entered is on the list or not. And I want the response in XML. I've tried whatever I could but not getting the result. (I'm using firefox by the way).
HTML
<html>
<head>
<script type="text/javascript" src="javer.js"></script>
</head>
<body>
<h1>Testing ajax!</h1>
<form onsubmit="changer('inputing')">
enter name <input type="text" id="inputing" />
<input type="submit" />
</form>
<p id="ch">enter name to check</p>
</body>
</html>
JAVASCRIPT
function changer(a) {
var mo = new XMLHttpRequest();
var qry = document.getElementById(a).value;
mo.onreadystatechange = function() {
if(mo.readyState == 4 && mo.status == 200) {
var res = mo.responseXML;
document.getElementById("ch").innerHTML = res.firstChild.nodeValue;
}
}
mo.open("GET", "appr.php?name=" + qry, true);
mo.send(null);
}
PHP
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo "<cover>";
$b = array("sam", "norton", "maya", "sijosh", "noor", "timothy");
$c = $_GET["name"];
if(in_array($c, $b)) {
echo "he is here";
}
else { echo "sorry... we dont know him"; }
echo "</cover>";
?>
You probably don't see what is happening as the form gets submitted the non-ajax / regular way as well.
You can avoid that by using for example:
<form action='' onsubmit="changer('inputing'); return false;">
Although ideally you would get rid of the inline javascript altogether and handle everything in a javascript event handler.
Well at last I figured it out! There were two problems. First one was that the page was getting refreshed every time I submit the form, as you guys said. I corrected it. The second problem was in the parsing of XML data. I transferred the XML to the variable 'res' but after that I had to get the 'documentElement' from the XML. So I added another variable 'xmlde'.
xmlde = res.documentElement;
Then,
document.getElementById("ch").innerHTML = xmlde.firstChild.nodeValue;
Problem was solved!
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.