Import PHP file content to Javascript variable - javascript

I'm trying to retrieve the online status of users from a chat client called IMVU(the regular little image holder by the profile pictures isn't enough, I'm making something bigger, so I need some signal), and the way to do that is use this line of the user ID 1111111 for example:
http://avatars.imvu.com/catalog/web_status_updater.php?ol=1&list=1111111
It returns a php file containing a line of JSON. I need that whole line of text put into a javascript variable so I can use it.
I need to use this in a script I'm making, but I can't seem to get it to work. I've tried lots of things, the closest seems to be this one:
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
readTextFile("http://avatars.imvu.com/catalog/web_status_updater.php?ol=1&list=1111111");
(I'll change the alert(allText); to return allText; or return rawFile.responseText; when I get this experiment to work first and make sure that the text is actually stored and displayed.)
What happens is that the alert shows up blank. Just a white box, that's all. My prior attempts had the box show up and it said "undefined", but now it's doing something I guess? Why is it blank though? And how do I fix it?
EDIT:
It works in IE but not Firefox apparently.

I believe the problem here is the Same Origin Policy. You are attempting to make a request to a domain that is different than the one that originated the request.
Some websites specify headers which allow this, but the headers returned here are missing the Access-Control-Allow-Origin header.
One way around this is to use JSON-P on servers that support it.
Try this:
jQuery.ajax({
url:"http://avatars.imvu.com/catalog/web_status_updater.php?ol=1&list=1111111",
dataType:"jsonp"
})
.done(function(data) {
console.log(data)
});

Related

JS style-changes don't get applied when inside request

I want to make it such that an image on a website gets its "onclick" event disabled and a gray filter applied, if a certain file on the same domain is not found. I want to use purely JS and have tried this so far:
function fileNonExist(url, callback){
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
if (http.readyState === XMLHttpRequest.DONE && callback) {
if(http.status != 200){
callback();
}
}
}
http.open('HEAD', url);
http.send();
}
fileNonExist("theFileIAmLookingFor.html", () => {
console.log("image changed");
image.onclick = "";
image.style.filter = "grayscale(100%)";
});
I have the image initialized and displayed. Thus image.onclick = "" and image.style.filter = "grayscale(100%)
both work, if they are used normally. However, even though the function blocks are executed as intended (Console logs "image changed" if the file isnt found, and nothing otherwise.) none of the style changes are ever visible, if they are executed from within those blocks. Why might that be and how could I fix it?
I found out the solution myself, while talking to Emiel Zuurbier: I noticed that the code works if I open the html file normally in my browser. The bug occurs, if I access the file over a webserver, which i've done the whole time. If I shut down the server while the site is still opened in the browser, then the changes also get applied. If I look at the requests with dev tools in the browser. I see that only the successfull requests are finishing and the unsuccessfull ones are left pending forever. Thats why the changes get applied when the server is shut down and all pending requests get closed with errors. The Server uses the Node.js "fs" module and its readFile method.
I will now try to turn the styles around so all images start off gray and without "onclick" - methods and only become unlocked once the file is found. This way the images with pending requests remain gray.

Checking for file existence in a local domain

I am pulling my hair out trying to figure this out since there are numerous examples of how to do this and none seem to work for me the way they are suppose to. I want to check for the existence of a local file. I have placed a file in the same directory as the html code and it is accessible and readable. This is NOT a URL or permission problem. Here is one example of code I am trying to use. checkURL() is called with the URL in the global variable linkURL.
function doesFileExist(urlToFile)
{
var xhr = new XMLHttpRequest();
xhr.open('HEAD', urlToFile, false);
xhr.send();
if (xhr.status != "200") {
return false;
} else {
return true;
}
}
function checkURL()
{
var result = doesFileExist(linkURL);
if (result == true) {
alert("Exists");
// Page would be loaded here with window.location.href = linkURL;
} else {
alert("NOT Exists");
}
}
The problem is this will always return true but never returns false and never alerts "NOT exist" Somehow it just bypasses that alert code. I have tried many variations of this and in all cases when the URL does not exist the test fails to display anything but always works when it exists. My goal here is to access multiple local URL's and display those that exist but if one does not exist I want to be able to display a message to that effect to the user and not actually access the URL and get a page error. The files and HTML code will ultimately be on a DVD and accessed by a browser.

My attempt at reading a text file with Javascript is failing

