how to load data using a javascript - javascript

I have almost zero experience with Javascript , I need to use this Javascript in my php script .
<script>
let arr = ["alfa", "beta", "charlie"]
const updateResult = query => {
let resultList = document.querySelector(".result");
resultList.innerHTML = "";
arr.map(algo =>{
query.split(" ").map(word =>{
if(algo.toLowerCase().indexOf(word.toLowerCase()) != -1){
resultList.innerHTML += `<li class="list-group-item">${algo}</li>`;
}
})
})
}
updateResult("")
</script>
This script load the data using
let arr =
However suppose I have all the data specified there in a file in this format
c:/data/mydata.txt
and the data.txt contains data in this form (one data per row)
alfa
bravo
charlie
Now how should I change the javascript above to load the data from c:/data/mydata.txt and not using
let arr = ["alfa", "beta", "charlie"]
?
Thank you

You do not need to change your file, but you cannot use it directly due to security issues. If I would write a Javascript which reads your secret files and you load my page, all your secrets would be revealed, therefore, if you want to load a file, you either have to allow your user to upload it and once the user uploads the file do your logic, or, you can request it via AJAX.
How to upload a file
An example for this is
<!DOCTYPE html>
<html>
<body onload="myFunction()">
<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
<p id="demo"></p>
<script>
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += "<br><strong>" + (i+1) + ". file</strong><br>";
var file = x.files[i];
if ('name' in file) {
txt += "name: " + file.name + "<br>";
}
if ('size' in file) {
txt += "size: " + file.size + " bytes <br>";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
</script>
<p><strong>Tip:</strong> Use the Control or the Shift key to select multiple files.</p>
</body>
</html>
source: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_fileupload_files
Getting the file via AJAX
In order to do that, you will need to:
send an AJAX request in your javascript code
parse the request and send back the file via PHP
do your logic in Javascript when the request is responded
Example:
HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Download POST Request</title>
</head>
<body>
Enter a text and click the button: <input type="text" id="content" value="Text for the generated pdf">
<button id="download">Send AJAX Request and download file</button>
<script>
document.getElementById('download').addEventListener('click', function () {
var content = document.getElementById('content').value;
var request = new XMLHttpRequest();
request.open('POST', '../server/', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.responseType = 'blob';
request.onload = function() {
// Only handle status code 200
if(request.status === 200) {
// Try to find out the filename from the content disposition `filename` value
var disposition = request.getResponseHeader('content-disposition');
var matches = /"([^"]*)"/.exec(disposition);
var filename = (matches != null && matches[1] ? matches[1] : 'file.pdf');
// The actual download
var blob = new Blob([request.response], { type: 'application/pdf' });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
// some error handling should be done here...
};
request.send('content=' + content);
});
</script>
</body>
</html>
PHP
<?php
require_once 'vendor/autoload.php';
if($_SERVER['REQUEST_METHOD'] === 'POST') {
header('Content-type: application/pdf');
http_response_code(200);
// Contents
$pdfContent = !empty($_POST['content']) ? $_POST['content'] : 'no content specified';
// Generate the PDOF
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10, $pdfContent);
return $pdf->Output(null, 'foobar-' . time() . '.pdf');
}
// Bad method
http_response_code(405);
exit();
Source: https://nehalist.io/downloading-files-from-post-requests/
You will of course need to modify the code to comply to your needs. Reading a tutorial would not hurt.

