ERROR---Origin null is not allowed by Access-Control-Allow-Origin [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin
I'm developing weather application which is working fine in browsers.
But when I try to deploy in my android phone it is not working fine and it is throwing error. XML response is null. please help me.
<html>
<head>
<title>Calling Web Service from jQuery</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.2.0.js"></script>
<script type='text/javascript' src='xmlObject.js'></script>
<script type='text/javascript' src='jquery-1.8.2.min.js'></script>
<script type="text/javascript" src="json2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnCallWebService").click(function (event) {
alert('click' + $("#cityName").val());
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://www.webservicex.net/globalweather.asmx?op=GetWeather",true);
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState == 4)
{
var myXML=xmlhttp.responseXML;
alert("Response XML in getWeatherInformation : ");
alert(myXML);
var json = XMLObjectifier.xmlToJSON(xmlhttp.responseXML);
var body=JSON.stringify(json.Body[0]);
var result = json.Body[0].GetWeatherResponse[0].GetWeatherResult[0].Text;
var myXML2=XMLObjectifier.textToXML(result);
var json2 = XMLObjectifier.xmlToJSON(myXML2);
var body2=json2;
var location=body2.Location[0].Text;
var time=body2.Time[0].Text;
var temperature=body2.Temperature[0].Text;
var pressure=body2.Pressure[0].Text;
alert("location"+location+"..."+time+".."+temperature+".."+pressure);
}
}
xmlhttp.setRequestHeader("Content-Type", "text/xml");
var xml ='<?xml version="1.0" encoding="utf-8"?>'+
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'+
'<soap:Body>'+
'<GetWeather xmlns="http://www.webserviceX.NET">'+
'<CityName>'+ $("#cityName").val() +'</CityName>'+
'<CountryName>India</CountryName>'+
'</GetWeather>'+
'</soap:Body>'+
'</soap:Envelope>';
alert("Request XML : ");
alert(xml);
xmlhttp.send(xml);
});
});
function processSuccess(data, status, req, xml, xmlHttpRequest, responseXML) {
alert('success' + status + ">>" +typeof $(req.responseXML));
var myObj = new Array();
$(req.responseXML)
.find('GetWeatherResult')
.each(function(){
alert($(this));
myObj.push($(this));
});
$(myObj).each(function(){
var x = $(this).find('Location').text();
alert('loc'+ x + $(this).find('Location'));
var p = $(this).find('Location');
for (var key in p) {
alert(key + " -> " + p[key]);
}
});
}
function processError(data, status, req) {
alert(req.responseText + " " + status);
console.log(data);
console.log(status);
console.log(req);
}
</script>
</head>
<body>
<h3>
Weather Report
</h3>
Enter your city name:
<input id="cityName" type="text" />
<input id="btnCallWebService" value="GetInformation" type="button" />
</body>
</html>

You need to allow the cross domain calls to http://www.webservicex.net
See this post:
Cordova 1.9.0 Ajax not retrieving
Edit your xml in your res folder to include this line:
<access origin="http://www.webservicex.net*"/>
Or if its Phonegap-Build add that line to the config.xml

Related

Problem of NodeJS & JavaScript: webpage no output [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 11 months ago.
newsfeed.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>News Feed</title>
<link rel = "stylesheet" href = "stylesheets/style.css">
<script src = "javascripts/script.js"></script>
</head>
<body onload = "showNewsFeed()">
<!-- (i) -->
<div id = "header">
<input id="searchNewsHeadline" type="text">
<button onclick="">Search news headlines</button>
<a>Login</a>
</div>
<!-- (ii) -->
<div id = "news">
<!-- Display news entries -->
</div>
<!-- (iii) -->
<div id = "pageindex">
<!-- page indices -->
</div>
</body>
</html>
app.js
var express = require('express');
var app = express();
var monk = require('monk');
var db = monk('127.0.0.1:27017/assignment1');
// Make db accessible to router
app.use(function(req,res,next){
req.db = db;
next();
});
var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
})
app.get('/newsfeed.html', function(req, res){
var db = req.db;
var newsList = db.get('newsList');
var response = "";
newsList.find({}, ['-_id', 'headline', 'date', 'content', '-comments']).each((news) =>{
response += "<h4>" + news['headline'] + "</h4>";
response += "<h6>" + news['date'] + "</h6>";
response += "<p>" + news['content'] + "</p>";
})
res.send(response);
});
script.js
function showNewsFeed(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
var newsfeeds = JSON.parse(xmlhttp.responseText);
document.getElementById("news").innerHTML = newsfeeds;
}
}
xmlhttp.open("GET", "/newsfeed.html", true);
xmlhttp.send();
}
I am working on an assignment that fetches newsfeeds from a MongoDB database and then puts them onto the webpage (newsfeed.html). I tried to do so with these codes, it return a blank page with no output. I do believe the database is linked correctly and I am not sure which part goes wrong as no error message is kicking back.
app.get('/newsfeed.html', function(req, res){
var db = req.db;
var newsList = db.get('newsList');
var response = "";
newsList.find({}, ['-_id', 'headline', 'date', 'content', '-comments']).each((news) =>{
response += "<li><h4>" + news['headline'] + "</h4>";
response += "<h6>" + news['date'] + "</h6>";
response += "<p>" + news['content'] + "</p></li>";
}).then(()=>{
res.send(response);
})
});
Turn out it can be solved by this. I think the scope of var response makes it empty after executing the loop.

