Click on HTML element on iframe [duplicate] - php

This question already exists:
Closed 11 years ago.
Possible Duplicate:
Get xpath location of element in iframe(iframe from my domain)
I have a javascript function to get xpath as result (getXPath) and below is the code. Also I have a an external site in iframe but I show him when I use proxy (code is below). And I have a jquery function to show me xpath when I click on some element in iframe but Dont work. What is problem:
CODE:
<?php
error_reporting(E_ALL ^ E_NOTICE);
$url = $_GET['url'];
if( ! empty($url))
{
$data = file_get_contents($url);
$data = str_replace('<head>', '<head><base href="'.$url.'" /></base>', $data);
$data = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $data);
$data = preg_replace('#<iframe(.*?)></iframe>#is', '', $data);
$data .=
'
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$("div").each(function(i){
if($(this).css("position") == "fixed") $(this).css("display", "none");
});
</script>
'
;
die($data);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="author" content="Webarto" />
<title>AdriaMart</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
//function for xpath location
<script type="text/javascript">
function getXPath(node, path) {
path = path || [];
if(node.parentNode) {
path = getXPath(node.parentNode, path);
}
if(node.previousSibling) {
var count = 1;
var sibling = node.previousSibling
do {
if(sibling.nodeType == 1 && sibling.nodeName == node.nodeName) {count++;}
sibling = sibling.previousSibling;
} while(sibling);
if(count == 1) {count = null;}
} else if(node.nextSibling) {
var sibling = node.nextSibling;
do {
if(sibling.nodeType == 1 && sibling.nodeName == node.nodeName) {
var count = 1;
sibling = null;
} else {
var count = null;
sibling = sibling.previousSibling;
}
} while(sibling);
}
if(node.nodeType == 1) {
path.push(node.nodeName.toLowerCase() + (node.id ? "[#id='"+node.id+"']" : count > 0 ? "["+count+"]" : ''));
}
return path;
};
</script>
//function to get xpath location and write in textfield in focus
***<script>
$('#iframe').ready(function () {
var selectedtextbox;
$('input[name="myinput"]').focus(function(){selectedtextbox=$(this);});
$('div, p, li, a, href').click(function () {
var xpath = getXPath(this);
selectedtextbox.val(xpath)
});
});
</script>***
<style type="text/css">
<!--
iframe{width:100%;height:400px;}
-->
</style>
</head>
<body>
<!-- ... -->
<input id="iframe_url" name="" type="text" />
<input id="iframe_button" name="" type="button" />
<iframe id="iframe" src="?url=http://kupime.com"></iframe>
<script type="text/javascript">
document.getElementById('iframe_button').onclick = function () {
document.getElementById('iframe').src = '?url=' + document.getElementById('iframe_url').value;
};
</script>
<!-- ... -->
//Textfields for xpath location to write inside them
<input id="" name="myinput" type="text" value="">
<input id="" name="myinput" type="text" value="">
<input id="" name="myinput" type="text" value="">
</body>
</html>
***
$('#iframe').ready(function () {
var selectedtextbox;
$('input[name="myinput"]').focus(function(){selectedtextbox=$(this);});
$('div, p, li, a, href').click(function () {
var xpath = getXPath(this);
selectedtextbox.val(xpath)
});
});
</script>***

