I know how to use jQuery well, but I don't know so much pure JavaScript.
This is my jQuery code:
$(document).ready(function() {
$.get('http://jsonip.com/', function(r){
var ip_address = r.ip;
my_function(ip_address);
});
function my_function(ip_address){
var url = "Url_to my server hosted on a different domain";
var data = {number:"1286", ip: ip_address};
$.ajax({
url: url,
type: "POST",
dataType: 'json',
crossDomain: true,
data: {data: data},
success: function (data) {console.log(JSON.stringify(data));},
error: function (xhr, error) {console.log("There was an error and data was not posted.");}});}
});
What it does: it is pasted in any website, then it picks any visitors ip address and send that as JSON to my server as variable data.
Problem: the code is working perfectly okay in some sites but not all the sites due to jQuery dependency. And I want to remove this and use pure JavaScript.
I am getting great answers but CORS is not working, there failing them. I am using different domains since the site we are sending data to is hosted on another server.
As mentioned in my commment above, you do not need the first ajax request as you can get this information from the request headers (PHP Example below) from your AJAX request.
To make sure that your website(s) have jQuery loaded you can run a check in your script and load it in dynamically. Using some code from this answer. See below for an example:
// Anonymous "self-invoking" function
(function() {
// Load the script
var script = document.createElement("SCRIPT");
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName("head")[0].appendChild(script);
// Poll for jQuery to come into existance
var checkReady = function(callback) {
if (window.jQuery) {
callback(jQuery);
}
else {
window.setTimeout(function() { checkReady(callback); }, 100);
}
};
// Start polling...
checkReady(function($) {
var url = "Url_to my server hosted on a different domain";
var data = {number:"1286", ip: ip_address};
$.ajax({
url: url,
type: "POST",
dataType: 'json',
crossDomain: true,
data: {data: data},
success: function (data) {console.log(JSON.stringify(data));},
error: function (xhr, error) {console.log("There was an error and data was not posted.");
});
});
})();
To get the IP Address from your ajax request: (PHP) Source
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
The annoying part is that you need to do a cross-domain POST to send your data. There's a W3C standard for this called Cross-Origin Resource Sharing (CORS). Check out this tutorial for more info.
You'll want to put this at the bottom of the page. Different browsers handle ready state change events differently, so let's just avoid them.
<script>
// Once the JSONP script loads, it will call this function with its payload.
function getip(ipJson) {
var method = 'POST';
var url = 'URL of your server';
// The XMLHTTPRequest is the standard way to do AJAX. Try to use CORS.
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
}
// Create your request body. It has to be form encoded. I'm not sure
// where you get `number` from, so I've hard-coded it.
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send('number=1286&ip=' + ipJson.ip);
}
</script>
<!-- Get the IP using JSONP so we can skip implementing that. -->
<script type="application/javascript" src="http://www.telize.com/jsonip?callback=getip"></script>
This probably only works in modern browsers, but it should work in most modern browsers.
Replace $.ready(function...) with document.addEventListener('DOMContentLoaded', function..., false).
Replace $.ajax with XMLHttpRequest:
var xhr = new XMLHttpRequest();
//var data = {number:"1286", ip: ip_address};
var data = new FormData();
data.append("number", "1286");
data.append("ip", ip_address); // As stated by Scriptable in the question comments, your server should be able to get it from the request headers.
xhr.onload = function() { console.log(JSON.stringify(this.response)); };
xhr.onerror = function() { console.log("There was an error and data was not posted.") };
xhr.open("POST", "URL to your server");
xhr.send(data);
Related
Having trouble showing the JSON response using window.alert or alert in JavaScript. I'm not a native JS coder, I apologize for the noobness. Below are a few examples I've tried based on examples I found online.
My goal is to have the JSON response appear in an alert popup window.
# example 1
<script type="text/javascript">
var client = new HttpClient();
client.get('https://website.com/json/', function(response) {
window.alert(response);
});
</script>
# example 2
$.get('https://website.com/json/', function(responseText) {
alert(responseText);
});
# example 3
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
$.get('https://website.com/json/', function(responseText) {
alert(responseText);
});
</script>
# example 4
var xhr = new XMLHttpRequest();
xhr.open('GET', "https://website.com/json/", true);
xhr.send();
xhr.onreadystatechange = processRequest;
function processRequest(e) {
}
The first problem that I can see is that the url https://website.com/json does not have a correct response.
you can for example try these links: https://jsonplaceholder.typicode.com/posts/1
or https://ipinfo.io/json
I prove your example 4 and it work perfectly.
var xhr = new XMLHttpRequest();
xhr.open('GET', "https://jsonplaceholder.typicode.com/posts/1", true);
xhr.send();
xhr.onreadystatechange = processRequest;
function processRequest(e) {
var response=JSON.stringify(e);
alert(response);
}
you can notice that I put the alert in the processRequest function and before display it. I used JSON.stringify to change the object e to a string. Let me knoe if that work for you.
When trying to display object in alert it will say [Object object]. Your response is a JSON. Stringify it, so that alert can display it.
$.get('https://website.com/json/', function(responseText) {
alert(JSON.stringify(responseText));
});
I have created a sample code on jsfiddle for your scenario:
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts/1/comments",
type: "GET",
dataType: "json",
success: function(data){
alert(JSON.stringify(data));
}
});
https://jsfiddle.net/ashvinimaurya/kn3yv7Lh/7/
I'm making an ajax call and then alerting the response data after stringifying.
I think you are getting cors error, (cross origin error). You should set your request headers correctly according to the third party (https://website.com/json/) server headers.
I want to call sample service using Ajax. Below is the code i am using.
<script type="text/javascript">
var date1;
var time1;
var time2;
var date2
function CallService() {
date1 = new Date();
time1 = date1.getMilliseconds();
$.ajax({
url: "https://www.google.co.in",
type: "GET",
crossDomain: true,
contentType: "text/xml; charset=\"utf-8\"",
success: OnSuccess,
error: OnError
});
return false;
}
function OnSuccess(data, status) {
alert('success');
}
function OnError(request, status, error) {
alert('error');
}
$(document).ready(function () {
jQuery.support.cors = true;
});
</script>
I know that if we add header('Access-Control-Allow-Origin: *'); in server will remove the issue.
But i don't have access to the server side code so please can some one tell me how can i enable cross domain access in javascript.
Thanks in Advance.
You can use JSONP which stands for “JSON with Padding” and it is a workaround for loading data from different domains. It loads the script into the head of the DOM and thus you can access the information as if it were loaded on your own domain, thus by-passing the cross domain issue
Basic Example : http://jsfiddle.net/yvzSL/714/
Please refer "http://www.sitepoint.com/jsonp-examples/" for more examples
Is there a way to add a custom http header into the request done by an <iframe> when changing the source (src) using javascript?
You can have the results of an ajax request that has custom headers be set as the content of an iframe like so:
$.ajax({
type: "GET",
url: "https://app.icontact.com/icp/a/",
contentType: "application/json",
beforeSend: function(xhr, settings){
xhr.setRequestHeader("some_custom_header", "foo");},
success: function(data){
$("#output_iframe_id").attr('src',"data:text/html;charset=utf-8," + escape(data))
}
});
This is assuming the iframe is pointing at a cross domain src. It is simpler if everything is on the same domain.
Edit: Maybe try this variation.
$.ajax({
type: "GET",
url: "https://app.icontact.com/icp/a/",
contentType: "application/json",
beforeSend: function(xhr, settings){
xhr.setRequestHeader("some_custom_header", "foo");},
success: function(data){
$("#output_iframe_id").attr('src',"/")
$("#output_iframe_id").contents().find('html').html(data);
}
});
Rather than using a data URI, or setting the contents to a string, you can use URL.createObjectURL(), and set it as the src of the iframe.
var xhr = new XMLHttpRequest();
xhr.open('GET', 'some.pdf');
xhr.onreadystatechange = handler;
xhr.responseType = 'blob';
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
// this.response is a Blob, because we set responseType above
var data_url = URL.createObjectURL(this.response);
document.querySelector('#output-frame-id').src = data_url;
} else {
console.error('no pdf :(');
}
}
}
The object URLs are pretty interesting. They're of the form blob:https://your.domain/1e8def13-3817-4eab-ad8a-160923995170. You can actually open them in a new tab and see the response, and they're discarded when the context that created them is closed.
Here's a full example: https://github.com/courajs/pdf-poc
I ended up going with the approach proposed by the other answers here, that use ajax to get the html string and then directly set the contents of the iFrame.
However, I used the approach posted in this answer to actually set the contents of the iFrame, as I found it worked well cross platform with almost all devices I could dig up.
Tested - successful:
Chrome 54 (desktop) ^
Firefox 49 (desktop) ^
IE 11 (desktop) ^
IE 10 (desktop) in emulation mode ^
Safari/Chrome on iOS 8 (ipad)
Chrome on Android 6 (nexus phone)
Edge on Lumia 950 (Win 10 Phone)
^ confirmed that linked css and js in the content run correctly (others not tested)
Tested - unsuccessful:
IE 9 (desktop) in emulation mode
Safari/Chrome on iOS 7 (iPhone)
So putting them together gives something like this (Note: I havn't actually run this exact code):
$.ajax({
type: "GET",
url: "https://yourdomain.com/gethtml",
beforeSend: function(xhr) {
xhr.setRequestHeader("yourheader", "value");
},
success: function(data) {
var iframeDoc = document.querySelector('#myiframe').contentWindow.document;
iframeDoc.open('text/html', 'replace');
iframeDoc.write(data);
iframeDoc.close();
}
});
Here's an example of setting the iFrame contents in this JS Bin
Edit: Here's the html part
<iframe id="myiframe" src="about:blank"></iframe>
Edit 2:
The solution above appears to no longer be working in Firefox (50.1.0) for some unknown reason. Using the solution in this answer I've now changed to code to the example below, which also seems to be more robust:
$.ajax({
type: "GET",
url: "https://yourdomain.com/gethtml",
beforeSend: function(xhr) {
xhr.setRequestHeader("yourheader", "value");
},
success: function(data) {
var iframe = document.getElementById('myiframe');
iframe.contentWindow.contents = data;
iframe.src = 'javascript:window["contents"]';
}
});
The following code works. It is a modification of the code provided by Matthew Graves, modified to use the srcdoc attribute to solve the problem of CSS and JavaScript references not been ran. Unfortunately, it is only working in Chrome.
$.ajax({
type: "GET",
url: "https://app.icontact.com/icp/a/",
contentType: "application/json",
beforeSend: function(xhr, settings){
xhr.setRequestHeader("some_custom_header", "foo");},
success: function(data){
$("#output_iframe_id").attr('srcdoc',data)
}
});
Edit: Finally, I have resolved the issue of the scripts blocks cross-browser, by reassigning them to the iframe on document.ready function:
$(document).ready(function () {
var doc = $(document);
if (frames.length > 0) {
doc = frames[0].document;
$(doc).find('script').each(function () {
var script = document.createElement("script");
if ($(this).attr("type") != null) script.type = $(this).attr("type");
if ($(this).attr("src") != null) script.src = $(this).attr("src");
script.text = $(this).html();
$(doc).find('head')[0].appendChild(script);
$(this).remove();
});
}
});
I have a user enter a value in a form and onClick() activates a function that takes the URL the user pasted and cuts it down (using an algorithm I made, but that is irrelevant). I end up with a string of 11 characters and im not sure how to get this to a php page that submits it to my database. The way i am doing it now takes the browser to a new page and i want the user to stay on the same page.
function findvideoid(){
window.location.href = 'submitvid.php?videoID=' + videoID;
}
Pure JavaScript solution (recommended):
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyStatus == 4) { // finished
if (xhr.status == 200) { // 200 HTTP code returned by server
}
else { // error
}
}
};
xhr.open("GET", "your-script.php?videoID=" + encodeURIComponent(videoID));
xhr.send(null);
jQuery solution (recommended if you already use jQuery in your project or if you want to try it out):
// PHP script can access $_GET['videoID']
jQuery.get("your-script.php?videoID=" + encodeURIComponent(videoID));
// PHP script can access $_POST['videoID']
jQuery.post("your-script.php", {videoID: videoID});
jQuery.get( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
jQuery.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
What about masking the actual ajax call with the loading of an external html resource?
If no real callback is expected, you could inject an iframe into the document pointing to the specified url and then remove it from the document.
Here's an example of accessing your backend's api url masked by loading an image:
function findvideoid(id, callback){
var img = new Image();
img.onload = callback;
img.src = apiUrl + '?videoId=' + encodeURIComponent(id)
+ '&antiCache=' + new Date().getTime();
}
No ajax. No other libs. Google does it for it's analytics. Why shouldn't you?
Use AJAX:
function findvideoid()
{
var html = $.ajax({
type: "POST",
url: "submitvid.php",
data: "videoID=" + videoID,
async: false
}).responseText;
if(html == "success")
{
// Uncomment the following line in your application
//return true;
}
else
{
return false;
}
}
You can do this easily in jQuery
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
I want to send http request for fetching finance.yahoo stock data with url like : http://finance.yahoo.com/d/quotes.csv?s=GAIL.NS+BPCL.NS+%5ENSEI&f=snl1hgp which returns a csv file. I want to read the response data and fill it in a listview using Javascript or JQuery mobile. None of the links I referred helped me.
I tried using the following code:
$.ajax({
type: "GET",
url: "http://finance.yahoo.com/d/quotes.csv",
data: "s=GAIL.NS+BPCL.NS+%5ENSEI&f=snl1hgp",
dataType: "text/csv",
success: function(data) {
alert(JSON.stringify('data is :' + data));
}
});
I get blank data as alert.
Any sample code or useful link would be appreciated.
I think that the problem is the request is cross domain. There is another question about this here:
Cross-Domain get CSV file
and another answer here :Yahoo JSONP Ajax Request Wrapped in callback function
and a working example here: Displaying ajax results from yahoo finance using underscore.js
Here is a working jsfiddle which makes a jsonp request to d.yimg.com to get the data http://jsfiddle.net/gp6zL/
YAHOO.Finance.SymbolSuggest.ssCallback = function (data) {
alert(JSON.stringify(data));
};
var query;
query = 'Google';
if (query.length > 0) {
$.ajax({
type: "GET",
url: "http://d.yimg.com/autoc.finance.yahoo.com/autoc",
data: {
query: query
},
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "YAHOO.Finance.SymbolSuggest.ssCallback",
});
}
I try to take jQuery out of the equation. The following code will work as long as you whitelist "finance.yahoo.com".
var request = new XMLHttpRequest();
request.open("GET", "http://finance.yahoo.com/d/quotes.csv?s=GAIL.NS+BPCL.NS+%5ENSEI&f=snl1hgp", true);
request.onreadystatechange = function() {//Call a function when the state changes.
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
console.log(request.responseText);
}
}
}
request.send();