Readability API - javascript

I want to use readability parser API but when I am making call to this API I am getting blank/no response.
When I tried with some other url the same code is giving proper response.
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8;">
<head>
<script language="javascript">
var getJSON = function(url, successHandler, errorHandler) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
alert("-------" + url);
//xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
alert("===========" + status);
if (status == 200) {
successHandler && successHandler(xhr.response);
} else {
errorHandler && errorHandler(status);
}
};
xhr.send();
};
function getReading() {
var url1 = "https://www.readability.com/api/content/v1/parser?url=";
var testurl = "http://www.saptechnical.com/Tutorials/WebDynproABAP/ALV/page1.htm";
var urltoken = "&token=tokenkeyhere";
var finalurl = url1 + testurl + urltoken;
alert(finalurl);
getJSON(finalurl, function(data) {
alert(data.domain);
});
}
</script>
</head>
<body>
<input type="button" value="go" onClick="getReading()" />
</html>

I got answer and code is working now..
I used getJSON method to make a call to API.
function getInfo() {
var url = $("#txtSubmitlink").val();
$.getJSON("https://www.readability.com/api/content/v1/parser?url="+ url +"&token=tokenkeyhere&callback=?",
function (data) {
$("#dvContent").html(data.content);
$("#imgLeadImage").attr('src', data.lead_image_url);
});
}
Thanks everyone-

Related

How i call controller function from below javascript code in view page(Codeigniter)

