PHP + JSON Not Working Correctly - javascript

I just started using JSON and found this example from http://imdbapi.com/:
<script type="text/javascript">
// IMDb ID to Search
var imdbLink = "tt1285016";
// Send Request
var http = new ActiveXObject("Microsoft.XMLHTTP");
http.open("GET", "http://www.imdbapi.com/?i=" + imdbLink, false);
http.send(null);
// Response to JSON
var imdbData = http.responseText;
var imdbJSON = eval("(" + imdbData + ")");
// Returns Movie Title
alert(imdbJSON.Title);
</script>
But it just returns a blank page. What is wrong?

I'm sorry not to directly answer your question, but here is a jQuery version:
var imdbLink = "tt1285016";
// Send Request
$.getJSON("http://www.imdbapi.com/?i=" + imdbLink + "&callback=?", function(data) {
alert(JSON.stringify(data));
});
There are a couple possible issues with your code.
1.) ActiveX is IE only, not firefox, chrome, safari, etc.
2.) You have a cross-domain issue.
Example Fiddle

Related

How to turn responseText into image from sharepoint?

I'm trying to use XMLHttpRequest to get image from a sharepoint library. But failed at the point of converting a weird string like
����JFIFS���E������..
back to image.
I managed to get a URL of my sharepoint files that when i put it in the browser, it will automatically download the image. I have also obtained the accessToken to gain permission to the files.
I tried to use base64 encoder from external script to convert the responseText and failed to display as image. Btw, the window.atob() or window.btoa() doesn't seems to do anything for my responseText.
I am not sure what kind of format i received from the responseText to be dealt with. Because i tried manually converting the image to base64 for testing, which begin like this
/9j/4AAQSkZJRgABAQAAAQABAAD/2wB..
. However, the string i got from using the the base64encoder i found online start like this
/f39/QAQSkZJRgABAQAAAQABAAD9/QBDAAs..
<div><img id="imgplaceholder" alt="place here"/></div>
<script>
var url =...;
var accessToken = ...;
var xhr = new XMLHttpRequest();
xhr.open("GET",url,true);
xhr.setRequestHeader("Accept","application/json; odata=verbose");
xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var data = xhr.responseText;
//or var data = base64Encode(data);
document.getElementById("imgplaceholder").src = "data:image/jpeg;base64," + data;
}else{
alert(xhr.status + ":\n " + xhr.responseText);
}
}
</script>
I expect the image to be displayed in the , but nothing happens. I have tried using ajax too, but noting works. Please can someone help me?
I was following this https://sharepoint.stackexchange.com/questions/231251/fetch-and-display-image-from-sharepoint-list-javascript
Hope below script would be helpful for you.
<script type="text/javascript">
function Uint8ToBase64(u8Arr) {
var CHUNK_SIZE = 0x8000; //arbitrary number
var index = 0;
var length = u8Arr.length;
var result = '';
var slice;
while (index < length) {
slice = u8Arr.subarray(index, Math.min(index + CHUNK_SIZE, length));
result += String.fromCharCode.apply(null, slice);
index += CHUNK_SIZE;
}
return btoa(result);
}
$(function () {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFileByServerRelativeUrl('" + _spPageContextInfo.siteServerRelativeUrl + "/MyDoc/panda.jpg')/openbinarystream";
var xhr = new window.XMLHttpRequest();
xhr.open("GET", url, true);
//Now set response type
xhr.responseType = 'arraybuffer';
xhr.addEventListener('load', function () {
if (xhr.status === 200) {
var sampleBytes = new Uint8Array(xhr.response);
var imageBase64 = Uint8ToBase64(sampleBytes);
document.getElementById("imgplaceholder").src = "data:image/jpeg;base64," + imageBase64;
}
})
xhr.send();
})
</script>
<div><img id="imgplaceholder" alt="place here" /></div>

xhr does not get invoked from js

i am using phonegap and trying to invoke a xhr POST on click of a button.
my flow goes to the method call but doesn't invoke the xhr code and i am failing to understand why.
The call looks like:
function fetchTags(){
console.log("Fetched url is:" + IMAGE_URL);
//var url = "http://localhost:8080/echo";
var url ="http://localhost:8080/echo";
console.log("#1");
var xhr = new XMLHttpRequest();
console.log("#2");
xhr.addEventListener("error", onError);function onError(evt) { console.log("An error occurred while transferring the file."); }
console.log("#3");
xhr.setRequestHeader("Content-type", "application/json");
console.log("#4");
xhr.open('POST', url, true);
console.log("#5");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
window.alert(response);
}else{
window.alert(xhr.status);
}
};
console.log("#5");
//var msg = "{'message' : '" + IMAGE_URL + "'}";
console.log("sending request");
xhr.send(JSON.stringify({"message" : "my msg"}));
}
Button code:
<button class="button button-raised larger" type="button" onclick="fetchTags()">Vision</button>
The console prints:
Fetched url is:undefined
#1
#2
#3
To clarify i can see first console.log getting printed. but that's it. nothing happens after that.
just for everyone's benefit the issue was not the javascript but invoking from the phonegap using the localhost.
I was unders the assumption that phonegap will be able to access my api at localhost (not sure why had this stupid idea) but yes using the actual ip of the host machine made it work right away.

