Get user IP from remote script - javascript

I have a page which loads a script from a remote location (say myscript.com.
This scripts makes an Ajax request to a distant API.
How can this API get the visitor's IP address?
If I use request.remote_addr in the request handler, I get the IP from the script's location (myscript.com).

use this api to get all this data as a json who visited your page
{"as":"AS9583SifyLimited","city":"Bengaluru","country":"India","countryCode":"IN","isp":"Sify Limited","lat":12.9833,"lon":77.5833,"org":"Sify Limited","query":"202.191.210.194","region":"KA","regionName":"Karnataka","status":"success","timezone":"Asia/Kolkata","zip":"560099"}
API_Location=' http://ip-api.com/json';
$.getJSON( API_Location)
.done(function( position ) {
if (position.lat && position.lon) {
updateWeather(position);
} else {
updateWeather({"lat":DEFAULT_LAT, "lon":DEFAULT_LON});
}
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
visit this page ip and you can get how to get ip!

Related

MasterCard Payment Gateway API Single Page App

I am using the Mastercard Payment Gateway API for Hosted Session: Mastercard Payment Gateway API Documentation
The integration works as expected on the first load but this has been written into a single page app. When the user goes back a page via the breadcrumbs (using javascript hash to load 'pages'). When the user then returns to the payment 'page' the Mastercard payment api should then be triggered a second time, this does not happen.
The documentation doesn't say if PaymentSession.configure({}) can be sent more than once but I am assuming that is my issue.
I have tried to 'reset' the PaymentSession and reload the session.js javascript but so far have not been able to get this particular case working. I was wondering if there is a way to 'reset' the configure() or if there was another way to approach this?
I would rather not copy and paste my code in as it's a payment integration although it's pretty much line for line the same as the example on the documentation. I would also say that the issue is unrelated my personal code and more towards how Mastercard's Payment API works and the fact that my website is a single page rather than only loading session.js when needed.
I don't like it when the answer is given by the op, but I have a solution:
$.getScript("<mastercard url + version + merchant id>/session.js", function() {
//PaymentSession && PaymentSession.configure();
});
This uses jQuery to load session.js every time the single page payment hash is called. Once the MasterCard payment script has been executed it then runs the PaymentSession.configure().
My company will be eventually moving away from the MasterCard payment api so this is a suitable solution and doesn't add too much to the page load.
I would still be very interested in learning whether or not this script can be reset another way.
install jquery first then do this in your component
declare const PaymentSession: any;
$.getScript(
<"mastercard url/version/merchantId>/session.js",
function () {
if (PaymentSession) {
PaymentSession.configure({
fields: {
// ATTACH HOSTED FIELDS TO YOUR PAYMENT PAGE FOR A CREDIT CARD
card: {
number: "#card-number",
securityCode: "#security-code",
expiryMonth: "#expiry-month",
expiryYear: "#expiry-year",
nameOnCard: "#cardholder-name",
},
},
session: "xxxxxxxxxxxxxxxx",
//SPECIFY YOUR MITIGATION OPTION HERE
frameEmbeddingMitigation: ["javascript"],
callbacks: {
initialized: function (response) {
console.log(response);
// HANDLE INITIALIZATION RESPONSE
},
formSessionUpdate: function (response) {
// HANDLE RESPONSE FOR UPDATE SESSION
if (response.status) {
if ("ok" == response.status) {
console.log(
"Session updated with data: " +
response.session.id
);
//check if the security code was provided by the user
if (
response.sourceOfFunds.provided.card
.securityCode
) {
console.log(
"Security code was provided."
);
}
//check if the user entered a Mastercard credit card
if (
response.sourceOfFunds.provided.card
.scheme == "MASTERCARD"
) {
console.log(
"The user entered a Mastercard credit card."
);
}
} else if (
"fields_in_error" == response.status
) {
console.log(
"Session update failed with field errors."
);
if (response.errors.cardNumber) {
console.log(
"Card number invalid or missing."
);
}
if (response.errors.expiryYear) {
console.log(
"Expiry year invalid or missing."
);
}
if (response.errors.expiryMonth) {
console.log(
"Expiry month invalid or missing."
);
}
if (response.errors.securityCode) {
console.log(
"Security code invalid."
);
}
} else if (
"request_timeout" == response.status
) {
console.log(
"Session update failed with request timeout: " +
response.errors.message
);
} else if (
"system_error" == response.status
) {
console.log(
"Session update failed with system error: " +
response.errors.message
);
}
} else {
console.log(
"Session update failed: " + response
);
}
},
},
interaction: {
displayControl: {
formatCard: "EMBOSSED",
invalidFieldCharacters: "REJECT",
},
},
});
}
}
);

Mixed Content Error (Http/Https)

I have mixed content error, on web site used both http and https protocols.
Here's the error from Chrome console:
Mixed Content: The page at 'https://www.amazon.com/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://www.amazon.com/../?redirect=true'. This request has been blocked; the content must be served over HTTPS.
Here's screenshot with the error: http://prntscr.com/9os5li
Was found some solution like:
Change link from "http://" to "https://" in
Blocked loading mixed active content.
Nothing helped me, because Amazon server drop it all the time when I change link in code or manual from http to https drop it and make it as http.
For example this one Link 2 I can't use here https, because of this I have mixed content error.
Here's my AJAX where I make a call:
$.ajax({
url: "//" + MWS_URL + rest_path,
data: request,
dataType: 'text',
type: 'POST',
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
beforeSend: function(req) {
//req.setRequestHeader("User-Agent", "chrome extension");
req.setRequestHeader("x-amazon-user-agent", "chrome extension");
},
success: function(data){
if (onSuccess) {
onSuccess(data);
}
},
error: function(jqXHR, textStatus, errorThrown) {
if (onError) {
onError(jqXHR, textStatus);
}
}
});
setTimeout(callService, 1000);
}
Request:
requests.push(
$.get(link.URL, function (data) {
if (IsCancel()) {
return;
}
var jdata = $($.parseHTML(data));
var parser = new ProductPageParser(jdata, link.URL);
if (!parser.isValidProduct()) {
console.log(link.URL + " is not a valid product, skipped.");
link.processed = true;
return;
}
// Process associated (linked) product on this page according to user preferences.
crawlLinkedProducts(jdata, link.URL, config);
// Store product into a collection.
var product = getProductForParser(parser, link);
//product.dbRawProductURL = urlRaw;
if (product) {
products.push(product);
}
link.processed = true;
})
);
And as I have parse in parser, here's second level parser. I parsed products on main page:
$(productUrls).each(function (index, link) {
if (!link.processed) {
console.log("Download second level -> " + link.URL);
requests_2level.push(
$.post(link.URL, "", function (data) {
if (IsCancel()) {
return;
}
console.log("End download second level -> " + link.URL);
var jdata = $($.parseHTML(data));
var parser = new ProductPageParser(jdata, link.URL);
if (!parser.isValidProduct()) {
console.log(link.URL + " is not a valid product, skipped.");
link.processed = true;
return;
}
var hackUrl = "//amazon.com/o/ASIN/" + parser.getAsin();
link.URL = hackUrl;
var product = getProductForParser(parser, link);
if (product) {
products.push(product);
}
link.processed = true;
})
);
}
});
Anyone have idea how to fix this problem?
If Amazon keep redirecting you from HTTPS to HTTP then there is nothing you can do about that short of:
Complaining hard enough at Amazon that they fix it or
Using a difference service
Decide whether to use http or https and use the same on for every call.

How to tie bind and load methods?

Loaded content on the page to another page. If the information is read incorrectly, then you should use the bind () method to display a message about it. How to do it?
$("#result").load("university.html");
If you just want to know if the request succeeded, you can use a callback function.
$("#result").load("university.html", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});

jQuery sends OPTIONS instead of POST request to REST on localhost

I am trying to send a form thru POST to my REST Resource (Java) and I am not able to, as my request gets sent as OPTIONS instead. I Know that the REST Resource is fine since it works perfectly while I test it with Poster Firefox.
jQuery/Ajax call:
function loadTwitter(){
arrayTweets = new Array();
var urlTwitter = "http://localhost:8081/streamingvideoservice/services/twitter/retrieveTweets";
$.ajax({
type: "POST",
url: urlTwitter,
contentType: "application/x-www-form-urlencoded",
//accept: "application/json",
data: $("form#mapForm").serialize(),
dataType: "json",
async: false,
success: function (resp, status, xhr) {
$("#message").html("STATUS: " + xhr.status + " " + xhr.statusText + "\n" + resp);
$("#message").hide();
$.each(resp, function() {
$.each(this, function(i, item) {
arrayTweets.push(item);
});
});
displayTweets();
},
error: function(resp, status, xhr){
$("#message").html("ERROR: " + xhr.status + " " + xhr.statusText + "\n" + resp.e);
$("#message").show();
}
});
}
REST Resource:
#POST
#Path("/retrieveTweets")
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Produces("application/json")
public List<Tweet> retrieve(#FormParam("lat") Double Latitude, #FormParam("lon") Double Longitude, #FormParam("rad") Integer Radius, #FormParam("from") String From, #FormParam("to") String To) {
ArrayList<Tweet> lTweets = new ArrayList<Tweet>();
boolean status = false;
Twitter twitter = new TwitterFactory().getInstance();
AccessToken accessToken = new AccessToken(TwitterInterface.ACCESS_TOKEN, TwitterInterface.ACCESS_TOKEN_SECRET);
twitter.setOAuthConsumer(TwitterInterface.CONSUMER_KEY, TwitterInterface.CONSUMER_SECRET);
twitter.setOAuthAccessToken(accessToken);
try {
Query query = new Query("");
GeoLocation geo = new GeoLocation(Latitude, Longitude);
query.setGeoCode(geo, Radius, Query.KILOMETERS);
query.setCount(100);
query.setSince(From);
query.setUntil(To);
QueryResult result;
result = twitter.search(query);
List<Status> tweets = result.getTweets();
for (Status tweet : tweets) {
System.out.println("#" + tweet.getUser().getScreenName() + " - " + tweet.getText() + " - " + tweet.getCreatedAt());
Tweet t = new Tweet();
t.setUser(tweet.getUser().getScreenName());
t.setText(tweet.getText());
lTweets.add(t);
}
}
catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to search tweets: " + te.getMessage());
System.exit(-1);
}
return lTweets;
}
I am using jQuery 1.9.1 and hosting the Resource on Tomcat 6.
Any help is appreciated.
Thanks in advance.
You appear to be making a cross origin Ajax request. This requires that the server provides an Access-Control-Allow-Origin header to grant permission to the site hosting the page containing the JS to read the data.
Something about the request (probably the X-Requested-With header that jQuery adds to Ajax requests) is triggering a preflight request which uses an OPTIONS request to ask the server for permission before making the main request.
You will need to configure the server to provide an OPTIONS response with suitable Access Control headers as per the CORS specification (linked above).
Solved it with a GET instead and passing the parameters in the URI.