I have the following function executing on page load:
function get_words()
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "file:///C:\Users\myMachineName\Documents\PersonalSite_Improved\wordsEn.txt", true);
rawFile.onreadystatechange = function ()
{
if (rawFile.readyState === 4)
{
if (rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
rawFile.send(null);
}
}
It is my own use of the procedure from this S.O. thread: Javascript - read local text file
I'll confess that I don't totally understand the procedure. However, I can obviously see that I would be getting an alert of the text file contents if the page was working properly. I ran some tests using console.log() to determine that the first if statement is never entered. But since I have no idea what's going on here, I have no idea how to troubleshoot the issue.
Any help?
The document you are trying to read must be served by an HTTP server, you can't pull up local files from your hard drive or machine. The reason for this is simply security, for if JavaScript could read files on local machines, everyone would be able to open, view and read everything on people's computers. Just run a local HTTP server such as WampServer or something of that nature.
You cannot use an xml request to read a local file due to security reasons.
See this answer for more info.

XML accessible from URL line but not from script

When I type a certain URL in FF, I get the XML returned displayed on the screen, so the web service is apparently working. However, when I try to access it from a local HTML document running JS, I get unexpected behavior. The returned code is "200 OK" but there's no text (or rather it's an empty string) nor xml (it's null) in the response sections according to FireBug.
This is how I make the call.
var httpObject = new XMLHttpRequest();
httpObject.open("GET", targetUrl, true);
httpObject.onreadystatechange = function () {
if (httpObject.readyState == 4) {
var responseText = httpObject.responseText;
var responseXml = httpObject.responseXML;
}
}
httpObject.send(null);
Why does it happen and how do I tackle it?
That may be an HTTP header problem (e.g. missing Accept header); observe the headers sent by FF (you can use Firebug for that) and try to replicate them in your script (setRequestHeader).
Otherwise, that may be a "same origin policy" problem.

Replace current page with ajax content

I have a page with a dialog window which sends ajax post data to server and receives a response. During development, there can be two responses - one regular (this is not the question) or one with an error. Server returns code 500 and a page with lot of debug informations. This is a regular page returned from a framework and contains some javascript code. I want to be able to display this error page in case it happens.
The problem is, I can not simply attach the returned result to body element or open a new link in a new page and load this error again. I simply get a html page instead of data and I have to display the page (in current window or in another one).
I am using jQuery.
Configure jQuery ajax setup as follows:
$.ajaxSetup({
error: handleXhrError
});
where handleXhrError function look like this:
function handleXhrError(xhr) {
document.open();
document.write(xhr.responseText);
document.close();
}
See also:
Handling of server-side HTTP 4nn/5nn errors in jQuery
You may also try to use data URL's, the latest versions of the major browsers supporting it:
function utf8_to_b64( str ) {
return window.btoa(unescape(encodeURIComponent( str )));
}
function loadHtml(html)
{
localtion.href='data:text/html;base64,'+utf8_to_b64(html);
}
This way, you can load any html page you want in runtime.
In your ajax callback:
success: function (data) {
$("html").html($(data).find("html").html());
}
That will replace the entire page's HTML content with the one received from your AJAX request. Works in Chrome... not sure about IE.
Despite that, I'm not sure why you'd want to include the <head> section... but you can easily modify the above to display just what's in the body of the AJAX response, and append it to a div or even a lightbox. Much nicer.
Here is an example of how to change either if the response is a url or a html content (using django\php)
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
var replace_t = '{{ params.replace_t }}';
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if(replace_t == 'location')
window.location.replace(xmlhttp.responseText);
else if(replace_t == 'content')
{
document.open();
document.write(xmlhttp.responseText);
document.close();
}
}
}
xmlhttp.open("GET",SOME_ASYNC_HANDLER_URL,true);
xmlhttp.send();
I found this solution. I don't know if it si correct, but for Opera and Firefox it is working.
var error_win = window.open(
'',
'Server error',
'status=0,scrollbars=1, location=0'
);
error_win.document.write(XMLHttpRequest.responseText);
Have you tried just simply creating an element and inserting the returned error page into the element? I do this with error pages and jQuery.
var errorContainer = $( '<div/>' );
errorContainer.html( errorTextResponse );
errorContainer.appendTo( $( 'body' ) );
I may be misunderstanding, but do you know what elements from the result you specifically want to display? You could trying something like this:
success: function(data){
//store the response
var $response=$(data);
//use .find() to locate the div or whatever else you need
var errorMessage = $response.find('#warning').text();
alert(errorMessage);
}
Is that what you were looking for?
I don't think there's any way to do that. Iframes are meant for loading other pages and there's no other sandbox in which to dump a standalone page -- that's what frames were designed for.
It might be difficult with the framework you're using, but it's probably worthwhile to have it generate different errors for your Ajax requests. My Ajax pages will only ever send
{"exit": 1, "message": "As in the shell, a non-zero exit is an error and this is why..."}
Just figured this out
as easy as
document.body.innerHTML = YourAjaxrequest.responseText;
_______________________________________________^ up here is what over writes your current HTML page with the response.
request.onreadystatechange = function() {
if (request.readyState == 1) {
document.getElementById('sus').innerHTML = "SENDING.......";
}
if (request.readyState == 3){
document.getElementById('sus').innerHTML = "SENDING >>>>>>>>>>>>>";
}
if (request.readyState == 4 && request.status == 200) {
//document.getElementById('sus').innerHTML = request.responseText;
document.body.innerHTML = request.responseText;
}
}
request.send(formD);
},false);

Categories

Resources