ajax check if link is on website - ajax

I'm looking for a way to check if a link exists on a certain page. I know that this is possible with a ping, but I really don't know how to do this.
What I have is a list of links to other webpages, they should have a backlink to my page also. I want to check this, when the backlink is there, a text should appear, something like "ok" and when the result is negative, something like "no backlink"
I know the urls of the pages where my link should appear, in case you need to know that.
Any help would be great!
I have found a piece of code wich I think could be used to serve my needs. I self don't know how, but it would be great if anyone can help me with this.
This is the code:
<html>
<head>
<script language="javascript" type="text/javascript">
<!--
var ajax = new XMLHttpRequest();
function pingSite() {
ajax.onreadystatechange = stateChanged;
ajax.open('GET', document.getElementById('siteToCheck').value, true);
ajax.send(null);
}
function stateChanged() {
if (ajax.readyState == 4) {
if (ajax.status == 200) {
document.getElementById('statusLabel').innerHTML = "Success!";
}
else {
document.getElementById('statusLabel').innerHTML = "Failure!";
}
}
}
-->
</script>
</head>
<body>
Site To Check:<br />
<input type="text" id="siteToCheck" /><input type="button" onclick="javascript:pingSite()" />
<p>
<span id="statusLabel"></span>
</p>
</body>

You can't natively use Javascript to parse external domains, I used a proxy page which sniffs the content and feeds it to the ajax callback.
My solution basically grabs the source of the site to check and sees if a string, which can be your site link matches. I would assume this should be sufficient rather than trying to parse and look for anchors, but you can be as thorough as you want ( parse the whole thing as a DOM element and look for href attribute value ).
Let me know if you run into any issues.
<?php
$query = isset($_POST['submitted']) ? true : false;
if ( $query ) {
$url = #file_get_contents( $_POST['site-url'] );
if ( $url && strlen( $url ) > 0 ) {
$checkFor = $_POST['check-for'];
$match = preg_match( '/' . $checkFor . '/', $url );
echo $match ? 'string (link) is found' : 'string not found';
} else {
echo 'could not connect to site..';
}
exit;
}
?>
<form action="" id="site-checker">
<div class="field">
<label for="site-url">Site to check:</label>
<input id="site-url" name="site-url" value="http://jquery.com">
</div>
<div class="field">
<label for="check-for">Check for:</label>
<input id="check-for" name="check-for" value="docs.jquery.com">
</div>
<input type="hidden" name="submitted" value="true">
<input type="submit">
</form>
<div id="result"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
$('#site-checker').submit(function(e) {
e.preventDefault();
$.ajax({
url:'check.php',
type:'POST',
data:$('#site-checker').serialize(),
success:function(html) {
$('#result').html( html );
}
});
});
</script>

IMHO it would be better to perform this task in a server side script. Depending on your platform there might be functions for sending HTTP requests and HTML parsing which is what you need here. Javascript has cross domain restrictions which will prevent you from sending ajax requests to different domains than the one that is hosting the web page.

Related

Get the place_id of a city using google places autocomplete

I'm using an input field with google places autocomplete. I' ve set autocomplete to predict only cities but I'm stuggling to find a simple way to get the unique place_id of the selected city. I don't want to use it with google maps. I need it just to identify with a unique value the selected city.. Thanks in advance..
Here's my JS:
<script src="maps.googleapis.com/maps/api/js?libraries=places"; type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var options = { types: ['(cities)'] };
var input = document.getElementById('searchCity');
var autocomplete = new google.maps.places.Autocomplete(input,options);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
And here's my PHP:
<form method="GET" action=<?php echo $_SERVER['PHP_SELF'];?>>
<input id="searchCity" type="text" size="50"
placeholder="Enter a City" autocomplete="on" name="city">
<br>
<?php if (!empty($_GET['city']) ) {
echo $_GET['city'];
} else {
echo "not set";
}
unset($_GET['city']); ?>
</form>
<!-- Here I would like to show the place_id of the selected city-->
</div>
You don't need PHP to display the place details. You just need a Javascript event handler for place_changed.
E.g. add this code to your initialize function:
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
var form = input.parentElement;
form.appendChild(document.createTextNode("Place ID is " + place.place_id));
});
These samples from Google's docs contain complete examples of using the place_changed event. They're worth looking at:
https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete
https://developers.google.com/maps/documentation/javascript/examples/places-placeid-finder

google.maps.places.Autocomplete requests Location too many times in Firefox