JQuery Ajax - How to Detect Network Connection error when making Ajax call

I have some Javascript JQuery code that does an Ajax call to the server every 5 mins, it's to keep the server session alive and keep the user logged in. I'm using $.ajax() method in JQuery. This function seems to have an 'error' property that I'm trying to use in the event that the user's internet connection goes down so that the KeepAlive script continues to run. I'm using the following code:
var keepAliveTimeout = 1000 * 10;
function keepSessionAlive()
{
$.ajax(
{
type: 'GET',
url: 'http://www.mywebapp.com/keepAlive',
success: function(data)
{
alert('Success');
setTimeout(function()
{
keepSessionAlive();
}, keepAliveTimeout);
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('Failure');
setTimeout(function()
{
keepSessionAlive();
}, keepAliveTimeout);
}
});
}
When I run it, I'll get 'Success' popup on the screen in an alert box every 10 seconds which is fine. However, as soon as I unplug the network cable, I get nothing, I was expecting the error function to get called and see a 'Failure' alert box, but nothing happens.
Am I correct in assuming that the 'error' function is only for non '200' status codes returned from the server? Is there a way to detect network connection problems when making an Ajax call?
// start snippet
error: function(XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.readyState == 4) {
// HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText)
}
else if (XMLHttpRequest.readyState == 0) {
// Network error (i.e. connection refused, access denied due to CORS, etc.)
}
else {
// something weird is happening
}
}
//end snippet
You should just add: timeout: <number of miliseconds>, somewhere within $.ajax({}).
Also, cache: false, might help in a few scenarios.
$.ajax is well documented, you should check options there, might find something useful.
Good luck!
Since I can't duplicate the issue I can only suggest to try with a timeout on the ajax call. In jQuery you can set it with the $.ajaxSetup (and it will be global for all your $.ajax calls) or you can set it specifically for your call like this:
$.ajax({
type: 'GET',
url: 'http://www.mywebapp.com/keepAlive',
timeout: 15000,
success: function(data) {},
error: function(XMLHttpRequest, textStatus, errorThrown) {}
})
JQuery will register a 15 seconds timeout on your call; after that without an http response code from the server jQuery will execute the error callback with the textStatus value set to "timeout". With this you can at least stop the ajax call but you won't be able to differentiate the real network issues from the loss of connections.
What I see in this case is that if I pull the client machine's network cable and make the call, the ajax success handler is called (why, I don't know), and the data parameter is an empty string. So if you factor out the real error handling, you can do something like this:
function handleError(jqXHR, textStatus, errorThrown) {
...
}
jQuery.ajax({
...
success: function(data, textStatus, jqXHR) {
if (data == "") handleError(jqXHR, "clientNetworkError", "");
},
error: handleError
});
If you are making cross domain call the Use Jsonp. else the error is not returned.
USE
xhr.onerror = function(e){
if (XMLHttpRequest.readyState == 4) {
// HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText)
selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
}
else if (XMLHttpRequest.readyState == 0) {
// Network error (i.e. connection refused, access denied due to CORS, etc.)
selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);
}
else {
selFoto.erroUploadFoto('Erro desconhecido.');
}
};
(more code below - UPLOAD IMAGE EXAMPLE)
var selFoto = {
foto: null,
upload: function(){
LoadMod.show();
var arquivo = document.frmServico.fileupload.files[0];
var formData = new FormData();
if (arquivo.type.match('image.*')) {
formData.append('upload', arquivo, arquivo.name);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'FotoViewServlet?acao=uploadFoto', true);
xhr.responseType = 'blob';
xhr.onload = function(e){
if (this.status == 200) {
selFoto.foto = this.response;
var url = window.URL || window.webkitURL;
document.frmServico.fotoid.src = url.createObjectURL(this.response);
$('#foto-id').show();
$('#div_upload_foto').hide();
$('#div_master_upload_foto').css('background-color','transparent');
$('#div_master_upload_foto').css('border','0');
Dados.foto = document.frmServico.fotoid;
LoadMod.hide();
}
else{
erroUploadFoto(XMLHttpRequest.statusText);
}
if (XMLHttpRequest.readyState == 4) {
selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
}
else if (XMLHttpRequest.readyState == 0) {
selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);
}
};
xhr.onerror = function(e){
if (XMLHttpRequest.readyState == 4) {
// HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText)
selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
}
else if (XMLHttpRequest.readyState == 0) {
// Network error (i.e. connection refused, access denied due to CORS, etc.)
selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);
}
else {
selFoto.erroUploadFoto('Erro desconhecido.');
}
};
xhr.send(formData);
}
else{
selFoto.erroUploadFoto('');
MyCity.mensagens.push('Selecione uma imagem.');
MyCity.showMensagensAlerta();
}
},
erroUploadFoto : function(mensagem) {
selFoto.foto = null;
$('#file-upload').val('');
LoadMod.hide();
MyCity.mensagens.push('Erro ao atualizar a foto. '+mensagem);
MyCity.showMensagensAlerta();
}
};
here's what I did to alert user in case their network went down or upon page update failure:
I have a div-tag on the page where I put current time and update this tag every 10 seconds. It looks something like this: <div id="reloadthis">22:09:10</div>
At the end of the javascript function that updates the time in the div-tag, I put this (after time is updated with AJAX):
var new_value = document.getElementById('reloadthis').innerHTML;
var new_length = new_value.length;
if(new_length<1){
alert("NETWORK ERROR!");
}
That's it! You can replace the alert-part with anything you want, of course.
Hope this helps.
Have you tried this?
$(document).ajaxError(function(){ alert('error'); }
That should handle all AjaxErrors. I´ve found it here.
There you find also a possibility to write these errors to your firebug console.

Categories