I've exhausted every avenue of research to solve this one so hopefully someone else will think of something I just didn't.
Relatively straight forward setup, I have a html page with some javascript that makes an ajax request to a URL (in the same domain) the java web app in the background does its stuff and returns a partial html page (no html, head or body tags, just the content) which should be inserted at a particular point in the page.
All sounds pretty easy and the code I have works in IE, Firefox and Safari, but not in Chrome. In Chrome the target element just ends up empty and if I look at the resource request in Chromes developer tools the response content is also empty.
All very confusing, I've tried a myriad of things to solve it and I'm just out of ideas. Any help would be greatly appreciated.
var container = $('#container');
$.ajax({
type: 'GET',
url: '/path/to/local/url',
data: data('parameters=value&another=value2'),
dataType: 'html',
cache: false,
beforeSend: requestBefore,
complete: requestComplete,
success: requestSuccess,
error: requestError
});
function data(parameters) {
var dictionary = {};
var pairs = parameters.split('&');
for (var i = 0; i < pairs.length; i++) {
var keyValuePair = pairs[i].split('=');
dictionary[keyValuePair[0]] = keyValuePair[1];
}
return dictionary;
}
function requestBefore() {
container.find('.message.error').hide();
container.prepend('<div class="modal"><div class="indicator">Loading...</div></div>');
}
function requestComplete() {
container.find('.modal').remove();
}
function requestSuccess(response) {
container.empty();
container.html(response);
}
function requestError(response) {
if (response.status == 200 && response.responseText == 'OK') {
requestSuccess(response);
} else {
container.find('.message.error').fadeIn('slow');
}
}
All of this is executed in a $(document).ready(function() {});
Cheers,
Jim
#Oleg - Additional information requested, an example of the response that the ajax call might receive.
<p class="message error hidden">An unknown error occured while trying to
retrieve data, please try again shortly.</p>
<div class="timeline">
<a class="icon shuttle-previous"
rel="max_id=16470650733&page=1&q=something">Newer Data</a>
<a class="icon shuttle-next"
rel="max_id=16470650733&page=3&q=something">Older Data</a>
</div>
<ol class="social">
<li class="even">
<div class="avatar">
<img src="sphere_normal.gif"/>
</div>
<p>
Some Content<br/>
<span class="published">Jun 18, 2010 11:29:05 AM</span> - <a
target="_blank" href="">Direct Link</a>
</p>
</li>
<li class="odd">
<div class="avatar">
<img src="sphere_normal.gif"/>
</div>
<p>
Some Content<br/>
<span class="published">Jun 18, 2010 11:29:05 AM</span> - <a
target="_blank" href="">Direct Link</a>
</p>
</li>
</ol>
<div class="timeline">
<a class="icon shuttle-previous"
rel="max_id=16470650733&page=1&q=something">Newer Data</a>
<a class="icon shuttle-next"
rel="max_id=16470650733&page=3&q=something">Older Data</a>
</div>
I just resolved a similar problem, and thought I'd post my solution in case it's of use for anyone else.
Only Firefox and Chrome were showing an empty ajax response, so it seemed to be a cross domain problem, yet everything was on the same domain.
It turned out that the 'www.', which I had superfluously and stupidly hard-coded into my ajax url was to blame. Had I been using a relative path, everything would've been fine.
I had my test site open at that particular moment as "http://domain.com", with no 'www.', so Firefox and Chrome treated it as a different domain. Navigating to "http://www.domain.com" resulted in the ajax call working in all browers.
So, given that you wrote:
url: '/path/to/local/url'
..as is the convention when we don't want to disclose our paths, I couldn't help but wonder if in fact you had written an absolute path, just as I had...?
Chrome stepped onto its own foot with local files security, so no AJAXing local files with relative paths:
http://code.google.com/p/chromium/issues/detail?id=47416
I took your source code and set up a quick test scenario but fail to replicate your problem. It is working for me just fine in both Firefox (3.6.3) and Chrome (5.0.375.70). I tried it both locally and on a remote server.
So your code is most likely not to blame. But I would also think that it's not generally a Chrome related issue.
Other people seem to have come across this though. Changing the content type had no effect in my test scenario though. It even works when I set the Content-Type to image/jpeg.
On the JQuery forums someone indicated differing behavior depending on whether he runs his application locally or on a remote server. If this was the case for you, you could compare HTTP request and response headers to track down the issue.
Related
I am very new to using APIs and am having a difficult time making a GET request to IP Geolocation API. I am not sure if the problem is with my code or with something concerning CodePen (it's probably my code).
I took the JavaScript directly from the example listed on IP Geolocation API page. I was going to modify it after seeing it work in action but I couldn't get it work at all. I tried modifying the URL to include both http:// and https://.
JavaScript:
$(document).ready(function() {
$.getJSON("http://ip-api.com/json/?callback=?", function(data) {
var table_body = "";
$.each(data, function(k, v) {
table_body += "<tr><td>" + k + "</td><td><b>" + v + "</b></td></tr>";
});
$("#GeoResults").html(table_body);
});
});
HTML:
<div class="weather">
<div class="row title">
<h1>weather</h2>
</div>
<div class="row icon">
</div>
<div id = "GeoResults" class="row temp">
<p class = "city">City here</p>
</div>
</div>
URL to my CodePen: https://codepen.io/mattr8/pen/yXEMRM
API I am trying to use: http://ip-api.com/docs/api:json
Codepen doesn't want to work with ip-api.com because of https. Because codepen is served over https it will block any requests that are not https. If you go to http://ip-api.com/json/?callback=? you will see the information you're trying to reach. If you go to https://ip-api.com/json/?callback=? you will receive an error.
The jsbin example they link to does not use https, so it works fine.
So to fix your issue, create an example on a service or your own machine using http, not https for the request.
I'm trying to make a redirection to other page (for example google) but it doesn't work. This is the code:
function algo(a) {
$.get("links/privado/verlink.php?" + a, function(data, status) {
document.getElementById("algunacosa").href = data;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="algunacosa">Ir al link</a>
<button onclick="algo">Retrive link</button>
if the response is: http://google.com it redirects me to http://mrvikxd.ddns.net/m/http://google.com and appears an 403 error
Edit: I've seen the code on the Google Chrome development console and the href of <a id="algunacosa"> is href="http://google.com". I don't know why it doesn't go to Google.
Using the rel attribute on your anchor tag, you should be able to force the link to lead to an external site. https://developer.mozilla.org/en-US/docs/Web/HTML/Link_types
<a id="algunacosa" rel="external">Ir al link</a>
Just fixed. verlink.php was in UTF-8 BOM and it was producing the \uffef character what is not visible but enought to confuse the browser
I am building a player for an online radio station. The stream is providing an XML file that displays the current song information. This XML file is hosted on the stream server which is NOT the server the website is running on.
Here is a sample of whats in the XML. Lets pretend it comes from http://randomserver/station.xml
<playlist>
<stationCallSign>KCXR</stationCallSign>
<programType>PGM</programType>
<mediaType>AUD</mediaType>
<title>Break Free</title>
<artist>Decyfer Down</artist>
<album>End of Grey</album>
<cover>
http://cdnrf.securenetsystems.net/file_radio/album_art/O/1/5/51Oo0rBqATL.jpg
</cover>
<duration>199</duration>
<campaignId/>
<fileId/>
<programStartTS>30 Sep 2015 17:48:22</programStartTS>
<adBlockPos>1</adBlockPos>
</playlist>
I need to pull that data to display it on the webpage and then refresh everything based on how many seconds are in the "duration" field. Essentially refresh all of this when the song changes.
Here is the html output I need.
<div id="playerDiv" class="player-div" style="display: block;">
<div id="album-art">
<img id="now-playing-album-art" src="http://cdnrf.securenetsystems.net/file_radio/album_art/e/1/5/51eeZTxMYuL.jpg" class="player-div-img cP" width="250" height="250" title="">
</div>
<div id="now-playing" class="now-playing tS">
<span id="now-playing-title" class="menuHeader f15em">Lights Out</span> - <span id="now-playing-artist">Silverline</span>
<div id="now-playing-album">Lights Out</div>
</div>
[playercode]
</div>
I was hoping to use the mobile jquery so that this functions well on mobile devices.
It sounds like you might need to do a little more research into ajax requests.
setTimeout(function() {
jQuery.ajax('http://randomserver/station.xml', {
success: function() { //Parse xml and update document },
error: function() { //handle error }
}
}, songDuration);
With jQuery you can easily download your xml file and update the song
In the above code setTimeout(callback,timeInMillis) allows you to set a time in milliseconds for the callback to occur. The callback then makes an XMLHTTPRequest to the url of your choice and then updates the page if it is successful in getting the page.
You can use the default Javascript XML parser to parse the response you get from the server.
Resources Used:
https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout
http://api.jquery.com/jquery.ajax/
I'm doing a project for school and so far it's been a lot of copy this script and paste it here to make things "work". I don't really have any idea what I'm doing besides comparing one line of code to another and looking for the differences.
I've got javascript that is returning some values to me and it works fine when it's in a simple webpage format but when I insert it into a more complicated page it stops working.
At the very end of the page it should give a line of numeric values and be updated every 1000 milliseconds but what happens is it just sits there displaying Temp()...
I've checked the data.xml and those values are being updated when I push buttons and stuff on my PIC protoboard.
I'm using the same ajax.js file for both the simple webpage and the complicated page.
I'm thinking it is something simple like a missed </p> or </div> tag but my eyes don't seem to see it.
Could some take a look at the code and see what I've missed? Thanks!
ajax.js
var xhr;
function getXMLHttpRequest(){
try { return new ActiveXObject("Msxm12.XMLHTTP"); } catch(e){};
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e){};
try { return new XMLHttpRequest(); } catch(e){};
return null;
}
function parseHttpResponse(){
if(xhr.readyState == 4){
if(xhr.status == 200){
document.getElementById("T0").innerHTML=xhr.responseText;
}
else
{
}
}
}
function getTemp(){
xhr = getXMLHttpRequest();
xhr.open("GET", "data.xml", true);
xhr.onreadystatechange = parseHttpResponse;
xhr.send(null);
}
setInterval("getTemp()", 1000);
Simple webpage - this works great
<html>
<head><title>Ajax test - index1</title>
<script src="ajax.js" type="text/javascript">
</script>
</head>
<body onload="getTemp();">
<h2>Headline</h2>
<p>Paragraph</p>
<div id='T0'>Loading Temp0...</div>
</body>
</html>
"Complicated" webpage - when this is used I get no joy
<!DOCTYPE html>
<html>
<head>
<title>Elex267-Webpage</title>
<script src="ajax.js" type="test/javascript">
</script>
<link rel="stylesheet" href="myStyle.css" type="text/css" >
</head>
<body onload="getTemp();">
<!-- Banner at Top of Page ***********************************-->
<div style="background-color:blue; color:white;font-size:30px;">
<img src="Pics/camosun-white.png" alt="CamosunPNG" width="200" height="70" align="left">
<div align="center"style="margin-left:50%">Elex 267 Web Demo
<br>
Microchip TCP/IP Stack v3.02</div>
</div>
<!--*********************************************************-->
<!--NavBar Code *********************************************-->
<div class="nav">
<ul>
<li>Home</li>
<li>Features</li>
<li>About</li>
</ul>
</div>
<!--***************************************************-->
<p>
Welcome to the Elex 267 Demo Web Server for [Name Here].<br>
</p>
<p>
This web page is being run on the NM101 NorthMicro Pic Prototype Board with the LCD/Keypad and Network modules.
<br>
This web page refreshes the data every 3 seconds.
</p>
<center>
<img border="5" src="http://www.northmicro.com/GFX/nm110nm120onproto.jpg" alt="NM110 Proto Pic" width="200" height="200" >
</center>
<br>
<div id="feedback" style="width:500px;float:left;">
Pot RA0: 1022 <br>
Pot RA1: 223
<br><br>
Switch RA2: <img src="Pics/SwitchUp.gif" alt="SwitchOff" width="20" height="20" align="top">
<br><br>
LEDs: RB6 <img src="Pics/LEDOff.gif" alt="LED_Off" width="20" height="20" align="top"> RB5 <img src="Pics/LEDOn.gif" alt="LED_On" width="20" height="20" align="top">
</div>
<div id="input" style="width=50%;margin-left:50%;">
<b>Commands</b><br>
<button align="left" type="button" onclick="alert ('RB5 Activated')">Toggle RB5</button>
<br>
<button align="left" type="button" onclick="alert ('RB6 Activated')">Toggle RB6</button>
</div>
<br><br>
<div id='T0'>Loading Temp0...</div>
</body>
</html>
setInterval("getTemp()", 1000);
does not make sense at this line, and it might be the cause of your problems. This call causes getTemp to be called every second, starting from after this call as returned. In the getTemp function you are reusing the xhr variable, creating a new XMLHttpRequest instance each time. That alone is not necessarily a problem (aside from the "Msxm12.XMLHTTP" which appears to be wrong; should probably be "Msxml2.XMLHTTP").
But in each call of getTemp you are issuing a new request, regardless if the previous request has received a response (the third argument being true means asynchronous request-response handling). Consider this: The readystatechange listener might not have been called (or its readyState == 4 part has not be executed) because the client is waiting for the server to respond. Now your one-second timer kicks in, calls getTemp again and thus overwrites the xhr value that is to be used in the listener code. There is a closure, xhr is a bound variable, and therefore there is a race condition already.
Further, an HTTP client SHOULD NOT (per RFC 2616), and a well-designed Web browser will not, keep more than a specified number of persistent HTTP connections (default: 2 to 8) open to the same server or proxy. So the more complex the document, and the more resources need to be loaded in parallel, the more likely that this approach will fail.
You should remove the setInterval(…) call and add a getTemp() call below the line where you update the innerHTML property (when the request was successful, status == 200), so that only then a new request is issued. You should at least wait for the readyState to become 4 (FINISHED) before you issue a new request. Since you want to wait one second before the next call, use window.setTimeout("getTemp()", 1000).
It should help your understanding if you pretty-print that code, that is, indent function body and block content with a reasonable amount of white-space, and add some white-space, for example between ) and {. There are editors like Eclipse JavaScript Development Tools which can automate much of the code formatting.
Afterwards you should learn to use a debugger (use Firebug for Firefox, newer versions of other browsers have one built-in) and set breakpoints in your code, particulary in getTemp and parseHttpResponse. Step through the code (caveat: step over send(), then continue so that execution halts at the breakpoint in parseHttpResponse) to see what is going on. Good luck.
Hi all i am writing a Rails application and i include some link_to_remote links
The generated code is
Test
That works perfectly fine on Safari and Firefox but when i try to click the link on IE7 and Opera it does not even hit the server.
Any hints ?
Use a fully qualified URL: http://.....
This is a bad practice to include all of this code in the <a href> tag anyways. I suggest you make a function such as:
function doAjax(url)
{
new Ajax.Request(url, {asynchronous:true, evalScripts:true});
return false;
}
in the javascript code. And change the url to say instead:
<a href="#" onclick="return doAjax('/b10/categories/games?category=Action');">
Test</a>