you can use ajax for loading data from external file.
a sample of jquery get call is given below. You can also use the same code with your file path and variables.
$("button").click(function(){
$.get("demo_test.php", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
if you are using pure java script instead of jQuery you have to use pure ajax calls.
for more details about jQuery ajax check this link

Related

AJAX return undefined in html document

I have the following xml document
<?xml version="1.0" ?>
<result searchKeyword="Mathematics">
<video>
<title>Chaos Game</title>
<channel>Numberphile</channel>
<view>428K</view>
<link>http://www.youtube.com/watch?v=kbKtFN71Lfs</link>
<image>http://i.ytimg.com/vi/kbKtFN71Lfs/0.jpg</image>
<length>8:38</length>
</video>
<video>
<title>Australian Story: Meet Eddie Woo, the maths teacher you wish you&apos;d had in high school</title>
<channel>ABC News (Australia)</channel>
<view>223K</view>
<link>http://www.youtube.com/watch?v=SjIHB8WzJek</link>
<image>http://i.ytimg.com/vi/SjIHB8WzJek/0.jpg</image>
<length>28:08</length>
</video>
<video>
<title>Ham Sandwich Problem</title>
<channel>Numberphile</channel>
<view>557K</view>
<link>http://www.youtube.com/watch?v=YCXmUi56rao</link>
<image>http://i.ytimg.com/vi/YCXmUi56rao/0.jpg</image>
<length>5:53</length>
</video>
<video>
<title>Magic Square Party Trick</title>
<channel>Numberphile</channel>
<view>312K</view>
<link>http://www.youtube.com/watch?v=aQxCnmhqZko</link>
<image>http://i.ytimg.com/vi/aQxCnmhqZko/0.jpg</image>
<length>3:57</length>
</video>
<video>
<title>The 8 Queen Problem</title>
<channel>Numberphile</channel>
<view>909K</view>
<link>http://www.youtube.com/watch?v=jPcBU0Z2Hj8</link>
<image>http://i.ytimg.com/vi/jPcBU0Z2Hj8/0.jpg</image>
<length>7:03</length>
</video>
</result>
I have created this html file which has an AJAX call to get the xml file but it return all the values as "undefined"
<html>
<head>
<title>A7-Question2</title>
<script>
function getSearch()
{
// create an XMLHttpRequest
var xhttp = new XMLHttpRequest();
//create a handler for the readyState change
xhttp.onreadystatechange = function() {
readyStateChangeHandler(xhttp);
};
//get XML file by making async call
xhttp.open("GET", "A7.xml", true);
xhttp.send();
}
// handler for the readyState change
function readyStateChangeHandler(xhttp){
if (xhttp.readyState == 4){
// readyState = 4 means DONE
if(xhttp.status == 200){
// status = 200 means OK
handleStatusSuccess(xhttp);
}else{
// status is NOT OK
handleStatusFailure(xhttp);
}
}
}
// XMLHttpRequest failed
function handleStatusFailure(xhttp){
// display error message
var displayDiv = document.getElementById("display");
displayDiv.innerHTML = "XMLHttpRequest failed: status " + xhttp.status;
}
// XMLHttpRequest success
function handleStatusSuccess(xhttp){
var xml = xhttp.responseXML;
// print XML on the console
console.log(xml);
// parse the XML into an object
var searchResult = parseXML(xml);
// print object on the console
console.log(searchResult);
// display the object on the page
display(searchResult);
}
// parse the XML into an object
function parseXML(xml){
var resultElement = xml.getElementsByTagName("result")[0];
//create a receipt object to hold the information in the xml file
var searchResult = {};
searchResult.searchKeyword= resultElement.getAttribute("searchKeyword");
var videoElements = xml.getElementsByTagName("video");
//create an array to hold the items
searchResult.videoArray = [];
for(var i=0; i< videoElements.length; i++){
var video = {};
video.title = videoElements[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
video.channel = Number(videoElements[i].getElementsByTagName("channel")[0].childNodes[0].nodeValue);
video.view = Number(videoElements[i].getElementsByTagName("view")[0].childNodes[0].nodeValue);
video.link = Number(videoElements[i].getElementsByTagName("link")[0].childNodes[0].nodeValue);
video.image = Number(videoElements[i].getElementsByTagName("image")[0].childNodes[0].nodeValue);
searchResult.videoArray.push(video);
};
return searchResult;
}
// display the searcg result object on the page
function display(searchResult){
var html = "<p>searchKeyword: Mathematics</p>";
for(var i=0; i<searchResult.videoArray.length; i++){
var video = searchResult.videoArray[i];
html += "title: " + searchResult.title + "<br/>";
html += "channel: " + searchResult.channel + "<br/>";
html += "view: " + searchResult.view + "<br/>";
html += "link: " + searchResult.link + "<br/>";
html += "image: " + searchResult.image + "<br/>";
html += "length: " + searchResult.length + "<br/>";
}
var displayDiv = document.getElementById("display");
displayDiv.innerHTML = html;
}
</script>
</head>
<body>
<button onclick="getSearch()">Get Search Result</button>
<div id="display"></div>
</body>
</html>
Is the problem with my success function? Is it returning null because it hasn't returned all the values or something due to how AJAX runs?
Thanks heaps for any help
There's a lot of code to go over and a working snippet can't be produced because we can't put the XML file here.
This answer is making an assumption that your response from the XMLHttpRequest is null and the problem does not lie in any of your parsing functions.
It also seems that you're over complicating the request process by passing it around to many functions when it's quite simple itself.
Here is an example I made locally that correctly logged the XML to the console:
<!doctype html>
<html>
<head>
<title>A7-Questions2</title>
</head>
<body>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var xml = xhttp.responseXML;
// Logs just fine for me. You can do your parsing here.
console.log(xml);
}
};
xhttp.onerror = function() {
// Display error message.
var displayDiv = document.getElementById('display');
displayDiv.textContent = 'XMLHttpRequest failed status: ' + xhttp.status;
};
xhttp.open('GET', './path/to/xml.xml');
xhttp.send();
</script>
</body>
</html>

Export 2D javascript array to Excel sheet

I know, there are hundreds of questions on this topic on here, but I still could not find satisfactory answers after a day of searching:
I have a 2D javascript array, which I want to download as an Excel sheet.
Here is a fiddle with the code I got so far:
https://jsfiddle.net/3an24jmw/7/
The download works, but there are several issues, which I could not solve after days of trying:
All items end up in the first column of the Excel sheet, because Excel interprets the "," separating the elements as part of the data. How can I separate the elements in a way Excel understands?
The file name is some cryptic code. How can I set the file name?
The downloaded file has a double .xls ending (.xls.xls). How can get a single .xls ending?
Excel tells me every time the file could be corrupted or unsafe. How do I prevent this?
Any help for any of these questions would be appreciated.
exportToCsv = function() {
var CsvString = "";
Results.forEach(function(RowItem, RowIndex) {
RowItem.forEach(function(ColItem, ColIndex) {
CsvString += ColItem + ',';
});
CsvString += "\r\n";
});
window.open('data:application/vnd.ms-excel,' + encodeURIComponent(CsvString));
}
UPDATE
I just found out by chance, that 1. 2. and 4. can be solved by replacing vnd.ms-excel with csv.
The file will not be .xls anymore, but the csv can be opened by Excel without problems and behaves like intended.
Only problem remaining is the file name!
UPDATE 2
Finally after 2 full workdays of searching and trying, I found the solution, which I would like to share here, to help anybody with the same problem:
Simply include an invisible <a> element, which defines the file an useful name using its download="somedata.csv" attribute.
Here is my final and fully functional fiddle:
https://jsfiddle.net/3an24jmw/25/
Finaly after 2 full workdays of searching and trying, I found the solution, which I would like to share here, to help anybody with the same problem:
Simply include an invisible element, which gives the file an usefull name using its download="somedata.csv" attribute:
Here is my final and fully functional fiddle:
https://jsfiddle.net/3an24jmw/25/
var Results = [
["Col1", "Col2", "Col3", "Col4"],
["Data", 50, 100, 500],
["Data", -100, 20, 100],
];
exportToCsv = function() {
var CsvString = "";
Results.forEach(function(RowItem, RowIndex) {
RowItem.forEach(function(ColItem, ColIndex) {
CsvString += ColItem + ',';
});
CsvString += "\r\n";
});
CsvString = "data:application/csv," + encodeURIComponent(CsvString);
var x = document.createElement("A");
x.setAttribute("href", CsvString );
x.setAttribute("download","somedata.csv");
document.body.appendChild(x);
x.click();
}
The separator Excel expects for csv depends on your system locale setting for list separator.
You can hint Excel which separator to use for your csv file by adding "sep=," as the first line.
In your case use could use: var CsvString = '"sep=,"\r\n';
https://github.com/shuchkin/simplexlsxgen#js-array-to-excel-ajax
<?php // array2excel.php
if (isset($_POST['array2excel'])) {
require __DIR__.'/simplexlsxgen/src/SimpleXLSXGen.php';
$data = json_decode($_POST['array2excel'], false);
\Shuchkin\SimpleXLSXGen::fromArray($data)->downloadAs('file.xlsx');
return;
}
?>
<html lang="en">
<head>
<title>JS array to Excel</title>
</head>
<script>
function array2excel() {
var books = [
["ISBN", "title", "author", "publisher", "ctry"],
[618260307, "The Hobbit", "J. R. R. Tolkien", "Houghton Mifflin", "USA"],
[908606664, "Slinky Malinki", "Lynley Dodd", "Mallinson Rendel", "NZ"]
];
var json = JSON.stringify(books);
var request = new XMLHttpRequest();
request.onload = function () {
if (this.status === 200) {
var file = new Blob([this.response], {type: this.getResponseHeader('Content-Type')});
var fileURL = URL.createObjectURL(file);
var filename = "", m;
var disposition = this.getResponseHeader('Content-Disposition');
if (disposition && (m = /"([^"]+)"/.exec(disposition)) !== null) {
filename = m[1];
}
var a = document.createElement("a");
if (typeof a.download === 'undefined') {
window.location = fileURL;
} else {
a.href = fileURL;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
alert("Error: " + this.status + " " + this.statusText);
}
}
request.open('POST', "array2excel.php");
request.responseType = "blob";
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send("array2excel=" + encodeURIComponent(json));
}
</script>
<body>
<input type="button" onclick="array2excel()" value="array2excel" />
</body>
</html>

CKEditor response callback after file attached successfully

Using CKEditor to send email and upload attachments. Below is the minimal configuration I've from this source.
CKEDITOR.replace('email.Message', {
filebrowserUploadUrl: '/Controller/UploadAttachment',
extraPlugins: 'attach', // attachment plugin
toolbar: this.customToolbar, //use custom toolbar
autoCloseUpload: true, //autoClose attachment container on attachment upload
validateSize: 30, //30mb size limit
onAttachmentUpload: function(response) {
/*
the following code just utilizes the attachment upload response to generate
ticket-attachment on your page
*/
attachment_id = $(response).attr('data-id');
if (attachment_id) {
attachment = $(response).html();
$closeButton = $('<span class="attachment-close">').text('x').on('click', closeButtonEvent)
$('.ticket-attachment-container').show()
.append($('<div>', {
class: 'ticket-attachment'
}).html(attachment).append($closeButton))
.append($('<input>', {
type: 'hidden',
name: 'attachment_ids[]'
}).val(attachment_id));
}
}
});
On the Controller side I've got below code
const string scriptTag = "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction({0}, '{1}', '{2}')</script>";
public ContentResult UploadAttachment()
{
string basePath = HttpContext.Server.MapPath("~/assets/Images/");
const string baseUrl = #"/ckfinder/userfiles/";
var funcNum = 0;
int.TryParse(Request["CKEditorFuncNum"], out funcNum);
if (Request.Files == null || Request.Files.Count < 1)
return BuildReturnScript(funcNum, null, "No file has been sent");
if (!System.IO.Directory.Exists(basePath))
return BuildReturnScript(funcNum, null, "basePath folder doesn't exist");
var receivedFile = Request.Files[0];
var fileName = receivedFile.FileName;
if (string.IsNullOrEmpty(fileName)) {
return BuildReturnScript(funcNum, null, "File name is empty");
}
var sFileName = System.IO.Path.GetFileName(fileName);
var nameWithFullPath = System.IO.Path.Combine(basePath, sFileName);
//Note: you may want to consider using your own naming convention for files, as this is vulnerable to overwrites
//e.g. at the moment if two users uploaded a file called image1.jpg, one would clash with the other.
//In the past, I've used Guid.NewGuid() combined with the file extension to ensure uniqueness.
receivedFile.SaveAs(nameWithFullPath);
var url = baseUrl + sFileName;
return BuildReturnScript(funcNum, url, null);
}
private ContentResult BuildReturnScript(int functionNumber, string url, string errorMessage) {
return Content(
string.Format(scriptTag, functionNumber, HttpUtility.JavaScriptStringEncode(url ? ? ""), HttpUtility.JavaScriptStringEncode(errorMessage ? ? "")),
"text/html"
);
}
Below is the response I get back inside onAttachmentUpload - function
<form enctype="multipart/form-data" method="POST" dir="ltr" lang="en" action="/Controller/UploadAttachment?CKEditor=email_Message&CKEditorFuncNum=0&langCode=en">
<label id="cke_73_label" for="cke_74_fileInput_input" style="display:none"></label>
<input style="width:100%" id="cke_74_fileInput_input" aria-labelledby="cke_73_label" type="file" name="attachment" size="38">
</form>
<script>
window.parent.CKEDITOR.tools.callFunction(98);
window.onbeforeunload = function({
window.parent.CKEDITOR.tools.callFunction(99)
});
</script>
But it is expecting some data-id for attachment id. I've no idea what the response should look like. Could someone tell me what the actual response should look like and what is the data-id its expecting as attr in response? Also, is there anyway I can upload multiple files with this?
This is how I am returning the response now and rendering the attached file. Hope it might help someone in future.
[AcceptVerbs(HttpVerbs.Post)]
public ContentResult UploadAttachment() {
string basePath = HttpContext.Server.MapPath("~/somepath");
var funcNum = 0;
int.TryParse(Request["CKEditorFuncNum"], out funcNum);
if (Request.Files == null || Request.Files.Count < 1)
return Content("No file has been sent");
if (!System.IO.Directory.Exists(basePath))
Directory.CreateDirectory(Path.Combine(basePath));
var receivedFile = Request.Files[0];
var fileName = receivedFile.FileName;
if (string.IsNullOrEmpty(fileName)) {
return Content("File name is empty");
}
var sFileName = System.IO.Path.GetFileName(fileName);
var nameWithFullPath = Path.Combine(basePath, sFileName);
receivedFile.SaveAs(nameWithFullPath);
var content = "<span data-href=\"" + nameWithFullPath + "\" data-id=\"" + funcNum + "\"><i class=\"fa fa-paperclip\"> </i> " + sFileName + "</span>";
return Content(content);
}
and on the JS side I have below code to append the uploaded file name:
CKEDITOR.replace('email.Message', {
filebrowserUploadUrl: '/Controller/UploadAttachment',
extraPlugins: 'attach', // attachment plugin
toolbar: this.customToolbar, //use custom toolbar
autoCloseUpload: true, //autoClose attachment container on attachment upload
validateSize: 30, //30mb size limit
onAttachmentUpload: function(response) {
/*
the following code just utilizes the attachment upload response to generate
ticket-attachment on your page
*/
attachment_id = $(response).attr('data-id');
if (attachment_id) {
attachment = response;
$closeButton = '<span class="attachment-close btn btn-danger float-right" style="margin-top:-7px"><i class="fa fa-trash"></i></span>'; //.on('click', closeButtonEvent)
$respDiv = '<ol class="breadcrumb navbar-breadcrumb" style="padding:18px 15px"><li style="display:block">' + attachment + $closeButton + '</li></ol>';
$('.ticket-attachment-container').show()
.append($('<div>', {
class: 'ticket-attachment'
}).html($respDiv))
.append($('<input>', {
type: 'hidden',
name: 'attachment_ids[]'
}).val(attachment_id));
$('.ticket-attachment-container').on('click', '.attachment-close', function() {
$(this).closest('.ticket-attachment').remove();
if (!$('.ticket-attachment-container .ticket-attachment').length)
$('.ticket-attachment-container').hide();
});
}
}
});

Getting data from python in Javascript and AJAX

I have some issues retrieving info from python and try to show the data in a html page
I get the date from a python script (data.py)
import cx_Oracle
import json
lst_proveedores=[{}]
conn_str = 'user/pass#database'
conn = cx_Oracle.connect(conn_str)
c = conn.cursor()
c.execute('select id, name from provider')
for row in c:
record1 = {"id":row[0], "name":row[1]}
lst_proveedores.append(record1)
json_string = json.dumps(lst_proveedores)
print json_string
conn.close()
I try to parse the info with AJAX in a html page
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function ajax_get_json(){
var results = document.getElementById("results");
var hr = new XMLHttpRequest();
hr.open("GET", "prov1.py", true);
hr.responseType = "JSON";
hr.setRequestHeader("Content-Type", "application/json", true);
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
results.innerHTML = "";
for(var obj in data){
results.innerHTML += data[obj].id+" is "+data[obj].nombre+"<hr />";
}
}
}
hr.send(null);
results.innerHTML = "requesting...";
}
</script>
</head>
<body>
<div id="results"></div>
<script type="text/javascript">ajax_get_json();</script>
</body>
</html>
but doesn't work
I setup apache to execute python scripts and work with very simple scripts, but doesn't work when I retrieve data from the database
How can I show the data in a html page?
Or what language or framework may I can use to show the data
Any advice
I am desperate
Thanks in advance
First of all, you should try visit your python files in browser. If you can't see json print on page, there're problems in your server or python code.
If it works, that may be something wrong in your Ajax request.
You can use jQuery or zepto.js to help. They contain a method of Ajax: $.ajax.
You can visit: http://zeptojs.com
And search "$.ajax" on the page for help; )
===============================================================
try this:
//var data = JSON.parse(hr.responseText);
var data = JSON.parse(hr.response);
===============================================================
and this is my onreadystatechange function code, use it if it helps:
ajaxObject.onreadystatechange = function(){
//console.info('[Ajax request process] url:' + url +'; readyState:' + ajaxObject.readyState + '; status:' + ajaxObject.status);
if (ajaxObject.readyState == 4 && ((ajaxObject.status >= 200 && ajaxObject.status < 300) || ajaxObject.status == 304)){
var result = null;
switch (dataType){
case 'text':
result = ajaxObject.responseText;
break;
case 'xml':
result = ajaxObject.responseXML;
break;
case 'json':
default:
result = ajaxObject.response ? JSON.parse(ajaxObject.response) : null;
break;
}
if (typeof(success) == 'function'){
success(result,url);
}
}else if (ajaxObject.readyState > 1 && !((ajaxObject.status >= 200 && ajaxObject.status < 300) || ajaxObject.status == 304)){
console.warn('[Ajax request fail] url:' + url +'; readyState:' + ajaxObject.readyState + '; status:' + ajaxObject.status);
if (typeof(error) === 'function' && errorCallbackCount == 0){error(url);errorCallbackCount++;}
return false;
}
}