jQuery - d3.v3.min.js error 404 while building Spring Boot and Neo4j app

I'm trying to make application with Spring Boot, Neo4j and jQuery. For that I used Neo4j example project from github, but I'm getting error in those lines:
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="https://d3js.org/d3.v3.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function () {
function showMovie(title) {
$.get("/movies/search/findByTitle?title=" + encodeURIComponent(title), // todo fix paramter in SDN
function (data) {
if (!data) return;
var movie = data;
$("#title").text(movie.title);
$("#poster").attr("src","/posters/"+encodeURIComponent(movie.title)+".jpg");
var $list = $("#crew").empty();
movie.roles.forEach(function (cast) {
$.get(cast._links.person.href, function(personData) {
var person = personData.name;
var job = cast.job || "acted";
$list.append($("<li>" + person + " " +job + (job == "acted"?" as " + cast.roles.join(", ") : "") + "</li>"));
});
});
}, "json");
return false;
}
</script>
I'm getting error 404 when trying to use two first scripts. I'm running this project on my local server.
EDIT.
Here is response with an error:

Unable to Consume Linkedin API through Localhost

I found similar threads but unfortunately didn't help resolve my issue so posting a new thread
I am trying to consume the linked API through localhost. The error I am getting is:
Uncaught Error: You must specify a valid JavaScript API Domain as part of this key's configuration.
Under Javascript Settings, Valid SDK Domains I added
http://127.0.0.1
http://127.0.0.1:8704
http://localhost
http://localhost:8704
http://localhost
I tried adding in https as well but still I am facing the same error.
I tried creating a ASP.NET project in Visual studio and tried running my html file with the associated port number which also I added in valid SDK domain, still the same issue.
My code is below:
<html>
<head>
<script type="text/javascript" src="https://platform.linkedin.com/in.js">
api_key: [MY KEY] //Client ID
onLoad: OnLinkedInFrameworkLoad //Method that will be called on page load
authorize: true
</script>
</head>
<script type="text/javascript">
function OnLinkedInFrameworkLoad() {
console.log('OnLinkedInFrameworkLoad');
IN.Event.on(IN, "auth", OnLinkedInAuth);
}
function OnLinkedInAuth() {
console.log('OnLinkedInAuth');
IN.API.Profile("me").result(ShowProfileData);
}
function ShowProfileData(profiles) {
console.log('ShowProfileData' + profiles);
var member = profiles.values[0];
var id = member.id;
var firstName = member.firstName;
var lastName = member.lastName;
var photo = member.pictureUrl;
var headline = member.headline;
//use information captured above
var stringToBind = "<p>First Name: " + firstName + " <p/><p> Last Name: "
+ lastName + "<p/><p>User ID: " + id + " and Head Line Provided: " + headline
+ "<p/>"
document.getElementById('profiles').innerHTML = stringToBind;
}
</script>
<body>
<div id="profiles"></div>
</body>
</html>

JS automated click not working

