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.
Related
I am trying to test Google Cloud analyzeSyntax from JavaScript, forming an ajax request using jQuery, but I keep getting errors returned. I obviously don't understand how to form the call properly but cannot find any answers or examples that match what I am trying to do.
The documentation for the call is
https://cloud.google.com/natural-language/docs/reference/rest/v1/documents/analyzeSyntax.
HTML
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="pm.js"></script>
</head>
<body>
<button onclick="analyzeSyntax();">Go</button>
<div id="results"></div>
</body>
</html>
JS
function analyzeSyntax() {
$.ajax({
type: "POST",
url: "https://language.googleapis.com/v1/documents:analyzeSyntax?key=XXXXXXXXXXXXX",
data: { "document" : {
"type":"PLAIN_TEXT",
"content":"I just want to try out analyzeSyntax",
},
encodingType: "UTF8"
},
success: function(data){
alert("success " + data.responseText);
},
error: function(data){
alert("error " + data.responseText);
}
});
}
ERROR
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"document[type]\": Cannot bind query parameter. Field 'document[type]' could not be found in request message.\nInvalid JSON payload received. Unknown name \"document[content]\": Cannot bind query parameter. Field 'document[content]' could not be found in request message.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"document[type]\": Cannot bind query parameter. Field 'document[type]' could not be found in request message."
},
{
"description": "Invalid JSON payload received. Unknown name \"document[content]\": Cannot bind query parameter. Field 'document[content]' could not be found in request message."
}
]
}
]
}
I am new to Microsoft Cognitive services and this problem seems to have an easy fix but it has spoiled my two days. I have just copied the Computer vision for javascript code and replaced my the subscription key with mine and opened the .html file in my browser it says error.
DO I have to add something in the code
Also, I have nowt provided any image in this code what's he doing without an image?
The script code is here
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
var params = {
// Request parameters
"visualFeatures": "Categories",
"details": "{string}",
"language": "en",
};
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{6e07223403d94848be20af6f126fsssd}");
},
type: "POST",
// Request body
data: "{body}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
code and preview of error
While it's not very obvious, in any code snippet from the Cognitive Service API reference page such as this one that I suspect you were using, you must provide a value (or remove) wherever it shows {something}. Here's code with suitable values:
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
var myKey = "6e07223403d94848be20af6f126fsssd";
var myBody = {url:"http://www.gannett-cdn.com/-mm-/2d2a8e29485ced74b7537554043aeae2e0bba202/c=0-104-5177-3029&r=x1683&c=3200x1680/local/-/media/2015/07/18/USATODAY/USATODAY/635728260394906410-AP-GOP-Trump-2016.jpg"}
$(function() {
var params = {
// Request parameters
"visualFeatures": "Categories",
"language": "en",
};
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", myKey);
},
type: "POST",
// Request body
data: JSON.stringify(myBody),
})
.done(function(data) {
alert("success");
debugger;
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
I know I can use set to hit Firebase, but I want to use AJAX instead so I tried the below code. When I load test.html in my browser, the console says -
XMLHttpRequest cannot load https://jleiphonebook.firebaseio.com/json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 405.
//text.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Firebase Test</title>
<script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>
</head>
<body>
<div id="hi"></div>
<script src="https://code.jquery.com/jquery-1.12.2.min.js" integrity="sha256-lZFHibXzMHo3GGeehn1hudTAP3Sc0uKXBXAzHX1sjtk=" crossorigin="anonymous"></script>
<script>
$(document).ready(function () {
var param = {lastName: "Doe", firstName: "John"};
$.ajax({
url: 'https://jleiphonebook.firebaseio.com/json',
type: "POST",
data: param,
success: function () {
alert("success");
}
});
});
</script>
</body>
</html>
//firebase rules
{
"rules": {
".read": true,
".write": true
}
}
Firebase expects the body to be a JSON string, so you'll need to stringify it:
$(document).ready(function () {
var param = {lastName: "Doe", firstName: "John"};
$.ajax({
url: 'https://jleiphonebook.firebaseio.com/.json',
type: "POST",
data: JSON.stringify(param),
success: function () {
alert("success");
},
error: function(error) {
alert("error: "+error);
}
});
});
This will accomplish the same by the way:
$.post('https://jleiphonebook.firebaseio.com/.json',
JSON.stringify(param),
function () {
alert("success");
}
);
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"
}
]
}
);
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/