This is the javascript code that which used in core PHP for saving data entered in google map.
I want to pass the values in the variable 'url' to controller function in Codeigniter. what should i do?
function saveData() {
var name = escape(document.getElementById('name').value);
var address = escape(document.getElementById('address').value);
var type = document.getElementById('type').value;
var latlng = marker.getPosition();
var url = 'phpsqlinfo_addrow.php?name=' + name + '&address=' + address +
'&type=' + type + '&lat=' + latlng.lat() + '&lng=' + latlng.lng();
downloadUrl(url, function(data, responseCode) {
if (responseCode == 200 && data.length <= 1) {
infowindow.close();
messagewindow.open(map, marker);
}
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing () {
}
To fetch the parameters from a GET request use the CI library input. Documentation HERE.
Here's a simplified version for demonstration purposes starting with the view file viewMap.php
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button value="test" id='mapsave'>Click Me</button>
<div id="response"></div>
<script>
var el = document.getElementById("mapsave");
el.addEventListener("click", saveData, false);
function saveData() {
var res = document.getElementById("response");
var request = new XMLHttpRequest();
var name, url;
name = "Stevin";
url = "<?= base_url('maps/insert_church_details?name='); ?>" + name;
request.onreadystatechange = function () {
if (request.readyState == 4) {
res.innerHTML = request.responseText;
}
};
request.open('GET', url, true);
request.send();
}
</script>
</body>
</html>
Here is the controller. I've renamed it simply Maps instead of mapController because it simplifies URLs. Who want's to go http://example.com/mapController ? Also, mapController violates CodeIgniter class naming conventions. (Better explained HERE)
class Maps extends CI_Controller
{
public function index()
{
$this->load->view('viewMap');
}
public function insert_church_details()
{
echo $this->input->get('name');
//exit; <- Bad idea for CodeIgniter
}
}
In this example we only have the one item in the query string and we use input->get('name') to fetch it. The parameter passed to get() is the name of item. If we have several items we can fetch them one at a time or use get() without a parameter and capture all the items in an array. (See the docs if that doesn't make sense.)
Calling exit or die in CodeIgniter is a bad habit - not recommended. We're not doing procedural programming here. Using them will short-circuit the framework's normal execution path and, in this case, bypass several "hook" points that might be defined. Let functions return and have CI follow its normal execution path.
It's important to know that the call to base_url() only works because the JavaScript is included inline. If you load the js from an external file (e.g. <script src="assets/js/maps.js"></script>) it will not evaluate correctly.
You'll have to find another way to create a full URL, or use a relative URL.
Here's how to use an external js file, send and fetch a couple of parameters, use a relative URL, and respond with and utilize json.
The view
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button value="test" id='mapsave'>Click Me</button>
<div id="response"></div>
<script src="assets/js/maps.js"></script>
</body>
</html>
The Controller
class Maps extends CI_Controller
{
public function index()
{
$this->load->view('viewMap');
}
public function insert_church_details()
{
$name = $this->input->get('name');
$addr = $this->input->get('address');
echo json_encode(['name' => $name, 'addr' => $addr]);
}
}
The javascript
var el = document.getElementById("mapsave");
el.addEventListener("click", saveData, false);
function saveData() {
var res = document.getElementById("response");
var request = new XMLHttpRequest();
var name, url, address;
name = "Stevin";
address = 'Home';
url = '/maps/insert_church_details?name=' + name + '&address=' + address;
request.onreadystatechange = function () {
var out;
if (request.readyState == 4) {
out = JSON.parse(request.responseText);
res.innerHTML = out.name + ", " + out.addr;
}
};
request.open('GET', url, true);
request.send();
}
Just try use and replace {controllerName} into your controller name and replace {functionName} into controller method name:
var url = '<?php echo base_url(); ?>{controllerName}/{functionName}?name=' + name + '&address=' + address +
'&type=' + type + '&lat=' + latlng.lat() + '&lng=' + latlng.lng();

I get the Error code 401 when I run this script, what can I do?

I am a newbie in programming.
I have a sensor that is connected to the app via bluethooth. The app sends the data to the cloud service. I got a link from the cloud service that contains the data in a json format. Now I want this data to be displayed on my Website, but its cross domain and whatever I do it says 401 (Unauthorized).
<html>
<head>
<title>Sensor</title>
<script src="jquery-3.2.1.min.js"></script>
</head>
<body>
<h1>Sensor</h1>
<button onclick="myFunctionPost()">Start</button>
<div id="result" style="color:red"></div>
<script>
function myFunctionPost() {
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
}; getJSON('https://thetablewheremydatais$format=json').then(function(data) {
alert('Your Json result is: ' + data.result); //you can comment this, i used it to debug
result.innerText = data.result; //display the result in an HTML element
}, function(status) { //error detection....
alert('Something went wrong.');
});
}
</script>
</body>
</html>
Have you tried this line of code before you call the server with xhr.send()
xhr.withCredentials = true;

Uncaught ReferenceError: make_basic_auth is not defined

Like the title says: "Uncaught ReferenceError: make_basic_auth is not defined"
I have a sensor that is connected to the app via bluethooth. The app sends the data to the cloud service. I got a link from the cloud service that contains the data in a json format and I have to GET the data from it.
make_basic_auth is a function to authentificate my GET request.
Im new and I dont have a clue what I did wrong.
<html>
<head>
<title>Test</title>
<script src="jquery-3.2.1.min.js"></script>
<script src="Base64Toolkit.js"></script>
</head>
<body>
<button onclick="myFunctionPost()">Post</button>
<div id="result" style="color:red"></div>
<script>
function make_base_auth(user, password) {
var tok = user + ':' + pass;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
var auth = make_basic_auth('myUSERNAME','myPASSWORD');
var url = 'myURL';
// RAW
xml = new XMLHttpRequest();
xml.setRequestHeader('Authorization', auth);
xml.open('GET',url)
// ExtJS
Ext.Ajax.request({
url : url,
method : 'GET',
headers : { Authorization : auth }
});
// jQuery
$.ajax({
url : url,
method : 'GET',
beforeSend : function(req) {
req.setRequestHeader('Authorization', auth);
}
});
function myFunctionPost() {
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.withCredentials = true;
xhr.send();
});
};
getJSON('myURL').then(function(data) {
alert('Your Json result is: ' + data.result); //you can comment this, i used it to debug
result.innerText = data.result; //display the result in an HTML element
}, function(status) { //error detection....
alert('Something went wrong.');
});
}
</script>
</body>
</html>
Typo:
make_base_auth <- defined
make_basic_auth <- used

How to get HTML source with JavaScript?

I am trying to get HTML source with JavaScript:
Why this does not work?:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function MyGetHTML()
{
$.get("www.example.com/test1.html", function(data){
return data;
});
}
</script>
</head>
<body>
test 30.9.2015
<script>
alert(MyGetHTML());
</script>
</body>
</html>
(Below, i'm assuming that you need to get content from filen IN your source, from the same origin of your page.)
Your code doen't works because the the return of your MyGetHTML method is the get request itself, and the success callback of your request returns the data.
You could do:
function MyGetHTML(){
$.get("www.example.com/test1.html", function(data){
//alert(data);
//or use console.log() instead.
console.log(data);
});
}
And then
MyGetHTML(); //This will log your data after the succesfull request.
Further reading: https://api.jquery.com/jquery.get/
Hint on your use case:
A simple tutorial from Tuts+ on making simple ajax requests.
With pure JS:
load('test.html', function(xhr) {
document.getElementById('container').innerHTML = xhr.responseText;
});
function load(url, callback) {
var xhr;
if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
else {
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"]
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
xhr.onreadystatechange = ensureReadiness;
function ensureReadiness() {
if(xhr.readyState < 4) {
return;
}
if(xhr.status !== 200) {
return;
}
// all is well
if(xhr.readyState === 4) {
callback(xhr);
}
}
xhr.open('GET', url, true);
xhr.send('');
}
Or with jquery library
$('#container').load('test.html');
Because you're returning to the get not the function itself. Try like this:
function MyGetHTML()
{
var datum = '';
$.get("www.example.com/test1.html", function(data){
datum = data;
});
return datum;
}

JavaScript + Querystring + div

How to load content in to a html page. please note IM not allowed to use php or C. Only javascript and html.
for example
load Page B in to Page A
http:myweb.com/index.html?load=pageb
thank you.
Issue an AJAX request to Page B
Get the contents using responseText
Display the contents inside a div using innerHTML property.
If you can use a js framework then I would suggest jQuery and #marcgg's answer will do it.
Just plain JavaScript:
<html>
<head>
<script>
function getUrlVars() {
var map = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
map[key] = value;
});
return map;
}
function createRequestObject() {
var ro;
// Mozilla, Safari,...
if (window.XMLHttpRequest) {
ro = new XMLHttpRequest();
if (ro.overrideMimeType) {
ro.overrideMimeType('text/xml');
// See note below about this line
}
// IE
} else if (window.ActiveXObject) {
try {
ro = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ro = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!ro) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
return ro;
}
function sndReq(param,server,handler) {
//location.href = server+"?"+action; //uncomment if you need for debugging
http = createRequestObject();
http.open('GET', server, true);
http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
http.onreadystatechange = handler;
http.send(param);
}
handler_function = function()
{
if(http.readyState == 4)
{
if (http.status == 200)
{
document.getElementById("your_div_element").innerHTML = http.responseText;
}
else
{
alert('There was a problem with the request.');
}
}
}
</script>
</head>
<body>
<div id="your_div_element"></div>
<script>
var getvars= getUrlVars();
sndReq(null, getvars['action'], handler_function);</script>
</body>
</html>
html:
//Page A
<html>
<head><title>Page A</title></head>
<body>
<div id="pageB"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#pageB').load('pageb.html')
});
</script>
</body>
</html>
Using jQuery:
$.ajax({
type: "POST",
url: "http://some.com/page.html",
success: function(msg){
alert( "here's your data: " + msg );
jQuery("#yourDivID").html(msg);
}
});
http://docs.jquery.com/Ajax/jQuery.ajax
edit: added how to put it into a div

Categories