in my website, I have a singn_up-form and use the Google-Api to give the user some suggestions. The API requests the location of the user once in Internet-Explorer. But if I try Firefox, the requests are looped until I click "Standort immer Freigeben" - it means "always accept".
function initialize() {
autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')),
{ types: ['geocode'] });
}
The code is loaded at document.ready and contains more code, but this snippet also reproduces the error.
Does anyone has some ideas?
Try this :
put the apis in your <head></head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&libraries=places"></script>
put this in your body tag:
<label for="autocomplete">Please Insert an address:</label>
<br>
<input id="autocomplete" type="text" size="100">
put this in your onload function:
var input = document.getElementById('autocomplete');
new google.maps.places.Autocomplete(input);
this is my code :
var input = document.getElementById('autocomplete');
new google.maps.places.Autocomplete(input);
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&libraries=places"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<label for="autocomplete">Please Insert an address:</label><br>
<input id="autocomplete" type="text" size="100">
</body>
</html>
You might have kept some onfocus attribute as given in Google Maps API Example
<input id="autocomplete" placeholder="Enter your address" onFocus="geolocate()" type="text"></input>
OR
If you don't require keeping bounds for places suggestions, you may want to remove it
OR
If you need to set bounds for suggestions keep some condition to not call location consent every time, if user gives permission.
Please keep your condition in geolocate() function
Issue is happening only in Mozilla FireFox
What you want to do is this:
function handlePermission() {
navigator.permissions.query({name:'geolocation'}).then(function(result) {
if (result.state == 'granted') {
geoBtn.style.display = 'none';
} else if (result.state == 'prompt') {
geoBtn.style.display = 'none';
navigator.geolocation.getCurrentPosition(revealPosition,positionDenied,geoSettings);
} else if (result.state == 'denied') {
geoBtn.style.display = 'inline';
}
});
}
then put handlePermission(); after your callback function receives permission

Blank page after submitting external HIT in MTurk

If I submit my external HIT with the https://workersandbox.mturk.com/mturk/externalSubmit URL, it gets succesfully submitted to MTurk (in my requester Sandbox, i can see the result), but for the worker an empty / blank page appears, instead of the confirmation, that her/his HIT got submitted succesfully...
I guess, something with the action-parameter in my form could be wrong...
The HTML-Code of this blank page looks like:
<html><head>
<title><bean:message key="external_submit.title" /></title>
<script type="text/javascript">
function reloadOuterPage() {
var boxes = top.document.getElementsByName('autoAcceptEnabled');
if( boxes.length == 0 || !boxes[0].checked ) {
top.location = top.document.getElementById('hitExternalNextLink').href;
} else {
top.location = top.document.getElementById('hitExternalNextAcceptLink').href;
}
};
</script>
</head>
<body onload="reloadOuterPage();"><bean:message key="external_submit.body">
</bean:message></body></html>
The form I'm submitting:
<form target="_parent" name="hitForm" style="visibility:hidden" id="hitForm" method="POST"
action="https://workersandbox.mturk.com/mturk/externalSubmit">
<input type="hidden" id="assignmentId" name="assignmentId">
<input type="hidden" id="hitId" name="hitId"/>
<input type="hidden" id="workerId" name="workerId"/>
<input type="hidden" id="caption" name="caption" value="TEST">
<input type="submit" name="Submit" id="submitButton" value="submit" disabled="true">
</form>
<button ng-show="!hasAccepted()" disabled>You must first accept the HIT in order to Submit it!</button>
<button ng-click="submitHit(inputText)" ng-show="hasAccepted()">Submit</button>
where the submitHit Method looks like this (the ids get assigned properly - i checked that):
$scope.submitHit = function (cap) {
$scope.form = document.getElementById("hitForm");
$scope.assignmentId = "";
$scope.hitId = "";
$scope.workerId = "";
$scope.assignmentId = $scope.turkGetParam("assignmentId");
$scope.hitId = $scope.turkGetParam("hitId");
$scope.workerId = $scope.turkGetParam("workerId");
document.getElementById("assignmentId").value = $scope.assignmentId;
document.getElementById("hitId").value = $scope.hitId;
document.getElementById("workerId").value = $scope.workerId;
$scope.form.submit();
}
thank you very much for your help!
As always, one works nearly 2 days on this "bug" and after overcoming to ask on stackoverflow, one finds the solution: I had to delete the target="_parent" in my form and now everything works fine!

How to capture AJAX response?