Render HTML returned through AJAX call in JavaScript

I am a complete novice in the JavaScript and AJAX stuff. I am trying to make a call to the server using AJAX and display the returned HTML. However instead of rendering the HTML, the browser displays the HTML code. I am not using JQuery and I would prefer not using it (an acute shortage of time and my complete unfamiliarity with JQuery are two major reasons for sticking to basic JavaScript). Is there some way to render the HTML as it is supposed to be using just the basic JavaScript. Here is my code
function gotoNext(button){
try {
xmlHttp = new XMLHttpRequest ();
}
catch (e) {
try {
xmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
}
catch (el) {
try {
xmlHttp = new ActiveXObject ("Msxml2.XMLHTTP");
}
catch (el1) {
alert ("Your browser does not support AJAX! Please use a compatible browser!!");
}
}
}
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var df = document.getElementById ("dataForm");
var data = xmlHttp.responseText;
df.innerText = data;
}
};
var id = document.editEnv.id.value;
var sId = document.editEnv.sId.value;
var fileName = document.editEnv.fileName.value;
var group = document.editEnv.group.value;
xmlHttp.open("POST", "newData.jsp", true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
xmlHttp.send ("flag=" + flag + "&id=" + id + "&sId=" + sId + "&fileName=" + fileName + "&group=" + group);
You should use df.innerHTML = data;
innerText just gets/sets the value as plain text.
You can try to replace innerText with innerHTML The difference lies in the fact that innerText doesn't include any HTML tags whereas innerHTML does. For example
Here is a link
will display:
Here is a link
if you call innerText on it. However, if you call it with innerHTML it will display:
Here is a link
df.innerHTML = data;
should work!!
Because using innerHTML will render that html on browser.
innerText will just display HTML code as normal text.

Change 'Download URL' to 'Search URL' XML Data

I wonder whether someone can help me please.
I've put together this page, which will give the user functionality to load markers with the selection or deselection of checkboxes. They will then be able to click on these markers which in turn shows the nearest POI within a given radius.
The problem I'm having is with loading the xml at lines 143-145 which are:
downloadUrl("loadmylocations.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker")
Firefox tells me that the error is that the 'xml is undefined'. I think I know why and that's because I'm using this code to pull data for the POI's.
var radius = document.getElementById('radiusSelect').value;
var searchUrl = 'searchsites.php?siteosgb36lat=' + center.lat() + '&siteosgb36lon=' + center.lng() + '&radius=' + radius;
downloadUrl(searchUrl, function(data) {
var xml = parseXml(data);
So they clash, because I define the XML at the end of the script differently, these being
loadmylocations.php
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
searchsites.php
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
function doNothing() {}
Could someone perhaps tell me please how I can change so that I can pull the two sets of data wihtin the same script without them clashing.
Many thanks and kind regards
I did some work around this, and through trial and error I discovered that I could load the information for the 'loadmylocations' script as the 'searchsites' script i.e. var xml = parseXml(data); rather than var xml = data.responseXML;.

Getting a file from a server using Javascript

So, I wrote some JavaScript to grab an xml file from my desktop and display it on an html page. However, I now have added my xml file to a webserver (mongoose). I want to call the file from that server, but whenever I call the file from the server it dosen't work, but when I call it from my desktop it loads fine.
I want to swap
xmlhttp.open("GET","Devices.xml",false);
with
xmlhttp.open("GET","http://localhost:8080/Devices.xml",false);
Here is the code
<html>
<head>
<script type="text/javascript">
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","Devices.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
// the <Device> list
x = xmlDoc.getElementsByTagName('Device');
// make a function that extracts the attributes out of a Node
function getDeviceAttributes(dvc) {
var name = dvc.getAttribute("name");
var uuid = dvc.getAttribute("uuid");
var id = dvc.getAttribute("id");
return "<p>name: " + name + "<br> uuid: " + uuid + "<br> id: "+ id + "</p>";
}
// loop through the list
// assuming order doesn’t matter
var txt = '';
for (var i = x.length; i--;) {
txt += getDeviceAttributes(x[i]);
}
//show the result on page load
window.onload = function() {
document.getElementById("showDevices").innerHTML = txt;
};
</script>
</head>
<body>
<div id='showDevices'></div>
</body>
</html>
Does anyone know how I can get this to work?
I have been told to use AJAX and Jquery, but I have no idea how to or even where to begin.
It looks like you are repeating a lot of work that jQuery can do for you. Check out the documentation for the Get request method
So something like this:
$.get('http://localhost:8080/Devices.xml', function(data) {
$('#showDevices').html(data);
});
I believe that is the jQuery for what you are trying to do. Hope that helps.
-Charlie
Just some generic advice, you could also use the .load() ajax function if you didn't want to parse the response and this:
window.onload = function() {
document.getElementById("showDevices").innerHTML = txt;
};
can be done in jQuery like this $("#showDevices").html(txt);

Categories

Resources