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;
}
}
Related
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
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'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>
I am trying to implement a simple "global" counter that updates based on every user that clicks the button on their browsers button. For example, if you go to the website and click the button, I will see the counter increase on my side if I'm on the same website. I sought to do this with long polling, but am facing some issues. Mainly the server variable is not coming back as I think it should.
The server:
package main
import (
"net/http"
"log"
"io"
"io/ioutil"
)
var messages chan string = make(chan string, 100)
var counter = 0
func PushHandler(w http.ResponseWriter, req *http.Request) {
body, err := ioutil.ReadAll(req.Body)
if err != nil {
w.WriteHeader(400)
}
counter += 1
messages <- string(counter)
}
func PollResponse(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, <-messages)
}
func main() {
http.Handle("/", http.FileServer(http.Dir("./")))
http.HandleFunc("/poll", PollResponse)
http.HandleFunc("/push", PushHandler)
err := http.ListenAndServe(":8005", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
The client:
<html>
<script language=javascript>
function longpoll(url, callback) {
var req = new XMLHttpRequest ();
req.open ('GET', url, true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if (req.status == 200) {
callback(req.responseText);
longpoll(url, callback);
} else {
alert ("long-poll connection lost");
}
}
};
req.send(null);
}
function recv(msg) {
var box = document.getElementById("counter");
box.value += msg + "\n";
}
function send() {
var box = document.getElementById("counter");
var req = new XMLHttpRequest ();
req.open ('POST', "/push?rcpt=", true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if (req.status == 200) {
} else {
alert ("failed to send!");
}
}
};
req.send("hi")
//box.innerHTML += "test" ;
}
</script>
<body onload="longpoll('/poll', recv);">
<h1> Long-Poll Chat Demo </h1>
<p id="counter"></p>
<button onclick="send()" id="test">Test Button</button>
</body>
</html>
The counter variable is not coming back from the server for some reason. I believe I am changing the state every time the button is clicked and so the longpolling function should get the newly updated counter variable. If you have any suggestions, please let me know!
I see two issues in you program:
1. In the server:
messages <- string(counter)
You should use "strconv" package
messages <- strconv.Itoa(counter)
string(0) will return something like []byte{0} not a "0"
2. In your client:
function recv(msg) {
var box = document.getElementById("counter");
box.value += msg + "\n";
}
Should be:
function recv(msg) {
var box = document.getElementById("counter");
box.innerHTML += msg + "\n";
}
I don't think the p element have value property
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
Building a chat app and I am trying to fetch all logged in user into a div with ID name "chat_members". But nothing shows up in the div and I have verified that the xml file structure is correct but the javascript i'm using alongside ajax isn't just working.
I think the problem is around the area of the code where I'm trying to spool out the xml data in the for loop.
XML data sample:
<member>
<user id="1">Ken Sam</user>
<user id="2">Andy James</user>
</member>
Javascript
<script language="javascript">
// JavaScript Document
var getMember = XmlHttpRequestObject();
var lastMsg = 0;
var mTimer;
function startChat() {
getOnlineMembers();
}
// Checking if XMLHttpRequest object exist in user browser
function XmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
} else{
//alert("Status: Unable to launch Chat Object. Consider upgrading your browser.");
document.getElementById("ajax_status").innerHTML = "Status: Unable to launch Chat Object. Consider upgrading your browser.";
}
}
function getOnlineMembers(){
if(getMember.readyState == 4 || getMember.readyState == 0){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.send(null);
}else{
// if the connection is busy, try again after one second
setTimeout('getOnlineMembers()', 1000);
}
}
function memberReceivedHandler(){
if(getMember.readyState == 4){
if(getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
}
</script>
HTML page
<body onLoad="javascript:startChat();">
<!--- START: Div displaying all online members --->
<div id="chat_members">
</div>
<!---END: Div displaying all online members --->
</body>
I'm new to ajax and would really appreciate getting help with this.
Thanks!
To troubleshoot this:
-- Use an HTTP analyzer like HTTP Fiddler. Take a look at the communication -- is your page calling the server and getting the code that you want back, correctly, and not some type of HTTP error?
-- Check your IF statements, and make sure they're bracketed correctly. When I see:
if(getMember.readyState == 4 || getMember.readyState == 0){
I see confusion. It should be:
if( (getMember.readyState == 4) || (getMember.readyState == 0)){
It might not make a difference, but it's good to be absolutely sure.
-- Put some kind of check in your javascript clauses after the IF to make sure program flow is executing properly. If you don't have a debugger, just stick an alert box in there.
You must send the xmlhttp request before checking the response status:
function getOnlineMembers(){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.timeout = 1000; //set timeout for xmlhttp request
getMember.ontimeout = memberTimeoutHandler;
getMember.send(null);
}
function memberTimeoutHandler(){
getMember.abort(); //abort the timedout xmlhttprequest
setTimeout(function(){getOnlineMembers()}, 2000);
}
function memberReceivedHandler(){
if(getMember.readyState == 4 && getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.documentElement.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
To prevent caching response you can try:
getMember.open("GET", "get_chat.php?get_member&t=" + Math.random(), true);
Check the responseXML is not empty by:
console.log(responseXML);
Also you might need to select the root node of the xml response before selecting childNodes:
var members_nodes = xmldoc.documentElement.getElementsByTagName("member"); //documentElement selects the root node of the xml document
hope this helps