I have a simple script, in ajax, and I want to capture the return and process it according to the value:
if (xmlhttp.readyState==4) {
if (xmlhttp.responseText == "not available") {
document.write("not available");
}
}
At the same time, I tried this, which worked:
if (xmlhttp.readyState==4) {
document.write(xmlhttp.responseText);
}
What wrong am I doing?
Thank you for your reply. This is my current domain availability checking script which works great:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#dtype').change(function() {
var opt = $('#domain').val();
$.ajax({
type: "POST",
url: "testwhois.php",
data: 'd=' + opt,
success:function(data){
$('#txtHint'). html(data);
}
});
});
});
</script>
</head>
<body>
<form> Domain name : <input type="text" name="domain" id="domain"> <input type="radio" name="dtype" id="dtype" value="new">New <input type="radio" name="dtype" value="transfer">Transfer <span id="txtHint"></span> </form>
</body>
</html>
However, I want to have two things in it:
a preloader image (I have it) while the script is working in the place of 'txtHint' where the answer will be displayed.
The answer is returned in the format of "not available" or available". I want to make the 'domain' field blank, when the answer is returned as "not available" with the html codes.
Thanks again.
Forgive me if you know this already, but in case you don't:
Ajax posts data to an external php file, which processes the data it receives, and sends back an answer. It looks like this:
FILE #1:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#Sel').change(function() {
var opt = $(this).val();
var someelse = 'Hello';
var more_stuff = 'Goodbye';
$.ajax({
type: "POST",
url: "receiving_file.php",
data: 'selected_opt=' + opt + '&something_else=' +someelse+'&more_stuff='+more_stuff,
success:function(data){
alert('This was sent back: ' + data);
}
});
});
});
</script>
</head>
<body>
<select id = "Sel">
<option value ="Song1">default value</option>
<option value ="Song2">Break on through</option>
<option value ="Song3">Time</option>
<option value ="Song4">Money</option>
<option value="Song5">Saucerful of Secrets</option>
</select>
FILE #2: receiving_file.php
<?php
$recd = $_POST['selected_opt'];
echo 'You chose: ' . $recd;
The above example works. If you copy/paste it into two files, you will see AJAX in action. Of course, the server side scripting is in PHP, so your server needs to handle that. If necessary, download XAMPP and install it on your local computer. Place these two files in the htdocs folder and, in the browser address bar, type:
http://localhost/whatever_you_called_the_first_page.php
As you can see, it is much simpler to write AJAX code using jQuery. All that is needed is the jQuery library (usually in the header tags, as in code example above), and the AJAX code block.
Here are some other examples to study:
More complicated example
Populate dropdown 2 based on selection in dropdown 1

prototype ajax updater div with different buttons

i'm learning it, but i cant find what's wrong in this!
i want the div2 to get data from the form in div1, called formulario.
i would like to know which item is selected and which button was clicked.
main html file:
<script src="utils/Scripts/prototype.js" type="text/javascript"></script>
<script type="text/javascript">
function sendf(formul, divi, php)
{
var params = Form.serialize($(formul));
new Ajax.Updater(divi, php, {method: 'post', parameters: params, asynchronous:true});
}
</script>
</head>
<body>
<div id="div1">
contenido div1
<form id="formulario" method="POST">
<select size="3" id="lista" onchange="sendf('formulario', 'div2', 'prodiv1.php');">
<option>elemento 1</option>
<option>elemento 2</option>
<option>elemento 3</option>
</select>
<input type="button" id="b1" value="bot1" onclick="sendf('formulario', 'div2', 'prodiv1.php');" />
<input type="button" id="b2" value="bot2" onclick="sendf('formulario', 'div2', 'prodiv1.php');" />
</form>
<div id="div2" style="background: blue;">
contenido div2
</div>
</div>
</body>
</html>
the php file, prodiv1.php:
<?
echo 'exec: prodiv1.php<br>';
print_r($_POST);
echo serialize($_POST);
if (isset($_POST))
{
foreach ($_POST as $key=>$value)
{
echo $key.'=>'.$value."<br>";
}
}
echo "select: ".$_POST['lista'];
if (isset($_POST['b1'])) {echo 'click: boton1';} else {echo 'click: boton2';}
?>
i've tried a lot of things, and seen that it could be done with event observers, httprequests and such, but what i need is quite easy, and probably there's an elegant way to solve it...
i thank in advance any help!
have a nice day.
guillem
if you dont need to actually process the form contents in some way then you have no need to use Ajax to pass to a PHP script. Depending on what exactly you wanted to display in div 2 you could do something as simple as this:
function sendf()
{
var listvar = $('lista').value;
$('div2').update('select menu value was ' + listvar);
}
This is obviously missing quite a lot of detail and can be massively improved but it should highlight the fact that AJAX is not required.
Edit Looking at the rest of the code you have posted, is AJAX really required for this? surely you are just updating the existing page with data already present on the page, the server has no real part to play in this?
Sorry to dive into jQuery again, but this should allow you to get the values into "div2" without an ajax request.
$(document).ready(function() {
$("input").click(function(e) {
$("#div2").html($(this).attr("id")+" clicked<br />");
updateList();
});
});
function updateList() {
$("#div2").append($("#lista").val() + " selected");
}
In plain English this code says "if an input element is clicked, update the value of div2 with the input variables id, and append the selected value from the list to the result". Hopefully that makes sense to you :)
If you need an easy, elegant way to solve this with AJAX, use the jQuery library's ajax and post methods. For more information take a look here, it will significantly cut down on the size and complexity of your code.

Resources