get content from external url using javascript - javascript

I am using freetexthost.com to store my json code..
and now i ve to get those content from url using javascript,jquery,ajax...
bt am being unable to get it..
am trying following code
<!DOCTYPE html>
<html>
<head>
<title>Useless</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.11.0.min.js'></script>
<script type="text/javascript">
$.ajax({
type: "GET",
url: "http://freetexthost.com/r56ct5aw03",
dataType: "jsonp",
success: function(data){
console.log(data);
}
});
</script>
</head>
<body>
<div class="content" >Hello</div>
</body>
</html>
getting an error as `Uncaught SyntaxError: Unexpected token <
is there any chances we can manipulate content of other page(url) using js...

in your json file create function:
//----for example
parseResponse({"Name": "Foo", "Id": 1234, "Rank": 7});
then call this function by JSONP
var result = $.getScript("http://freetexthost.com/r56ct5aw03?callback=parseResponse");
I hope to help you.
reference : JSONP

You need to close your url using ":
$.ajax({
type: "GET",
url: "https://http://freetexthost.com/r56ct5aw03", // <-- Here
dataType: "jsonp",
success: function(data){
console.log(data);
}
});

The content of the page http://freetexthost.com/r56ct5aw03 is html, it should be jsonp to parse properly
The only difference between json and jsonp is that when calling jsonp you will also pass a callback parameter
e.g. url:"http://freetexthost.com/r56ct5aw03?callback=myFunction",
Now the server side should print the json enclosed in this function name like below.
myFunction(
{
"sites":
[
{
"siteName": "123",
"domainName": "http://www.123.com",
"description": "123"
},
{
"siteName": "asd",
"domainName": "http://www.asd.com",
"description": "asd"
},
{
"siteName": "zxc",
"domainName": "http://www.zxc.com",
"description": "zxc"
}
]
}
);

Related

Load data from local JSON file into javascript

[added:] Thank you guys for the reply. I understand that ajax has to used on a server. I wonder if there is a way to load the data from local json file into js in this example?
I have a file named employee.json. I tried load this JSON data into JavaScript. I saved both the .json and .html files on my desktop but when I click in the HTML, there is nothing shown. I tried to use alert() in the .ajax() method but it does not work. I am not sure what is wrong with my AJAX method. What do I need to do to take the id from the JSON and put it into an array in javaScript? Thank you in advance.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var res = [];
$.ajax({
url: 'employee.json',
dataType: 'json',
method: 'get',
cache: false,
success: function(data) {
$(data.employee).each(function(index, value) {
res.push(value.id);
});
document.getElementById("demo").innerHTML = res.toString();
}
});
</script>
</body>
</html>
{
"employee": [{
"id" : 1,
"firstName" : "Lokesh"
},{
"id" : 2,
"firstName" : "bryant"
},{
"id" : 3,
"firstName" : "kobe"
}]
}
As an alternative you can load your JSON as a javascript, just wrap all your JSON data into
var employees = { /*all your json data here*/ }
and save this as employees.js
Then you can just use a regular script tag in the html:
<script src="/yourpath/employees.js"/>
And then inside your javascript "employees" will be a global object.
so you will have:
employess.employee[1].FirstName
result in "bryant" in your case;

JSONP callback is returning error

I'm trying to learn JSONP. From my research online, I understood that it's invoke function with callback.Apart from that everything else (the way data is handled/data format) similar to JSON?
I'm just playing with JSONP as below. But It's returning error, please explain in detail about it, please..
Script.js
function test(){
jQuery.ajax({
url: "/plugins/system/chat/jsonstr.php",
dataType: "jsonp",
jsonpCallback: "logResults"
});
jsonstr.php
logResults(){
$arr = '[{
"title": "keren",
"picture": "http://something.png",
"id":1
}, {
"title": "diana",
"picture": "/plugins/system/conversekit/conversekit/images/avatar.png",
"id": 2
}]';
echo $arr;
}
I expect this call to return json object so that I can manipulate it in success function of test. But error as below is thrown:
<br />
<b>Parse error</b>: syntax error, unexpected '{' in <b>C:\projects\easysocial.com\plugins\system\conversekit
\jsonstr.php</b> on line <b>14</b><br />
The url in console is as this:
GET http://mysite.localhost.com/plugins/system/chat/jsonstr.php?callback=logResults
logResults() is JavaScript callback, not PHP function. jsonstr.php should only return valid JSON.
So jsonstr.php should look like this
<?php
$arr = [
[
'title' => "keren",
'picture' => "http://something.png",
'id' => 1,
],
[
'title' => "diana",
'picture' => "/plugins/system/conversekit/conversekit/images/avatar.png",
'id' => 2,
],
];
echo(json_encode($arr));
And Script.js
function logResults() {
console.log('ajax done');
}
function test(){
jQuery.ajax({
url: "/plugins/system/chat/jsonstr.php",
dataType: "jsonp",
jsonpCallback: logResults
});
}
Two issues:
Your server-side script doesn't return anything, as the Net pane in your browser developer tools should reveal.
JSONP is just a dirty trick to avoid cross-site permission issues in AJAX, not a way to make PHP code interact with JavaScript (something that is not possible). So when you say "I want a callback function called logResults" you mean a JavaScript function.
If you want to use JSONP you need:
Make your server actually return JSONP (not even JSON):
$callback = filter_INPUT(INPUT_GET, 'callback');
// ...
echo sprintf('%s(%s);', $callback, $json);
Define a JavaScript function to process the returned data:
function logResults (data) {
alert(data[0].title);
}
This way you basically get a dynamically generated good old <script> tag that loads a simple script:
logResults([{
"title": "keren",
"picture": "http://something.png",
"id":1
}, {
"title": "diana",
"picture": "/plugins/system/conversekit/conversekit/images/avatar.png",
"id": 2
}]);
But since you are making an AJAX call in your own domain:
url: "/plugins/system/chat/jsonstr.php",
^^
No "http://example.com/` prefix pointing to a third-party site
... you don't need JSONP at all: plain JSON will be enough.

