I'm trying to use javascript and read from http://search.yahooapis.com/ WebSearchService /V1/webSearch?appid=YahooDemo &query=persimmon&results=2 using xmlhttp. I'm getting an error because it cannot read
<script type="text/javascript">
url="http://search.yahooapis.com/ WebSearchService /V1/webSearch?appid=YahooDemo &query=persimmon&results=2";
var xmlhttp = null;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
if ( typeof xmlhttp.overrideMimeType != 'undefined')
{
xmlhttp.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert('Perhaps your browser does not support xmlhttprequests?');
}
xmlhttp.open('GET', url, true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
alert("success");
}
else
{
alert("failure");
}
};
</script>
Unless your web site is hosted on search.yahooapis.com you're probably encountering the Same Origin Policy.
This is causing your outgoing request to return with a 404 status code:
You should be using JSONP instead of XMLHttpRequest:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript file download</title>
<script type="text/javascript">
function yahooApi(resp) {
var scriptEl = document.getElementById("yahooApiJsonP");
scriptEl.parentNode.removeChild(scriptEl);
console.log(resp);
}
window.onload = function() {
var scriptEl = document.createElement("script");
scriptEl.id = "yahooApiJsonP";
scriptEl.src = "http://search.yahooapis.com/WebSearchService/V1/webSearch?output=json&callback=yahooApi&appid=YahooDemo&query=persimmon&results=2";
document.body.appendChild(scriptEl);
};
</script>
</head>
<body>
<p>This is a test</p>
</body>
</html>
This will send the request, which will return a 200 OK status:
It also looks like this service has been shut down:
Related
I wanna make ajax calls in symfony2. I already done with ajax with flat php and i have no idea how to set up in this symfony framework.
<html>
<head>
<script>
function showBook(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
function showAuthor(str){
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getAuthor.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form action="">
Book name: <input type="text" id="txt1" onkeyup="showBook(this.value)">
<br><br>
Author name:<input type="text" id="txt1" onkeyup="showAuthor(this.value)">
</form>
<br>
<div id="txtHint"><b>book info will be listed here...</b></div>
</body>
</html>
Where should i pass this request?? to controller??
how to set routes??
is there any way to use flat php instead of controller??
You would pass the request to a controller action exposed using a route:
http://symfony.com/doc/current/book/routing.html
Then in your html code, if you are using twig and including javascript in a script tag, you can do
xmlhttp.open("GET","{{ path("route_name", {"parameter_name":"parameter_value"}) }}");
If you want to access the route in an attached .js file, you can use FOSJsRoutingBundle to generate the route url
If you are in a form, you can do something like :
$(document).submit(function () {
var url = $('form').attr('action');
var data = $('form').serialize();
$.post(url, data, function (data) {
window.location.href = data.redirect;
})
.fail(function () {
$('form').replaceWith(data.form);
});
});
You just need to send the correct url :
$(document).on('click', 'a', function () {
var url = window.location.href;
$.get(url, function (data) {
$('.container').replaceWith(data);
});
});
It is also possible to use a routing generate, simply add:
"friendsofsymfony/jsrouting-bundle": "dev-master" to your composer.json.
AppKernel.php :
new FOS\JsRoutingBundle\FOSJsRoutingBundle()
Then config it in your routing.yml :
fos_js_routing:
resource: "#FOSJsRoutingBundle/Resources/config/routing/routing.xml"
And finally use "expose" arg in your routing :
#Route("/{table}/index", name="beta.index", options={"expose"=true})
I use annotation routing
In your JS :
var url = Routing.generate('beta.index', { 'table': 'foo' });
Hope it'll help you :)
I am trying to use XSL to translate an XML file into a neat table. For that I used the examples provided by W3schools which can be located here as a starting point. Yet the browser(chrome) is throwing the error that is described in the title of this post. I even tried copying the exact same example on W3 only to be met with the same error. Tried debugging in Firefox, this is the console output
TypeError: Argument 1 of XSLTProcessor.importStylesheet is not an object.
A similar question was posted before and the solution was in changing the model from synchronous to async. I tried doing that through the onreadystatechange method but without success. Here is the code I worked with.
<html>
<head>
<script>
function loadXMLDoc(filename)
{
if (window.ActiveXObject)
{
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
else
{
xhttp = new XMLHttpRequest();
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
return xhttp.responseXML;
}
};
xhttp.open("GET", filename);
try {xhttp.responseType = "msxml-document"} catch(err) {} // Helping IE11
xhttp.send("");
}
function displayResult()
{
xsl = loadXMLDoc("cdcatalog.xsl");
xml = loadXMLDoc("cdcatalog.xml");
// code for IE
if (window.ActiveXObject || xhttp.responseType == "msxml-document")
{
ex = xml.transformNode(xsl);
document.getElementById("dataTable").innerHTML = ex;
}
// code for Chrome, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument)
{
xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
resultDocument = xsltProcessor.transformToFragment(xml, document);
document.getElementById("dataTable").appendChild(resultDocument);
}
}
</script>
</head>
<body onload="displayResult()">
<div id="dataTable" />
</body>
Thank you for all the help!
Here is an example of two asynchronous requests where the callback of one event handler starts the next request whose callback does the transformation. To keep it simple, I have used onload instead of onreadystatechange, if you really need support for old IE versions you will need to adapt the code.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>XMLHttpRequest and onload handler with asynchronous requests</title>
<script>
function load(url, callback) {
var req = new XMLHttpRequest();
req.open('GET', url);
// to allow us doing XSLT in IE
try { req.responseType = "msxml-document" } catch (ex) {}
req.onload = function() {
callback(req.responseXML);
};
req.send();
}
function transform(xml, xsl) {
load(
xml,
function(inputXml) {
load(
xsl,
function(xsltSheet) {
displayResult(inputXml, xsltSheet);
}
);
}
);
}
function displayResult(xmlInput, xsltSheet) {
if (typeof XSLTProcessor !== 'undefined') {
var proc = new XSLTProcessor();
proc.importStylesheet(xsltSheet);
document.getElementById('example').appendChild(proc.transformToFragment(xmlInput, document));
}
else if (typeof xmlInput.transformNode !== 'undefined') {
document.getElementById("example").innerHTML = xmlInput.transformNode(xsltSheet);
}
}
</script>
</head>
<body onload="transform('catalog.xml', 'catalog.xsl')">
<div id="example"></div>
</body>
</html>
Online at http://home.arcor.de/martin.honnen/xslt/test2015072001.html, works fine with current versions of IE, Firefox and Chrome on Windows 8.1.
If you want to start two asynchronous requests directly to load XML and XSLT then you need to do some more work to make sure you know when both documents have been loaded to process them, an example of that is at http://home.arcor.de/martin.honnen/xslt/test2015072101.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>XMLHttpRequest and onload handler with asynchronous requests</title>
<script>
function makeRequest(url, loadedData, property, elementToAddResult) {
var req = new XMLHttpRequest();
req.open('GET', url);
// to allow us doing XSLT in IE
try { req.responseType = "msxml-document" } catch (ex) {}
req.onload = function() {
loadedData[property] = req.responseXML;
if (checkLoaded(loadedData)) {
displayResult(loadedData.xmlInput, loadedData.xsltSheet, elementToAddResult);
};
};
req.send();
}
function checkLoaded(loadedData) {
return loadedData.xmlInput != null && loadedData.xsltSheet != null;
}
function loadAndTransform(xml, xsl, elementToAddResult) {
var loadedData = { xmlInput: null, xsltSheet: null };
makeRequest(xml, loadedData, 'xmlInput', elementToAddResult);
makeRequest(xsl, loadedData, 'xsltSheet', elementToAddResult);
}
function displayResult(xmlInput, xsltSheet, elementToAddResult) {
if (typeof XSLTProcessor !== 'undefined') {
var proc = new XSLTProcessor();
proc.importStylesheet(xsltSheet);
elementToAddResult.appendChild(proc.transformToFragment(xmlInput, document));
}
else if (typeof xmlInput.transformNode !== 'undefined') {
elementToAddResult.innerHTML = xmlInput.transformNode(xsltSheet);
}
}
</script>
</head>
<body onload="loadAndTransform('catalog.xml', 'catalog.xsl', document.getElementById('example'));">
<div id="example"></div>
</body>
</html>
I want to retrieve all elements from an ajax call, then insert them into another element without:
using jquery (I just want to use pure JavaScript)
creating a new element to contain the ajax response
Here's what I have tried:
index.php
<!DOCTYPE HTML>
<head>
<script type="text/javascript">
function loadPage() {
var ajax = new XMLHttpRequest();
ajax.open('GET', 'test.php', true);
ajax.onreadystatechange = function (){
if(ajax.readyState === 4 && ajax.status === 200){
document.getElementById('output').appendChild( ajax.responseText ) ;
}
};
ajax.send();
}
loadPage();
</script>
</head>
<body>
<div id="output">
<h1>Default</h1>
</div>
</body>
</html>
test.php
<h1>
its work
</h1>
<div>
<h2>
its work2
</h2>
</div>
I already googled it, but the answer was always to use jQuery.
Node.appendChild requires a Node object as an argument. What you're getting from test.php is a string. Try using innerHTML instead
document.getElementById('output').innerHTML = ajax.responseText;
As of XHR level 2, you can simply attach an onload handler to XHR instead of checking the readyState and status properties.
ajax.onload = function() {
document.getElementById('output').innerHTML += this.responseText;
}
have you looked at this
http://w3schools.com/ajax/ajax_examples.asp
http://w3schools.com/ajax/tryit.asp?filename=tryajax_first
I think the most of the examples that you find use jquery because jquery makes it cross browser
try this one
function loadPage(){
var strURL="test.php";
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('output').value=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
function getXMLHTTP() { //function to return the xml http object
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
xmlhttp = false;
}
}
}
I'm trying to do a basic AJAX tutorial to read data from a file, hello.txt, into my webpage. hello.txt and my current html webpage are in the same directory. Does anyone know what I'm doing wrong? Nothing happens when I load the page.
<!DOCTYPE html>
<head><title>Ajax Test</title>
<script type="text/javascript">
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "hello.txt", true);
xmlHttp.addEventListener("load", ajaxCallback, false);
xmlHttp.send(null);
function ajaxCallback(event){
alert( "Your file contains the text: " + event.target.responseText );
}
</script>
</head>
<body>
</body>
</html>
here is a function i always use for simple async get ajax:
1.use onload as it's shorter to write and as you don't need to add multiple eventhandlers.
2.don't do syncronous ajax.
js
function ajax(a,b,c){//url,function,just a placeholder
c=new XMLHttpRequest;
c.open('GET',a);
c.onload=b;
c.send()
}
function alertTxt(){
alert(this.response)
}
window.onload=function(){
ajax('hello.txt',alertTxt)
}
example
http://jsfiddle.net/9pCxp/
extra info
https://stackoverflow.com/a/18309057/2450730
full html
<html><head><script>
function ajax(a,b,c){//url,function,just a placeholder
c=new XMLHttpRequest;
c.open('GET',a);
c.onload=b;
c.send()
}
function alertTxt(){
alert(this.response)
}
window.onload=function(){
ajax('hello.txt',alertTxt)
}
</script></head><body></body></html>
Here is your answer.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var allText = this.responseText;
alert(allText);
}
};
xhttp.open("GET", "filename.txt", true);
xhttp.send();
The below code may be useful for someone...
<!DOCTYPE html>
<html>
<body>
<h1>Load Data from text file </h1>
<button type="button" onclick="loadDoc()">Change Content</button>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "info.txt", true);
xhttp.send();
document.getElementById("demo").innerHTML = xhttp.responseText;
}
</script>
</body>
</html>
Open an empty .PHP file or .ASPX file (or just any server-side language that can run javascript)
Paste this code between "head" tags.
<script>
var xmlhttp;
function loadXMLDoc(url, cfunc) {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = cfunc;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function myFunction() {
loadXMLDoc("hello.xml", function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
});
}
</script>
As you see, javascript is referring to "hello.xml" file to get information from.
Open an empty XML file inside the project folder you have created in. Name your XML file as "hello.xml"
Paste this code to your XML file.
<?xml version="1.0" encoding="utf-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Run your php (or .aspx) file on localhost.
Click on button, your page must acquire the XML data into your website.
function Go() {
this.method = "GET";
this.url = "hello.txt";
if (window.XMLHttpRequest && !(window.ActiveXObject)) {
try {
this.xmlhttp = new XMLHttpRequest();
}
catch (e) {
this.xmlhttp = false;
}
// branch for IE/Windows ActiveX version
}
else if (window.ActiveXObject) {
try {
this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
this.xmlhttp = false;
}
}
}
if (this.xmlhttp) {
var self = this;
if (this.method == "POST") {
this.xmlhttp.open("POST", this.url, true);
}
else {
//remember - we have to do a GET here to retrive the txt file contents
this.xmlhttp.open("GET", this.url, true);
}
this.xmlhttp.send(null);
//wait for a response
this.xmlhttp.onreadystatechange = function () {
try {
if (self.xmlhttp.readyState == 4) {
if (self.xmlhttp.status == 200) {
if (self.xmlhttp.responseText != null) {
self.response = self.xmlhttp.responseText;
alert(self.xmlhttp.responseText);
}
else {
self.response = "";
}
}
else if (self.xmlhttp.status == 404) {
alert("Error occured. Status 404: Web resource not found.");
}
else if (self.xmlhttp.status == 500) {
self.showHtmlError("Internal server error occured", "Status: " + self.xmlhttp.responseText);
}
else {
alert("Unknown error occured. Status: " + self.xmlhttp.status);
}
}
}
catch (e) {
alert("Error occured. " + e.Description + ". Retry or Refresh the page");
}
finally {
}
};
}
}
//Use the function in your HTML page like this:
Go();
</script>
I'm trying to familiarize myself with Ajax as I will need to use it continually for work. I'm working through the W3Schools tutorial trying things with my Apache2 server. I have a file called ajax_info.txt on the server (under /var/www (ubuntu)). I'm making a call to it and with Firebug I see I get a good response (4 & 200) but it isn't outputting the contents of the file to the DOM. Here's the code:
<!DOCTYPE html>
<html>
<head>
<script>
var xmlhttp;
var url = "http://192.168.0.5/ajax_info.txt";
function loadXMLDoc(url, cfunc) {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = cfunc;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function myFunction() {
loadXMLDoc(url, function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
});
}
</script>
</head>
<body>
<div id="myDiv">
<h2>Let AJAX change this text</h2>
</div>
<button type="button" onclick="myFunction()">Change Content</button>
</body>
</html>
I'm not exactly sure what it is I'm doing wrong. The w3schools tutorial isn't exhaustive by any stretch. I plan on buying a book, but I'd love to learn these simple GET calls as it will get me headed in the proper direction. Any suggestions would be greatly appreciated.
function ajax(x) {
var a;
if (window.XMLHttpRequest) {
a = new XMLHttpRequest();
} else if (window.ActiveXObject) {
a = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Browser Dosent Support Ajax! ^_^");
}
if (a !== null) {
a.onreadystatechange = function() {
if (a.readyState < 4) {
//document.getElementById('cnt').innerHTML = "Progress";
} else if (a.readyState === 4) {
//respoce recived
var res = a.responseText;
document.getElementById('center_scrolling_div').innerHTML = res;
eval(document.getElementById('center_scrolling_div').innerHTML);
}
};
a.open("GET", x, true);
a.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
a.send();
}
}