I used to have a fancybox display a message to users based on the country they were visiting from like so:
<script>
jQuery.ajax({
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
// If the visitor is browsing from United Kingdom.
if (location.country_code === 'GB') {
// Tell him about U.S. store.
jQuery.fancybox.open(jQuery('#messageGB'));
}
}
});
</script>
<div id="messageGB">
<p>You are visiting our U.S. store. </p>
</div>
I was having some problems with fancybox placing cookies so now I am using a jquery pop up which works fine on its own, but it doesn't work if I try to do the country based call... any thoughts on what I am doing wrong?
// If the visitor is browsing from United Kingdom.
if (location.country_code === 'GB') {
// Tell him about U.S. store.
$('#popup_messageGB').popup({
setcookie: true,
cookie_timeout: 0
}
}
});
</script>
<div id="popup_messageGB">
<p>You are visiting our U.S. store. </p>
</div>
Cross Domain Ajax the Easy Way
Cross domain ajax requests need to be done in a specific way, which the web service needs to support. And the geo location service that you are using does support "jsonp" cross domain requests ... so you're in luck.
Note the callback parameter added to the query string. Your code is missing the callback, which is probably why it's not working.
http://freegeoip.net/json/?callback=onGeoLocation
The jQuery documentation explains how to make a jsonp call jQuery.getJSON()
And your jQuery code would looks something like this:
$.getJSON('http://freegeoip.net/json/?callback=?', function(data) {
// your popup here
});
Yet, for something simple like this one doesn't really need jQuery. You only need retrieve the visitor's location once. That can be done by including the web service URL in a normal script tag. And after it loads it will call your function with the returned data.
Update: In response to comment
#RobRob - Just copy the code below, add your popup code, and you're done.
<!doctype html>
<html>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON('http://freegeoip.net/json/?callback=?', function(location) {
// insert your popup code here
alert( location.country_name );
});
});
</script>
</body>
</html>
The example below demonstrates both methods of doing the jsonp call.
Run The Code Snippet to Display Your Country
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<button onclick="getLocation()">jQuery.getJSON</button>
<h2 id="country_name"></h2>
JSON:
<xmp id="stdout" style="border:1px gray solid; background-color:aliceblue;"></xmp>
<script type="text/javascript">
// Method 1: plain Javascript jsonp callback
function onGeoLocation( data ) {
document.getElementById('stdout').innerHTML = JSON.stringify(data,null,' ');
document.getElementById('country_name').innerHTML = 'Country: ' + data.country_name;
// add your popup here
};
// Method 2: Using jQuery
function getLocation() {
$.getJSON('http://freegeoip.net/json/?callback=?', function(data) {
alert( 'jQuery.getJSON\n' + JSON.stringify(data, null, ' '));
// your popup here
});
}
</script>
<!-- This script tag required for method 1 -->
<script type="text/javascript" src="http://freegeoip.net/json/?callback=onGeoLocation"></script>
</body>
</html>
Related
My aim is to get an element <div id="calender"> and all what is in the element shown in a browser. The point is that normal get-html-source won't do the thing. The element what I am looking for does not exists in the html output of php-function file_get_contents.
I have tried to get the source by php with xpath byt the help of http://us3.php.net/manual/en/class.domxpath.php which inludes a nice tool to get what is in any tag in the html page. But the problem here might be that the element (a calender) is formed to the loaded page by javascript and cannot be caught by server side php. So, is there a way I can catch such element (div) by javascript instead.
There are script examples of javascript for this kind of problem (if I have understood them correctly) but currently I cannot get a simple javascript to work. An example below shows how I have tried to built up a code. $ajax thing here is just one path I have tried to solve the problem but don't know how to use it. More here I cannot figure out why the simple javascript functions do not work (just test purposes).
<!doctype html>
<html lang="fi">
<head>
<meta charset="utf-8">
<title>load demo</title>
<style>
body {
font-size: 12px;
font-family: Arial;
}
</style>
<script type="text/javascript">
function ok {
alert "OK";
}
function get_html (my_html){
alert "OK";
var l = document.getElementById('my_link').value;
alert l;
alert my_html;
var url = my_html;
$.ajax({
url: url,
dataType: 'html'
success: function(data){
//do something with data, which is the page 1.html
var f = fs.open("testi_kalenteri.html", "w");
f.write(data);
f.close();
alert "data saved";
}
});
}
</script>
</head>
<body>
<p id ='my_link' onclick='get_html("lomarengas.fi/en/cottages/kuusamo-rukasaukko-9192")'>html-link</p>
<p id ='ok' onclick='ok()'>show ok</p>
</body>
</html>
Briefly, I have a link to a web page, which shows up a (booking) calendar in it but this calendar is missing in the "normal" source code, by file_get_contents (php). If I browse the html source with Chromes tools (F12) I can find the calendar there. T want that information get by javascript or by php or such.
If you read the source code of the page you point to (http://www.yllaksenonkalot.fi/booking/varaukset_akas.php), you notice that the calendar is loaded via an iframe.
And that iframe points to that location :
http://www.nettimokki.com/bookingCalendar.php?id_cottage=3629&utm_source=widget&utm_medium=widget&utm_campaign=widget
Which is in fact the real source of the calendar...
EDIT following your comment on this answer
Considering the real link : http://www.lomarengas.fi/en/cottages/kuusamo-rukasaukko-9192
If the calendar is not part of the generated html, it is surely asynchronously generated (in javascript, client side).
From this asumption, I inspected the source code (again).
In the developper tools of my browser, in the Network section, where you can monitor what files are loaded, I looked for
calls to server (everything but calls to resources : images, stylesheets...).
I then noticed calls to several urls with json file extensions like http://www.lomarengas.fi/api-ib/search/availability_data.json?serviceNumber=9192¤tMonthFirstDate=&duration=7.
I felt I was on the right track (asynchronous javscript calls to generate html with json datas), I looked for javascript code or files that was not the usual libraries files (jquery, bootstrap and such).
I stumbled upon that file : http://www.lomarengas.fi/resources_responsive/js/destination.js.
It contains the code that generates asynchronously the calendar.
tl;dr
The calendar is indeed generated asynchronously.
You can't get the full html with a curl or file_get_content in PHP and
you can't access it with ajax code (due to Same-origin policy).
By the way, you should contact the site to see if you can access their api via PHP with their consent.
Hope it helped you understand the whole thing...
To get <div id="calender"> you can use next code (jquery):
<div id="calender"></div>
<script>
$("#calendar").click(function(){
alert('calendar was clicked');
});
</script>
If I understand you correctly. I think you need appropriate php respond with some correct code inside php file:
// json_handler.php
<?php
if (is_ajax()) {
$return = $_POST;
$return["ok"]="ok";
$return["json"] = json_encode($return);
echo json_encode($return);
}
function is_ajax()
{
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
and this is script wich is inside html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<a id="click">click</a>
<script>
$("document").ready(function(){
$("#click").click(function(){
var data = {
"request": "request"
};
data=$.param(data);
// alert(data);
$.ajax({
type: "POST",
dataType: "json",
url: "json_handler.php",
data: data,
success: function(data) {
// here you will see echo respond from your php json_handler.php
// also you can add here more javascript (jquery code) to change your page after respond
alert();
}
});
return false;
});
});
</script>
<body>
<html>
http://www.w3schools.com/jquery/jquery_ajax_intro.asp
Trying to create a FAN area on facebook where I need to post all products available only to my facebook fans.
My php file creates plain HTML, which I would like to grab from Facebook end.
How this can be done if this can be done at all?
The following is entire content of my script.js file
$.ajax({
type:"POST",
url:"https://www.mysite.com/includes/facebook_fan_page.php",
data: data,
dataType:"html",
error:function(){},
success:function(response){
$('#products').html(response);
}
})
and here is my index.html
<html>
<head>
[[style.css]]
<script type="text/javascript" src="https://www.mysite.com/js/jquery-
1.8.2.min.js"></script>
[[script.js]]
</head>
<body>
<div class="content">
<div id="products"></div>
</div>
</body>
</html>
I do not know how to write output in to the empty div that I have on my apps index.html page <div id="products"></div>
Also, the app I use on facebook is Static HTML iFrame Tabs, if it makes any difference
Please help
Thanks to you all in advance
My skills of ajax and js are very limited, so please be patient with me on this one.
This is also a method for Ajax Post request, I find it simple. Tell me if you find this useful
In HTML Page
In script file or tag
$.POST("filename.php", data, function(response) {
if(!response) {
alert("Oh Snap! I hate this part");
}
else {
$("#div").html(response.field);
}
});
Read about his here AJAX POST REQUEST
I want to execute php file in javascript function. Code is as shown below:
<a id="cancel" href="./?&_action=list" onclick="javascript:clearRecord();return rcm.command('list','',this,event)">Cancel</a>
<script language="javascript" type="text/javascript">
var u1='michael';
function clearRecord() {
$(function() {
location.href = 'clear.php?h='+u1;
});
}
</script>
But when I click to cancel button, clear.php not executed. How I should come out from this?
full & working answer to your question:
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script language="javascript">
function cancelClicked() {
// function below will run clear.php?h=michael
$.ajax({
type: "GET",
url: "clear.php" ,
data: { h: "michael" },
success : function() {
// here is the code that will run on client side after running clear.php on server
// function below reloads current page
location.reload();
}
});
}
</script>
</head>
<body>
<a id="cancel" href="#" onclick="cancelClicked()">Cancel</a>
</body>
</html>
if you want to just execute some php and leave current page to the one generated by this php script. then you got it almost right.
I do not see that you are using jquery - so skip this "$(function(){})" part, and i don't see what u1 is added for but this will work:
function clearRecord() { location.href = 'clear.php'; }
and this will do the same:
Cancel
BUT if you want only to run "clear.php" and then reload current page.
One way of doing it can be putting at the end of your "clear.php" file something like:
header("Location:/");
(it will work only if clear.php does't write anything in response).
But you can do it other ways:
- using AJAX - call clear.php with jQuery.get() and call location.reload() on success;
- using IFRAME - set iframe's location to clear.php and then call window.location.reload();
- using IMG - set img.src to clear.php ...
...and possibly many other ways :)
The Ajax below is on a file with a Facebook Like button. The Like button works correctly. I am trying to use the Ajax below to execute some PHP on a file called fblike.php when the Facebook Like button is clicked. It's not working. Is there any way I can check to see if FB.Event.subscribe('edge.create', function(response) {}); is actually firing?
Thanks in advance,
John
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script >
FB.Event.subscribe('edge.create', function(response) {
$.ajax({
url: "fblike.php", // the url of your php script
context: document.body,
success: function(){
// if you want something to be executed when a result comes back
}
});
});
</script>
</head>
<body>
?>
Yes, use firebug or the inspection tool in chrome/safari, or even IE Developer toolbar. Navigate to the NET tab, and see if any requests are sent to 'fblike.php', alernatively add console.log or alert() messages to both success, and error callbacks.
I wanna use Facebook's Like button on my web site.
It's so simple as everyone knows but I have a problem with the censorship in our country.
Facebook is censored in our country and if I use the simple iframe, the people who have no access to Facebook (can't pass the censorship) will see the block page which I don't want to.
So I wanna check if loaded address is Facebook show them the iframe else (they will be redirected to another web site) hide the iframe.
Is there any way for me to find this out? I mean anything like address or content or id etc.
Here is my code:
<html>
<head>
<title>facebook test</title>
<style>
.facebook{
display:none;
}
</style>
<script type="text/javascript" src="jquery.js"></script>
</head>
<script type="text/javascript">
$.ajax({
url: 'https://graph.facebook.com/btaylor?callback=?',
dataType: 'json',
success: function(data) {
$(".faceboock").show();
// alert('success - facebook works');
// alert('data = ' + JSON.stringify(data));
},
error: function() {
alert('error - facebook fails');
}
});
</script>
<div class="faceboock">
<iframe src="http://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fpages%2Fmypage%2F152215541478267&width=292&colorscheme=light&show_faces=true&stream=true&header=true&height=427" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:292px; height:427px;" allowTransparency="true"></iframe>
</div>
It works when client has access to facebook, I mean the "success: function" works but error function doesn't.
The problem is when facebook is not accessible that json never responds.
Is there any way to set a timeout for response or anything else in order to handle the error?
You can't check the content of an iframe that is not on the same domain as your code.
See Same Origin Policy
iframe.src can be checked without restrictions, but does not change when the redirect happens
iframe.contentWindow.location.href does change when the redirect happens, but can't be accessed in your case due to the security restrictions mentioned above
The only way I can think of to test this is:
Do a JSONP call to one of the Facebook APIs (JSONP has no domain restrictions)
Check the response
If these JSONP calls get redirected as well than it will most likely throw an exception instead of returning the expected values (due to the fact that it will try to parse as javascript a response which is most likely a fullhtml page)
Here is a working example using jQuery to do the JSONP call.
It works from my location, could you test it and see if you get the error alert?
You can also go in your browser to the url in the example. If facebook.com gets redirected, but this one doesn't than you'll have to find some other way to check it...