There are 3 issues.
the iframe-element is not accessible at this point(the function is placed above the iframe, the #iframe-element is still unknown)
ready will fire when the current document is ready, not the document within the iframe. Use load instead
you need to set the document within the iframe as context-argument
//wait for ready in the current document to have access to #iframe
$(function()
{
$('#iframe')
//observe the load-event of the iframe-element
.on('load',
function ()
{
//set a default-input to avoid errors
var selectedtextbox=$('input[name="myinput"]:eq(0)');
$('input[name="myinput"]')
.focus(function(){selectedtextbox=$(this);});
//Note the 2nd argument here,
//it sets the contextof $() to the document inside the iframe
$('div, p, li, a, href',
this.contentWindow.document)
.click(function ()
{
var xpath = getXPath(this);
selectedtextbox.val(xpath)
});
});
});

Related

jQuery doesn't load content of page in Div

I have this page, terms.php with this content:
<label>
<span>
<a id="terms" href="/terms.php">Terms</a>
</span>
<input type="checkbox" name="terms" /> I Accept
</label>
<div id="content-area"></div>
<script>
jQuery.fn.terms_agree = function(content_area, selector) {
var body = $(body);
$(this).click(function() {
body.css("height", "auto").css("height", body.height()); // Prevent page flicker on slideup
if ($(content_area).html() == "") {
$(content_area).load( $(this).attr("href") + (selector ? " " + selector : "") );
}
$(content_area).slideToggle();
return false;
});
}
$(function() {
$("#terms").terms_agree("#content-area");
});
</script>
On terms.php i have:
<html>
<head>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
</head>
<body>
TEST TEST TEST
</body>
</html>
When I click on the link "Terms", a div is loaded which is totally blank. I checked the url to terms.php and that is working fine. Also terms.php is showing content when I visit it directly.
What is going wrong?

How to add two Google Place Autocomplete search boxes in one page? [duplicate]

This question already has answers here:
Google Maps API autocomplete 2nd address fields on same page
(3 answers)
jQuery and google maps auto complete
(2 answers)
Closed 3 years ago.
I am trying to add two Google Maps Autocomplete search boxes in one html page. However, the moment I copy the same code with same API only one of them works.
<body>
<div class="pac-card" id="pac-card">
<div id="pac-container">
<input id="pac-input" type="text"
placeholder="Enter a location">
</div>
</div>
<div id="map"></div>
<script>
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
var card = document.getElementById('pac-card');
var input = document.getElementById('pac-input');
var types = document.getElementById('type-selector');
var strictBounds = document.getElementById('strict-bounds-selector');
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(card);
var autocomplete = new google.maps.places.Autocomplete(input);
// Bind the map's bounds (viewport) property to the autocomplete object,
// so that the autocomplete requests use the current map bounds for the
// bounds option in the request.
autocomplete.bindTo('bounds', map);
// Set the data fields to return when the user selects a place.
autocomplete.setFields(
['address_components', 'geometry', 'icon', 'name']);
var infowindow = new google.maps.InfoWindow();
var infowindowContent = document.getElementById('infowindow-content');
infowindow.setContent(infowindowContent);
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert("No details available for input: '" + place.name + "'");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindowContent.children['place-icon'].src = place.icon;
infowindowContent.children['place-name'].textContent = place.name;
infowindowContent.children['place-address'].textContent = address;
infowindow.open(map, marker);
});
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function setupClickListener(id, types) {
var radioButton = document.getElementById(id);
radioButton.addEventListener('click', function() {
autocomplete.setTypes(types);
});
}
setupClickListener('changetype-all', []);
setupClickListener('changetype-address', ['address']);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
document.getElementById('use-strict-bounds')
.addEventListener('click', function() {
console.log('Checkbox clicked! New state=' + this.checked);
autocomplete.setOptions({strictBounds: this.checked});
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=My API KEY&libraries=places&callback=initMap"
async defer></script>
I've checked all possible questions in stack with respect to this topic and none of them used an API key which was the main reason for me posting this question. I ran all those codes that I found online but none worked perfectly.
To those who have the same problem as me, Here's the solution..
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Maps API v3 Multiple Autocomplete Inputs</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script
type="text/javascript"
src="/js/lib/dummy.js"
></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=Your API Code &libraries=places"></script>
<style id="compiled-css" type="text/css">
.autocomplete {
width:300px;
}
</style>
<!-- TODO: Missing CoffeeScript 2 -->
<script type="text/javascript">//<![CDATA[
var VanillaRunOnDomReady = function() {
function initialize() {
var acInputs = document.getElementsByClassName("autocomplete");
for (var i = 0; i < acInputs.length; i++) {
var autocomplete = new google.maps.places.Autocomplete(acInputs[i]);
autocomplete.inputId = acInputs[i].id;
google.maps.event.addListener(autocomplete, 'place_changed', function () {
document.getElementById("log").innerHTML = 'You used input with id ' + this.inputId;
});
}
}
initialize();
}
var alreadyrunflag = 0;
if (document.addEventListener)
document.addEventListener("DOMContentLoaded", function(){
alreadyrunflag=1;
VanillaRunOnDomReady();
}, false);
else if (document.all && !window.opera) {
document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>');
var contentloadtag = document.getElementById("contentloadtag")
contentloadtag.onreadystatechange=function(){
if (this.readyState=="complete"){
alreadyrunflag=1;
VanillaRunOnDomReady();
}
}
}
window.onload = function(){
setTimeout("if (!alreadyrunflag){VanillaRunOnDomReady}", 0);
}
//]]></script>
</head>
<body>
<input class="autocomplete" id="ac1" placeholder="Enter your address" type="text">
<br />
<br />
<input class="autocomplete" id="ac2" placeholder="Enter your address" type="text">
<br />
<br />
<input class="autocomplete" id="ac3" placeholder="Enter your address" type="text">
<br />
<br />
<span id="log"></span>
<script>
// tell the embed parent frame the height of the content
if (window.parent && window.parent.parent){
window.parent.parent.postMessage(["resultsFrame", {
height: document.body.getBoundingClientRect().height,
slug: "42usv81j"
}], "*")
}
// always overwrite window.name, in case users try to set it manually
window.name = "result"
</script>
</body>
</html>

PHP & AJAX Upload File Fails Some times

I am creating a simple video uploader for an adults site and it works for small files but it doesn't for bigger files. I have not tested what the break line is but I know for sure it works for 5mb or so file and fails for 100mb+ files. In the server I have set the maximum upload size and maximum post size to 1000mb in the php5.ini. Can you spot anything wrong with the code or do you think this is a server problem? The site is being hosted in a linux godaddy server. Here is a link for testing:
http://munchmacouchi.com/upload_sample/upload.php
Here is the code in upload.js:
var handleUpload = function(event){
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
data.append('ajax',true);
for ( var i = 0 ; i < fileInput.files.length ; i++ ){
data.append('file[]',fileInput.files[i]);
}
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(event){
if(event.lengthComputable){
var percent = event.loaded / event.total ;
var progress = document.getElementById('upload_progress');
while(progress.hasChildNodes())
progress.removeChild(progress.firstChild);
progress.appendChild(document.createTextNode(Math.round(percent*100)+' %'));
}
});
request.upload.addEventListener('load', function(event){
document.getElementById('upload_progress').style.display='none';
});
request.upload.addEventListener('error', function(event){
alert('Upload Failed');
});
request.addEventListener('readystatechange', function(event){
if(this.readyState == 4){
if(this.status == 200){
var links = document.getElementById('uploaded');
var uploaded = eval(this.response);
var div, a;
for(var i = 0 ; i < uploaded.length ; i++){
div = document.createElement('div');
a = document.createElement('a');
a.setAttribute('href','files/'+uploaded[i]);
a.appendChild(document.createTextNode(uploaded[i]));
div.appendChild(a);
links.appendChild(div);
}
}else{
console.log("Server replied with HTTP status " + this.status);
}
}
});
request.open('POST','upload.php');
request.setRequestHeader('Cache-Control', 'no-cache');
document.getElementById('upload_progress').style.display='block';
request.send(data);
}
window.addEventListener('load',function(event){
var submit = document.getElementById('submit');
submit.addEventListener('click',handleUpload);
});
and for upload.php:
<?php
if(!empty($_FILES['file'])){
foreach($_FILES['file']['name'] as $key => $name){
if($_FILES['file']['error'][$key] == 0 && move_uploaded_file($_FILES['file']['tmp_name'][$key], "files/{$name}")){
$uploaded[] = $name;
}
}
if(!empty($_POST['ajax'])){
die(json_encode($uploaded));
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Upload Test</title>
<h3>Upload Test</h3>
<script type="text/javascript" src="upload.js"></script>
<style type="text/css">
#upload_progress {display:none;}
</style>
</head>
<body>
<div id="uploaded">
<?php
if(!empty($uploaded)){
foreach($uploaded as $name){
echo '<div>', $name , '</div>';
}
}
?>
</div>
<div id="upload_progress"></div>
<div>
<form action="" method="post" enctype="multipart/form-data">
<div>
<input type="file" id="file" name="file[]" multiple="multiple"/>
<input type="submit" id="submit" value="Upload"/>
</div>
</form>
</div>
</body>
</html>

jQuery Dropdown Menu + PHP - keeping selection

I'm not very experienced at JS (PHP is my strong side) so I need your help about something.
I have a script with 2 drop down menus that shows hidden content. I'm using this example Change content based on select dropdown id in jquery
When I execute a PHP script, it checks for errors and if there are some it will return the user to the form. The problem with this is that it will not show the hidden content. I can set some sort of PHP vars and put them in the input like $selected_one = 'selected="selected"' and the dropdown menus will have the right selection, but the jQuery function does not work like that. I think it puts some sort of class that shows and hides the content.
I can't quite put my finger on what's going on, so I need your help. Can any body give me a hint how to fix this?
Here's some code to make things visual
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<style>
.list_publish, .list_news, option_value {
display: none;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<body>
<?php
$selected_news = '';
$selected_review = '';
$selected_news_text = '';
$selected_news_video = '';
if(isset($_POST['submit_news_text'])){
$selected_news = 'selected="selected"';
$selected_news_text = 'selected="selected"';
$news_title = $_POST['news_title'];
// Checks blank forms and return error
if(empty($news_title)) {
$error_message = 'This field must not be empty!';
$proceed = false;
} else {
$proceed = true;
}
}
if($proceed){
// do stuff
echo 'do stuff';
} else {
?>
<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<select class="change_publish" name="publish_type" id="publish_type" style="width: 238px;">
<option value="publish_type" data-title="choose">Publishing...</option>
<option value="publish_news" data-title="news" <?php echo $selected_news ?>>Publish News</option>
<option value="publish_review" data-title="review" <?php echo $selected_review ?>>Publish Review</option>
</select>
<div class="list_publish publish_type">
</div>
<div class="list_publish publish_news">
<select class="change_news" name="news_type" id="news_type" style="width: 238px;">
<option value="news_type" selected="selected" data-title="choose">News Type</option>
<option value="news_text" data-title="text" <?php echo $selected_news_text; ?>>Text</option>
<option value="news_video" data-title="video"<?php echo $selected_news_video; ?>>Video</option>
</select>
<div class="list_news news_type">
</div>
<div class="list_news news_text">
<input name="news_title" type="text" id="news_title">
<input name="submit_news_text" type="submit" value="Publish" id="submit_news_text" />
</div>
<div class="list_news news_video">
> This function is not available at the moment.
</div>
</div>
<div class="list_publish publish_review">
> This function is not available at the moment.
</div>
</form>
<?php
echo $error_message;
}
?>
<script>
// дропдаун меню
$('.change_publish').change(function(){
var selected = $(this).find(':selected');
$('.optionvalue').fadeOut(function(){
$('.optionvalue').html(selected.html()).fadeIn()
.attr('class', 'optionvalue '+selected.val());
});
var count = $('.list_publish').length;
$('.list_publish').slideUp(function(){
if(!--count) {
$('.'+selected.val()).slideDown();
}
});
});
$('.change_news').change(function(){
var selected = $(this).find(':selected');
$('.optionvalue').fadeOut(function(){
$('.optionvalue').html(selected.html()).fadeIn()
.attr('class', 'optionvalue '+selected.val());
});
var count = $('.list_news').length;
$('.list_news').slideUp(function(){
if(!--count) {
$('.'+selected.val()).slideDown();
}
});
});
</script>
</body>
</html>
And here's a demo http://www.demirevdesign.com/public/form.php
Trigger the change event on document load, like here:
<script>
// дропдаун меню
$('.change_publish').change(function(){
var selected = $(this).find(':selected');
$('.optionvalue').fadeOut(function(){
$('.optionvalue').html(selected.html()).fadeIn()
.attr('class', 'optionvalue '+selected.val());
});
var count = $('.list_publish').length;
$('.list_publish').slideUp(function(){
if(!--count) {
$('.'+selected.val()).slideDown();
}
});
}).change(); // HERE THE CHANGE
$('.change_news').change(function(){
var selected = $(this).find(':selected');
$('.optionvalue').fadeOut(function(){
$('.optionvalue').html(selected.html()).fadeIn()
.attr('class', 'optionvalue '+selected.val());
});
var count = $('.list_news').length;
$('.list_news').slideUp(function(){
if(!--count) {
$('.'+selected.val()).slideDown();
}
});
}).change(); // HERE THE CHANGE
</script>

Use javascript to force a textarea to scroll to end

I'm making an instant chat service using PHP and Async javascript. Messages are taken from a database and placed into a text area. The problem is that when messages require the textarea to scroll the setInterval() function used to check and grab new messages forces the text area back to the top of its scrolling height.
I've seen a few solutions and none have worked so far. I tried setting the scrollTop to equal the scrollHeight, but to no avail.
Here's some code:
window.onload = function()
{
if(getUrlVars()['to'] != null)
setInterval(GetMessages, 1000);
}
function ToServer(cmd, data)
{
xmlObj = new XMLHttpRequest();
xmlObj.open('POST','handler.php',true);
xmlObj.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlObj.send(cmd + data);
xmlObj.onreadystatechange = function()
{
if(xmlObj.readyState == 4 && xmlObj.status == 200)
{
if(cmd == 'cmd=push')
{
document.getElementById('pushResponse').innerHTML = xmlObj.responseText;
}
if(cmd == 'cmd=pop')
{
document.getElementById('messages').value += xmlObj.responseText;
}
}
}
}
function GetMessages()
{
// Grab account hash from auth cookie
aHash = readCookie('privateChat');
to = getUrlVars()['to'];
ToServer('cmd=pop','&account=' + aHash + '&to=' + to);
textArea = document.getElementById('messages');
textArea.scrollTop = textArea.scrollHeight;
}
And here's the HTML:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Private Chat</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div>
<h2>Conversation with {%RECIPIENT%}</h2>
<div id="fieldContainer">
<textarea col="10" rows="5" name="messageBox" id="messages"></textarea>
</div>
</div>
<div>
<legend>Message</legend>
<div id="fieldContainer">
<input type="text" id="msgBox">
</div>
</div>
<div>
<input type="button" name="fSend" value="Send message" onClick="SendMessage();">
</div>
<div id="pushResponse">Response</div>
<script src="Chat.js"></script>
</body>
</html>
Thanks!

Categories