How can I get response from webservice in jquery?

I want to get the data response from my login webservice. Here is my web service
http://41.128.183.109:9090/api/Data/getloginer?medid=a&pass=a
(for testing). Here is my code:
$("#login").click(function () {
var url = "http://41.128.183.109:9090/api/Data/getloginer?medid=a&pass=a";
$.ajax({
url: url,
type: 'Get',
success: function (data) {
alert(data.Medical_id);
},
});
});
The alert() shows me undefined. Please advise on what the problem could be.
The result is an array, so in order to get that field you have to iterate the result or get the first item:
for (var i in data) {
console.log(d[i].Medical_id);
}
Or you can simply get the first result:
$.ajax({
url: 'http://41.128.183.109:9090/api/Data/getloginer?medid=a&pass=a',
type: 'Get',
success: function (data) {
alert(data[0].Medical_id);
}
});
The JSON result you are getting is :
[{"$id":"1","id":8,"Medical_id":"a","Password":"a","Name":null,"Email":null,"gender":null,"Type":null}]
use for each to iterate through the results or
instead of this you can check the result like this :
var data = [{ "$id": "1", "id": 8, "Medical_id": "a", "Password": "a", "Name": null, "Email": null, "gender": null, "Type": null }]
alert(data[0].Medical_id);
If you develop application in localhost then refer this questions also.
"No 'Access-Control-Allow-Origin' header is present on the requested resource"
If you are using chrome, then use this link to use CORS enable plugin.
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US
hope this will help

Jquery webservice call Cannot read property 'contentDocument' of undefined

I am sending this valid json response from the backend
[
{
"id": 123,
"vendorName": "PoppyCounter",
"item": "Chocltae"
},
{
"id": 1234,
"vendorName": "PoppyCounter",
"item": "Chocltae"
},
{
"id": 12345,
"vendorName": "PoppyCounter",
"item": "Chocltae"
}
]
I am making a webservice call from Jquery as shown below
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'http://192.168.2.46:8086/Poller/poll/initial',
jsonpCallback: 'jsonCallback',
dataType: 'jsonp',
success: function (msg) {
},
error: function (e) {
$("#divResult").html("WebSerivce unreachable");
}
});
});
</script>
</head>
<body>
<div id="divResult" style="margin-top: 20px;">
</div>
</body>
</html>
I am getting the following exception
TypeError {stack: (...), message: "Cannot read property 'contentDocument' of undefined"}
Could anybody please tell me how to resolve this error ??
You are asking for JSONP but the response from your backend is raw JSON, the response should be more like:
jsonCallback([
{
"id": 123,
"vendorName": "PoppyCounter",
"item": "Chocltae"
}
])
There should also be a global function called jsonCallback that will get the data array as an argument.
function jsonCallback (data) {
console.log(data);
}
You have to setup the backend to format the JSONP, you can find the correct callback name as jQuery will send "jsonCallback" as the GET parameter "callback".
The backend should then serve the request as application/javascript instead of application/json.

jQuery .getJSON and .ajax get request both return null

I am trying to load a json file with ajax to populate my html, and for whatever reason, when I try to do so the json that is returned from either a simple ajax call or .getJSON call is null. Here is my HTML:
<!doctype html>
<html>
<head>
<title>Lab 4 AJAX</title>
<script type="text/javascript" src="resources/jquery-1.4.3.min.js"></script>
<script src="lab4.js"></script>
</head>
<body>
<div id="song-template">
<a id="site" href="#"><img id="coverart" src="images/noalbum.png"/></a>
<h1 id="title"></h1>
<h2 id="artist"></h2>
<h2 id="album"></h2>
<p id="date"></p>
<p id="genre"></p>
</div>
</body>
</html>
Here is a sample of the JSON I'm trying to load:
[
{
"name" : "Short Skirt, Long Jacket",
"artist" : "Cake",
"album" : "Comfort Eagle",
"genre" : "Rock",
"year" : 2001,
"albumCoverURL" : "images/ComfortEagle.jpg",
"bandWebsiteURL" : "http://www.cakemusic.com"
}
]
And here is the javascript I am trying to load it with:
function updateHTML(json)
{
var templateNode = $("#song-template").clone(true);
$("#song-template").remove();
debugger;
$.each(json, function(key, song)
{
var songNode = templateNode.clone(true);
songNode.children("#site").href(song.bandWebsiteURL);
songNode.children("#coverart").src(song.albumCoverURL);
songNode.children("#title").text(song.name);
songNode.children("#artist").text(song.artist);
songNode.children("#album").text(song.album);
songNode.children("#date").text(song.year);
songNode.children("#genre").text(song.genre);
$("body").append(songNode);
});
}
$(document).ready(function()
{
$("#site").click(function()
{
$.getJSON("lab4.json", updateHTML);
// $.ajax(
// {
// url: "lab4.json",
// type: "GET",
// dataType: "json",
// success: updateHTML
// });
});
});
Both the getJSON and the ajax result in json being null when updateHTML is run. Any idea what could be causing this?
.href and .src are not jQuery methods. You need to write:
.attr("href",
.attr("src",
http://jsfiddle.net/ExplosionPIlls/cwwCh/

Categories