EDIT:
I think i have found a solution for this one. Might be a little primitive but inserting it here until someone comes up with a better solution.
Thanks !
<html>
<body onload="makeShort()">
<p id="button" style=display:none; onclick="makeShort()">Click me.</p>
<span id="output" style=display:none; >Wait. Loading....</span>
</body>
<head>
</head>
<script type="text/javascript">
function makeShort()
{
var longUrl=location.href;;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response)
{
if(response.id != null)
{
str =""+response.id+"";
document.getElementById("output").innerHTML = str;
}
else
{
alert("error: creating short url n"+ response.error);
}
});
}
window.onload = makeShort;
function load()
{
//Get your own Browser API Key from https://code.google.com/apis/console/
gapi.client.setApiKey('xxxxxx');
gapi.client.load('urlshortener', 'v1',function(){document.getElementById("output").innerHTML="";});
}
window.onload = load;
</script>
<script>
setTimeout(function(){
document.getElementById('button').click();
},1000);
</script>
<script src="https://apis.google.com/js/client.js"> </script>
</html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<script>
function SendLinkByMail(href) {
var subject= "Interesting Information";
var body = document.getElementById("output").innerHTML;
body += " Interesting Information";
var uri = "mailto:?subject=";
uri += encodeURIComponent(subject);
uri += "&body=";
uri += encodeURIComponent(body);
window.open(uri);
}
</script>
</head>
<body>
<p>Email link to this page</p>
</body>
</html>
Can some one suggest why this "auto-click" function is not working in my code below?
function makeShort() {
var longUrl = location.href;;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response) {
if (response.id != null) {
str = "<b>Long URL:</b>" + longUrl + "<br>";
str += "<b>Short URL:</b> <a href='" + response.id + "'>" + response.id + "</a><br>";
document.getElementById("output").innerHTML = str;
} else {
alert("error: creating short url n" + response.error);
}
});} window.onload = function() {
var button = document.getElementById('modal');
button.form.submit();}
function load() {
//Get your own Browser API Key from https://code.google.com/apis/console/
gapi.client.setApiKey('xxxxxxxxx');
gapi.client.load('urlshortener', 'v1', function() {
document.getElementById("output").innerHTML = "";
});} window.onload = load;
<html>
<input type="button" id="modal" value="Create Short" onclick="makeShort();" /> <br/> <br/>
<div id="output">Wait. Loading....</div>
<head>
</head>
<script src="https://apis.google.com/js/client.js"> </script>
</html>
My basic aim is to insert a "share via email" button on the page which would shorten the url on the address bar and open user's email client/whatsapp app to share that url..
Obviously I could not find a way to combine these two functions in to one since I am not a very experienced js person. The primitive solution I found is to auto-click the first function, get the short url, and then find a different code to insert this in to the body of the "mailto" link, which will be my 2nd challenge.
To programmatically click a button on page load
If you are using jQuery:
$(function() {
$('#modal').click();
});
Plain javascript:
window.onload = function(){
var event = document.createEvent('Event');
event.initEvent('input', true, true);
document.getElementById("modal").dispatchEvent(event);
};

Javascript soap client doesn't work (wash_out service)

I wrote Web Service in Ruby (using wash_out). Here is link : http://dictionary.vipserv.org/slownik_de_pls/wsdl
I found solution to write javascript soap client. Code below:
<html>
<head>
<title>SOAP JavaScript Client Test</title>
<script type="text/javascript">
function soap() {
try
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'http://www.dictionary.vipserv.org/slownik_de_pls/wsdl/', true);
// build SOAP request
var sr = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tns="urn:WashOut"><soap:Body><tns:get_word_response><value xsi:type="xsd:string">robic</value></tns:get_word_response></soap:Body></soap:Envelope>';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert('done use firebug to see responce');
}
}
}
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(sr);
alert(xmlhttp.responseXML.xml);
// send request
// ...
}
catch(error)
{
alert(error);
}
}
</script>
</head>
<body>
<form name="Demo" action="" method="post">
<div>
<input type="button" value="Soap" onclick="soap();" />
</div>
</form>
</body>
</html>
Response is always null. What is wrong?
Cheers, thanks.
Take a look at the WSDL, you probably need to POST to http://dictionary.vipserv.org/slownik_de_pls/action instead of to http://www.dictionary.vipserv.org/slownik_de_pls/wsdl/.
Also, you might want to look at jQuery, and in particular a SOAP library like this one.
I have soap client in Ruby (Savon). There it works fine. I found other solution in jQuery, but I've got parse error. Below:
<html>
<head>
<title>Calling Web Service from jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnCallWebService").click(function (event) {
var wsUrl = "http://dictionary.vipserv.org/slownik_de_pls/wsdl";
var soapRequest = '<?xml version="1.0" encoding="UTF-8"?><env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tns="urn:WashOut" xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"><env:Body><tns:get_word><wartosc>machen</wartosc></tns:get_word></env:Body></env:Envelope>';
$.ajax({
type: "POST",
url: wsUrl,
contentType: "text/xml",
dataType: "xml",
data: soapRequest,
success: processSuccess,
error: processError
});
});
});
function processSuccess(data, status, req) {
if (status == "success")
$("#response").text($(req.responseXML).find("get_word_response").text());
}
function processError(data, status, req) {
alert(req.responseText + " " + status);
}
</script>
</head>
<body>
<h3>
Calling Web Services with jQuery/AJAX
</h3>
Enter your name:
<input id="txtName" type="text" />
<input id="btnCallWebService" value="Call web service" type="button" />
<div id="response" />
</body>
</html>

Categories

Resources