JSON error when trying to parse request length in loop

So I am trying to make a simple autocomplete form but keep getting a error when I try to test the program.
When I try to test the program my console spits out [11:25:26.267] SyntaxError: JSON.parse: unexpected character # /search.php:22 which is this line. I am pretty sure my syntax is fine but I could be mistaken. Any and all help would be most gratefully appreciated. Thank you to anyone who takes the time to read and/or answer even if you cannot help!
for (var i = 0; i < response.length; i++)
My Full code is as follows.
Edit: Now with page that echos the json. When I do console.log(req.responsetext) i get [11:38:04.967] ReferenceError: req is not defined. But i define req as a new xml request on window load so I am kind of stumped.
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Auto Complete</title>
</head>
<body>
<script>
window.onload = function () {
var req = new XMLHttpRequest(); //the HTTP request which will invoke the query
var input = document.getElementById('search'); //where to grab the search from
var output = document.getElementById('results'); //where to display the sugestions
input.oninput = getSuggestions;
function getSuggestions() {
req.onreadystatechange = function () {
output.innerHTML = ""; //CLEAR the previous results!! only once the server can process new ones though
if (this.readyState == 4 && input.value != "") {
var response = JSON.parse('(' + req.responseText + ')');
for (var i = 0; i < response.length; i++)
addSuggestion(response[i].terms);
}
}
req.open('GET', 'getterms.php?query=' + input.value, true); //GET request to getterms.php?=
req.send(null);
}
addSuggestion = function (suggestion) {
var div = document.createElement('div');
var p = document.createElement('p');
div.classList.add('suggestion'); //suggestion[x]...
p.textContent = suggestion;
div.appendChild(p);
output.appendChild(div);
div.onclick = function() {
input.value = p.innerHTML; //set the search box
getSuggestions(); //GET new suggesions
}
}
}
</script>
<input type='text' id='search' name='search' autofocus='autofocus'>
<div id='results'></div>
</body>
</html>
edit this is my php page that echos the json.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
if (!isset($_GET['query']) || empty($_GET['query']))
header('HTTP/1.0 400 Bad Request', true, 400);
else {
$db = new PDO(
my database
);
$search_query = $db->prepare("
SELECT * FROM `words` WHERE `word` LIKE :keywords LIMIT 5
");
$params = array(
':keywords' => $_GET['query'] . '%',
);
$search_query->execute($params);
$results = $search_query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
}
?>
Get rid of the ( and ) in the JSON.parse!
JSON.parse('(' + req.responseText + ')')
should be
JSON.parse( req.responseText );
hopefully the responseText is valid JSON

Categories

Resources