JSON URL : http://en.wikipedia.org/w/api.php?format=json&action=opensearch&search="+str+"&namespace=0&suggest=
Here "str" may be any 2-3 char for an example
str = 'nas'
then JSON URL : http://en.wikipedia.org/w/api.php?format=json&action=opensearch&search=nas&namespace=0&suggest=
I want to grab all result and put these result in a table
I tried AJAX, JSON, JQUERY
Can any one send me working Code for doing this .
My Dummy Code as :-
<!DOCTYPE html>
<html>
<head>
<script type="application/javascript">
function FillSearchBox(str)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status=200)
{
//Pointer never Comes in this Section (If I Debuug I got xmlhttp.status=0 every time)
var JSONObject = JSON.parse(xmlhttp.responseText);
}
}
var strr= "http://en.wikipedia.org/w/api.php?format=json&action=opensearch&search="+str+"&namespace=0&suggest=";
xmlhttp.open("GET",strr,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<input type="text" name="wikisearch" id="" onkeyup="FillSearchBox(this.value)" />
</form>
<!-- add Table or Div Here -->
</body>
</html>
You need to use JSONP to make cross-origin requests:
function gotData(d) { alert(d); }
var s = document.createElement('script');
s.src = "http://en.wikipedia.org/w/api.php?format=json&action=opensearch&search="+str+"&namespace=0&callback=gotData";
s.appendTo(document.body);
Note that this is much easier with jQuery.
Related
I have wrote a HTML/Javascript code generator but instead of outputting the code to a HTML site i would like the code to be send to php to be added to a database but i cant work out how to get the out put of the javascript into PHP
there is also another javascript doc to go with this if you need it to make it work ..
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="../voucher_codes.js"></script>
</head>
<body>
<h1>pattern codes</h1>
<ul id="pattern-codes"></ul>
<script>
var patternCodes = voucher_codes.generate({
prefix: "BREAK-",
postfix: "-2019",
length:5,
count: 5,
charset: "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
});
function fillList(listId, items) {
var list = document.getElementById(listId);
items.forEach(function(item) {
list.innerHTML += "<li>" + item + "</li>";
});
}
fillList("pattern-codes", patternCodes);
</script>
</body>
</html>
i am wanting the output of the function "fillList" to send the output to PHP if this is possible....
You would have to look into using AJAX or the Axios library to send requests to a server page such as PHP.
Here is a simple AJAX POST server request in Javascript:
`
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = this.responseText;
}
};
xhttp.open("POST", "request_page.php", true); // set method and page
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // set content type that we are sending POST data
xhttp.send("key=VALUE&key=VALUE"); // POST values
}
</script>
`
On the PHP page if you want to give a response of data to use back in Javascript, make sure to
json_encode($array_values)
the data array before echoing it out and set the headers to
header("Content-Type: application/json")
so you can grab the response data in Javascript and it can be turned into a Javascript {Object} or [Array]
I have this type of xml
<root>
<Message code="AC_CONNECTOR__FAIL_IN_CONNECT"
id="AR_AC_CONNECTOR__FAIL_IN_CONNECT"
bundleName="Error" locale="pt" severity="4" userFlag="">
(AR1-000001) Error in the data
</Message>
<Message code="AC_CONNECTOR__FAIL_IN_DISCONNECT"
id="AR_AC_CONNECTOR__FAIL_IN_DISCONNECT" bundleName="Error"
locale="pt" severity="4" userFlag="">
(AR1-000001) error
</Message>
</root>
and i want it to be read in the javascript
after reading this i need to replace value of the message with another based on the code property of the message
i have done this code ...
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Reading XML</title>
<script type="text/javascript">
function readXML() {
var xml = new XMLHttpRequest();
xml.open('GET', 'error1.xml', false);
xml.send();
var xmldata = xml.responseXML;
document.write("Nutan");
xmldata = (new DOMParser()).parseFromString(xml.responseText, 'text/xml');
var emp = xmldata.getElementsByTagName("ptr");
// document.write(emp);
var output=emp[0].getElementsByTagName("Message")[0].firstChild.data;
document.write(output);
}
</script>
</head>
<body>
<h1>
XMl file
</h1>
<button onclick="readXML()">Read xml file</button>
</body>
</html>
but this code is not reading the xml file ..which is in above format
please help me to read xml file with above format
If you want to access the code value you have to use the getAttribute("code") function reference, if you want to list the code value for each child the following code is working.
<html>
<head>
<script>
function readXML() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
};
xhttp.open("GET", "error1.xml", true);
xhttp.send();
}
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName("Message");
for (var i = 0; i < x.length; i++) {
var node_code = x[i].getAttribute("code");
document.write(node_code + " ");
var node_value = x[i].childNodes[0].nodeValue;
document.write(node_value + " <br>");
}
}
</script>
</head>
<body>
<button onclick="readXML()">Read xml file</button>
</body>
</html>
It's better if you separate your JS code from your HTML by using two separate files. If this isn't what you are looking for please explain your problem better.
I am attempting to write this code so when I click on the XML button it will show my XML document. I am unable to get the button to do anything, I am assuming that the function is missing something. Any help would be appreciated. Thanks in advance.
Function
<script language = "JavaScript">
xmlOpen = function(){
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
xmlhttp.open("GET","gameXML.xml",false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
}
</script>
Button HTML
<p>
<label>List of users:</label>
<input type="button" value="XML" id="users" onclick="xmlOpen()">
</p>
Are you serving these files from a web server? OR are you just opening the HTML page from your file system? If you use Chrome and try to open the HTML file from your file system, you will get an error (see the console) when you click the "XML" button.
To get around this, you can either serve the files from a web server (even on your local machine) OR you could try opening the HTML page in Firefox.
In terms of displaying the contents of the XML file, try taking a look at this question: How do I loop through XML Nodes in JavaScript?
Update:
I was successful in testing with the code below. Opening the HTML file from my Desktop in Firefox.
gameXML.xml
<?xml version="1.0" encoding="UTF-8" ?>
<users>
<user>Bob</user>
<user>James</user>
<user>Karen</user>
<user>Tom</user>
<user>Linda</user>
</users>
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<title>Test Page</title>
</head>
<body>
<p>
<label>List of users:</label>
<input type="button" value="XML" id="users" onclick="xmlOpen()">
<table id="tbody"></table>
</p>
<script language = "JavaScript">
xmlOpen = function(){
var users, i, len;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
xmlhttp.open("GET", "gameXML.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
users = xmlDoc.getElementsByTagName("user");
len = users.length;
for (i = 0; i < len; i++) {
var user = users[i].firstChild.nodeValue;
var tr = document.createElement("tr");
var td = document.createElement("td");
var textNode = document.createTextNode(user);
td.appendChild(textNode);
tr.appendChild(td);
document.getElementById("tbody").appendChild(tr);
}
}
</script>
</body>
</html>
Screenshot of result:
did you forget to display the data? If so, add this to your function:
document.getElementById('users').innerHTML = xmlDoc;
If that does not work, change responseXML to responseText.
If that does not work, try replacing
xmlhttp.open("GET","gameXML.xml",false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
with
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("users").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gameXML.xml",true);
xmlhttp.send();
I am testing out some code with Python and Javascript trying to get an Ajax system set up. Basically I just want to input a word and have the python code send it back. Here is my html/javascript:
<html>
<head>
<title>Simple Ajax Example</title>
<script language="Javascript">
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari/Chrome
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
updatepage(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send(getquerystring());
}
function getquerystring() {
var form = document.forms['f1'];
var word = form.word.value;
qstr = 'w=' + escape(word); // NOTE: no '?' before querystring
return qstr;
}
function updatepage(str){
document.getElementById("result").innerHTML = str;
}
</script>
</head>
<body>
<form name="f1">
<p>word: <input name="word" type="text">
<input value="Go" type="button" onclick='JavaScript:xmlhttpPost("/ajaxtest")'></p>
<div id="result"></div>
</form>
</body>
</html>
and here is my python:
class AjaxTest(BlogHandler):
def get(self):
user = self.get_user()
self.render('ajaxtest.html', user = user)
def post(self):
user = self.get_user()
word = self.request.get('w')
logging.info(word)
return '<p>The secret word is' + word + '<p>'
#having print instead of return didn't do anything
When I do logging the word shows up correctly and when I hardcode str in:
function updatepage(str){
document.getElementById("result").innerHTML = str;
}
It displays that correctly but right now without hardcoding it shows nothing. How am I supposed to send the response? I am using webapp2 as my Python framework and Jinja2 as the templating engine, though I don't think that has much to do with it. Do I need to send the HTTP headers?
If your problem is having difficulty returning a string from your post method, without rendering a template you can use the write method to accomplish that:
self.response.write('')
I believe you can change headers by just modifying self.response.headers
The code below is to read a text file using javascript. it works.
However, I just want to read part of the content.
For example, the content of the file is :"Hello world!"
I just want to display "Hello".
I tried function split(), but it only works on strings. I don't know how to insert it here.
var urls = ["data.txt"];
function loadUrl() {
var urlToLoad = urls[0];
alert("load URL ... " + urlToLoad);
browser.setAttributeNS(xlinkNS, "href", urlToLoad);
}
thank you!!!
I used
jQuery.get('http://localhost/foo.txt', function(data) {
var myvar = data;
});
, and got data from my text file.
Or try this
JQuery provides a method $.get which can capture the data from a URL. So to "read" the html/text document, it needs to be accessible through a URL. Once you fetch the HTML contents you should just be able to wrap that markup as a jQuery wrapped set and search it as normal.
Untested, but the general gist of it...
var HTML_FILE_URL = '/whatever/html/file.html';
$(document).ready(function() {
$.get(HTML_FILE_URL, function(data) {
var fileDom = $(data);
fileDom.find('h2').each(function() {
alert($(this).text());
});
});
});
Try this to read separate words if I understood correctly what you need.
Create a file with the contents "hello world" and browse to it with the example script.
The output is "hello".
<html>
<head>
<input type="file" id="fileinput" />
<script type="text/javascript">
function readSingleFile(evt) {
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
var ct = r.result;
var words = ct.split(' ');
alert(words[0]);
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
</head>
<body>
</body>
</html>
Reading directly has to be with an ajax request due to the javascript restrictions regarding safety.
This code shoudl perform the requested operation:
<html>
<head>
<input type="file" id="fileinput" />
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status==200 && xmlhttp.readyState==4){
var words = xmlhttp.responseText.split(' ');
alert(words[0]);
}
}
xmlhttp.open("GET","FileName.txt",true);
xmlhttp.send();
</script>
</head>
<body>
</body>
</html>
Opening a file in javascript with ajax (without using any framework)
var urls = ["data.txt"];
xhrDoc= new XMLHttpRequest();
xhrDoc.open('GET', urls[0] , async)
if (xhrDoc.overrideMimeType)
xhrDoc.overrideMimeType('text/plain; charset=x-user-defined')
xhrDoc.onreadystatechange =function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
var data= this.response; //Here is a string of the text data
}
}
}
xhrDoc.send() //sending the request