JavaScript/jQuery: Setting up IP Geolocation API within CodePen - javascript

I am very new to using APIs and am having a difficult time making a GET request to IP Geolocation API. I am not sure if the problem is with my code or with something concerning CodePen (it's probably my code).
I took the JavaScript directly from the example listed on IP Geolocation API page. I was going to modify it after seeing it work in action but I couldn't get it work at all. I tried modifying the URL to include both http:// and https://.
JavaScript:
$(document).ready(function() {
$.getJSON("http://ip-api.com/json/?callback=?", function(data) {
var table_body = "";
$.each(data, function(k, v) {
table_body += "<tr><td>" + k + "</td><td><b>" + v + "</b></td></tr>";
});
$("#GeoResults").html(table_body);
});
});
HTML:
<div class="weather">
<div class="row title">
<h1>weather</h2>
</div>
<div class="row icon">
</div>
<div id = "GeoResults" class="row temp">
<p class = "city">City here</p>
</div>
</div>
URL to my CodePen: https://codepen.io/mattr8/pen/yXEMRM
API I am trying to use: http://ip-api.com/docs/api:json

Codepen doesn't want to work with ip-api.com because of https. Because codepen is served over https it will block any requests that are not https. If you go to http://ip-api.com/json/?callback=? you will see the information you're trying to reach. If you go to https://ip-api.com/json/?callback=? you will receive an error.
The jsbin example they link to does not use https, so it works fine.
So to fix your issue, create an example on a service or your own machine using http, not https for the request.

Related

How to reload page in MVC dynamically

Can someone help me? I want to change my page when some status change. I don't want to see that refresh sign above.
<script type="text/javascript" language="javascript">
var idleInterval = setInterval("reloadPage()", 5000);
function reloadPage() {
location.reload();
}
</script>
<h2>Verlichting</h2>
<div class="Verlichting">
<div class="Border">
Verlichting Garage 1
</div>
<div class="ButtonVerlichting">
#if (Model.Verlichting1 == true)
{
<button class="On">Aan</button>
}
else if (Model.Verlichting1 == false)
{
<button class="Off">Uit</button>
}
</div>
<div class="Border">
Verlichting Garage 2
</div>
<div class="ButtonVerlichting">
#if (Model.Verlichting2 == true)
{
<button class="On">Aan</button>
}
else if (Model.Verlichting2 == false)
{
<button class="Off">Uit</button>
}
</div>
<div class="Border">
Verlichting Garage Grind
</div>
<div class="ButtonVerlichting">
#if (Model.VerlichtingGrind == true)
{
<button class="On">Aan</button>
}
else if (Model.VerlichtingGrind == false)
{
<button class="Off">Uit</button>
}
</div>
</div>
<div class="clear">
</div>
When one of the Models bool change.
My page need to change when some State change. The buttons control some lights.
Now I refresh te page every 5 seconds. But i want when one state change it change?
I work normally with C# MVC but not with javascript of something else.
You cannot refresh the View server side or "dynamically" with your current code.
HTTP is stateless.
HTTP works like this: a client (web browser in your case, like Chrome) has requested a resource from your server (/mywebsite/myview) because you entered a web address/URL/URI into your web browser location bar. That web address is a "mapping" to your server. An HTTP GET request is sent from your browser to your server and your server is running ASP.NET, IIS processes the request and passes the request to your ASP.NET MVC app. Your controller/view route entry matches and your ASP.NET app View code is served back to the web browser in the form of an HTTP response.
Your web browser parses the Response, containing CSS/HTML and Javascript and renders the view/page.
Your browser is now disconnected from the server. Your browser is not going to talk to your server again unless you take an action like pressing a button or entering a different URL into the location bar. On the other side, your server has no current way to talk to the client browser, your server is disconnected from your client/web browser.
This is a standard HTTP request/response.
You are looking for a push notification feature in your software. Since you are using ASP.NET and are not familiar with Javascript, SignalR would be the best way to keep a connection open between the web browser and your server via Web Sockets with a long polling fallback. SignalR is very easy to use and get setup.
Long polling is what you are currently doing, you are checking every 5 seconds for a change. You can continue to this but instead of getting all the HTML/CSS and Javascript again with a reload. Simply check some other Controller/API endpoint for a state change and then reload the whole page only when that state change occurs. This is actually a reasonably scalable solution from the sounds of your current needs.

The quote isnt appearing on the webpage

What I'm trying to do is when the button is click the quote appears on the webpage but its not working. I am using a api
$(".btn").on("click",function(){
$.ajaxSetup({cache:false})
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&callback=",function(data){
$(".quote").html(data[0].content + "-" + data[0].title);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<div class = "container-fluid">
<div class = "row"></div>
<div class = "text-center quote-box">
<h1 >Random Quote Generator</h1>
<p class = "quote"> Click the button to get a random quote</p>
</div>
<div class = col-md-4 id = quote-button>
<button class="btn btn-primary" type="submit" id = quote-button>New Quote</button>
<button class="btn btn-primary" type="submit" id = quote-button><i class = "fa fa-twitter">Twitter</i></button>
</div>
</div>
</div>
Change http to https. Issue might be due to "Mixed Content", http and https which will be blocked by your browser.
$(".btn").on("click",function(){
$.ajaxSetup({cache:false})
$.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&callback=",function(data){
$(".quote").html(data[0].content + "-" + data[0].title);
});
});
Check this plunk
Mixed content occurs when initial HTML is loaded over a secure HTTPS
connection, but other resources (such as images, videos, stylesheets,
scripts) are loaded over an insecure HTTP connection. This is called
mixed content because both HTTP and HTTPS content are being loaded to
display the same page, and the initial request was secure over HTTPS.
Modern browsers display warnings about this type of content to
indicate to the user that this page contains insecure resources.
The request is working but the browser is blocking it because it is a cross origin request. Either get the server administrator has to enable cors or check if a JSONP request is supported.

JavaScript Automatically Save Image File to Folder

How can I automatically save an image from canvas into a folder? I am using the
signature_pad-1.5.2 from szimek (link). Here is what I have tried so far:
HTML CANVAS
<div id="signature-pad" class="m-signature-pad">
<div class="m-signature-pad--body">
<canvas></canvas>
</div>
<div class="m-signature-pad--footer">
<div class="description">Signature</div>
<button type="button" class="button clear" data-action="clear">Clear</button>
<button type="button" class="button save" data-action="save">Save</button>
</div>
</div>
<script src="js/signature_pad.js"></script>
<script src="js/app.js"></script>
The signature_pad.js is for drawing in the canvas. Here is the content of my app.js from signature_pad-1.5.2 (I modified it a little):
app.js
var wrapper = document.getElementById("signature-pad"),
clearButton = wrapper.querySelector("[data-action=clear]"),
saveButton = wrapper.querySelector("[data-action=save]"),
canvas = wrapper.querySelector("canvas"),
signaturePad;
saveButton.addEventListener("click", function (event) {
if (signaturePad.isEmpty()) {
alert("Please provide signature first.");
} else {
newfolder = myObject.CreateFolder ("C:\\xampp\\htdocs\\signature\\resources\\sigs");
alert();
saveButton.href = signaturePad.toDataURL();
saveButton.download = 'image.png';
}
});
I am trying to save the image.png file to newFolder when I click the save button. Thanks
There is no way for javascript to access the filesystem, this is due to security concerns. You can store the image data as a string in a lot of places though, such as browser storage. Luckily for you it looks as though you're trying to store it in a web server's folder!
The best thing for you to do here is to make a script on the server that you want to store the image on. That script will accept a file POST request and store it in a server folder somewhere. This can be written in php for example.
Once you have that server-side script, make an AJAX request from the client (from the javascript) with the image data to that server script.
I would provide code samples and a more in-depth explanation, but unfortunately you haven't provided any real info about your tech stack and what exactly you're trying to accomplish. Good luck!

JSON data not showing up when I change http.jsonp() URL

I'm trying to read data from an external JSON file using AngularJS.
Here is my HTML
<div class="panel panel-default" ng-controller="MyAppController">
<div class="panel-heading">
<div class="input-group">
<input ng-model="query" type="text" placeholder="What file are you looking for?" class="form-control"><span ng-click="clearFilter()" ng-disabled="query.length == 0" class="input-group-addon"><i class="glyphicon glyphicon-remove"></i></span>
</div>
</div>
<div class="panel list-group">
<span data-ng-repeat="cat in cats | filter: query" class="list-group-item animate-repeat">{{cat.title}}
</span>
<div class="clearfix"></div>
</div>
</div>
It works fine when I use this in my JS file and data shows up in a list.
function MyAppController($scope, $http) {
var url = 'http://jobs.github.com/positions.json?callback=JSON_CALLBACK';
$http.jsonp(url).success(function(data) {
$scope.cats = data;
});
}
But when I change the URL to my personal site nothing shows up even though I literally just copied and pasted everything in the github JSON file to a local JSON file. (just to test it out)
function MyAppController($scope, $http) {
var url = 'http://ciagent.com/Website-files/positions.json?callback=JSON_CALLBACK';
$http.jsonp(url).success(function(data) {
$scope.cats = data;
});
}
http://ciagent.com/Website-files/positions.json?callback=JSON_CALLBACK &
http://jobs.github.com/positions.json?callback=JSON_CALLBACK have the same exact content but only the github one works with my angular app for some reason.
Any reasons as to why it's doing this?
Assuming you are using a static resource file you need to realize that the string 'JSON_CALLBACK' is a placeholder and gets modified within each $http.jsonp() request to something else.
You should be able to see this in the actual request URL in network tab of browser dev tools.
You can also open the github version in browser and change the value to see that it is not static on their server and will adjust to whatever value is sent.
If you want to use jsonp server side it needs to return dynamic value of the callback GET parameter value.
+1 to what #charlietfl said. Also, be sure to set Content-Type:application/javascript;charset=utf-8 in your response headers.

jQuery $.ajax response empty, but only in Chrome

I've exhausted every avenue of research to solve this one so hopefully someone else will think of something I just didn't.
Relatively straight forward setup, I have a html page with some javascript that makes an ajax request to a URL (in the same domain) the java web app in the background does its stuff and returns a partial html page (no html, head or body tags, just the content) which should be inserted at a particular point in the page.
All sounds pretty easy and the code I have works in IE, Firefox and Safari, but not in Chrome. In Chrome the target element just ends up empty and if I look at the resource request in Chromes developer tools the response content is also empty.
All very confusing, I've tried a myriad of things to solve it and I'm just out of ideas. Any help would be greatly appreciated.
var container = $('#container');
$.ajax({
type: 'GET',
url: '/path/to/local/url',
data: data('parameters=value&another=value2'),
dataType: 'html',
cache: false,
beforeSend: requestBefore,
complete: requestComplete,
success: requestSuccess,
error: requestError
});
function data(parameters) {
var dictionary = {};
var pairs = parameters.split('&');
for (var i = 0; i < pairs.length; i++) {
var keyValuePair = pairs[i].split('=');
dictionary[keyValuePair[0]] = keyValuePair[1];
}
return dictionary;
}
function requestBefore() {
container.find('.message.error').hide();
container.prepend('<div class="modal"><div class="indicator">Loading...</div></div>');
}
function requestComplete() {
container.find('.modal').remove();
}
function requestSuccess(response) {
container.empty();
container.html(response);
}
function requestError(response) {
if (response.status == 200 && response.responseText == 'OK') {
requestSuccess(response);
} else {
container.find('.message.error').fadeIn('slow');
}
}
All of this is executed in a $(document).ready(function() {});
Cheers,
Jim
#Oleg - Additional information requested, an example of the response that the ajax call might receive.
<p class="message error hidden">An unknown error occured while trying to
retrieve data, please try again shortly.</p>
<div class="timeline">
<a class="icon shuttle-previous"
rel="max_id=16470650733&page=1&q=something">Newer Data</a>
<a class="icon shuttle-next"
rel="max_id=16470650733&page=3&q=something">Older Data</a>
</div>
<ol class="social">
<li class="even">
<div class="avatar">
<img src="sphere_normal.gif"/>
</div>
<p>
Some Content<br/>
<span class="published">Jun 18, 2010 11:29:05 AM</span> - <a
target="_blank" href="">Direct Link</a>
</p>
</li>
<li class="odd">
<div class="avatar">
<img src="sphere_normal.gif"/>
</div>
<p>
Some Content<br/>
<span class="published">Jun 18, 2010 11:29:05 AM</span> - <a
target="_blank" href="">Direct Link</a>
</p>
</li>
</ol>
<div class="timeline">
<a class="icon shuttle-previous"
rel="max_id=16470650733&page=1&q=something">Newer Data</a>
<a class="icon shuttle-next"
rel="max_id=16470650733&page=3&q=something">Older Data</a>
</div>
I just resolved a similar problem, and thought I'd post my solution in case it's of use for anyone else.
Only Firefox and Chrome were showing an empty ajax response, so it seemed to be a cross domain problem, yet everything was on the same domain.
It turned out that the 'www.', which I had superfluously and stupidly hard-coded into my ajax url was to blame. Had I been using a relative path, everything would've been fine.
I had my test site open at that particular moment as "http://domain.com", with no 'www.', so Firefox and Chrome treated it as a different domain. Navigating to "http://www.domain.com" resulted in the ajax call working in all browers.
So, given that you wrote:
url: '/path/to/local/url'
..as is the convention when we don't want to disclose our paths, I couldn't help but wonder if in fact you had written an absolute path, just as I had...?
Chrome stepped onto its own foot with local files security, so no AJAXing local files with relative paths:
http://code.google.com/p/chromium/issues/detail?id=47416
I took your source code and set up a quick test scenario but fail to replicate your problem. It is working for me just fine in both Firefox (3.6.3) and Chrome (5.0.375.70). I tried it both locally and on a remote server.
So your code is most likely not to blame. But I would also think that it's not generally a Chrome related issue.
Other people seem to have come across this though. Changing the content type had no effect in my test scenario though. It even works when I set the Content-Type to image/jpeg.
On the JQuery forums someone indicated differing behavior depending on whether he runs his application locally or on a remote server. If this was the case for you, you could compare HTTP request and response headers to track down the issue.

Categories