Get a javascript derived dom-tree element - javascript

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&currentMonthFirstDate=&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

Related

How can I prevent an onclick JavaScript from running on page load?

I'm trying to attach a PHP script to a button so when someone clicks on it, I'm sent what page they're on. I have the PHP script written and I'm trying to attach it to a JavaScript onclick call. Here's what I have so far:
<button id="location">Click to reveal the page you're on</button>
<script>
function send_sms() {
var result = '<?php locate_me(); ?>';
console.log('send_sms');
}
document.getElementById('location').addEventListener('click', send_sms, false);
</script>
However, the JavaScript gets called when the page loads - not when the button is clicked - or maybe it's just the PHP that gets run. The console.log command does not get written on page load, but the PHP script is run. Very strange - at least to me.
I'm not proficient with JavaScript, but I thought the addEventListener() would prevent that from happening. What am I doing wrong?
Thanks,
Frank
I'm not sure about what you mean by "revealing what page the user is on", but I'm thinking that's not relevant to the question, you're asking. I'm not too kean on running php scripts on the same file, I'm running my js on. As nice_dev suggested, I would make an ajax call to a seperate php file, in order to get live updates and not having your php variables pre-loaded.
So I would write my code like this:
Your main file:
<?php // Result from your second php file ?>
<script>
// Ajax call
$(document).ready(function(){
$("#location").click(function(){
var result = '<?php echo $variable; ?>';
$.ajax({
url: "somepage.php",
type: "POST",
data: {result:result},
success: function(result){alert(result }});
});
});
</script>
<html>
<body>
<button id="location">Click to reveal the page you're on</button>
</body>
</html>
Your second file, which will handle your ajax request:
<?php
$yourvariable = $POST['result'];
if isset($yourvariable){
// The php code you want to execute
}
?>
I hope this makes sense. Otherwise, I would be happy to elaborate.
In summary, I would try to run your code on 2 files in a circular process.

How to run a python script on remote server by button click on web page?

I have a python program on remote server. I need to create a web page (html code present in same directory as that of python script on server) having a button on clicking which python script should run. One more thing is that we need to choose a file from local machine after which the python script takes that file as input, runs and outputs another file which needs to be displayed on web page.
I don't know what to use javascript or ajax or php to achieve this. I tried out different ways but in vain.
This is the html code I have been trying with...
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
// var file = $('#fileInput')[0].files[0]
var fd = new FormData();
fd.append('fileInput', file);
// console.log(fd)
$.ajax(
{
type: "POST",
url: "./summarize.py",
data: "fd"
success: function (response) {
}
// error: function (response) {}
});
});
});
</script>
</head>
<body>
<h3>Upload reviews file</h3>
<input type="file" id="fileInput" name="fileInput">
<p>Click the "Get summary" button to summarize the reviews.</p>
<button>Get summary</button>
</body>
</html>
I have searched online but no where the answer was specific (I felt so). Since I am new to javascript, I have trouble in following them. Someone kindly explain what is to be done.
Thank you.
I think you can use php exec, to run Python and your summarize.py script.
<?php
// #result array
exec("python summarize.py", $result);
PHP exec will return you result. Also you can use django or other frameworks to run your Python code.

$.post() Get url of php in html

I am making an html script that will use jQuery.post() method in order to use a php script. The post() method needs an url of the php code but my php code is part of the html code
What Url should i use?
<html>
<body>
<button onclick="test()">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
var test = function() {
$('--I DONT KNOW--',{testvar:"hello"});
}
</script>
<?php
$testvar = $_POST['testvar'];
echo $testvar;
?>
</body>
</html>
An empty URL is a relative URL that resolves as the URL of the current page.
$.post("", {testvar:"hello"});
(Keep in mind that since your PHP does nothing with the data except output it, and your JS does nothing with the response, this will have no visible effect outside of the Network tab of your browser's developer tools).

Loading content only

I am using a $_GET function to load content into the website,
what I want to do is add a Loading image into all that mess.
Right now it looks like it opens a whole new page.
Code:
<?php
if (isset($_GET['page']) || isset($_POST['page'])) {
$page = trim(isset($_POST['page']) ? $_POST['page'] : $_GET['page']);
if (preg_match("/a-z/", $page)) {
}
} else {
$page = "index";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body>
<div id="navigation">
<ul class="nav-items">
<li>Home</li>
<li>Test</li>
<li>Beta</li>
</ul>
</div>
<div id="content">
<?
if ($page != '')
include('pages/'.$page . '.php');
else
{
include('pages/error.php');
}
?>
</div>
</body>
</html>
Now, it works perfectly but I'd want it to show a Loading... image while loading the content , and instead of reloading whole page would be great to load the content div ONLY.
I did not try javascript solution since I didn't find anything that would work correctly and would keep the links working (for example http://example.com/index.php?page=test with already loaded the text.php file from pages folder). Plus I'm a real newbie in javascript so I have no idea what to start with.
The only solution to this problem is with JavaScript because PHP will only execute on the server and will only present HTML on the client side.
If you understand the HTTP request/response system, you will know that a request is sent to the server and then the server responds back with the page content, which will be the HTML (and CSS and any client-side scripts such as JavaScript). This method normally means having to reload the page but if you use AJAX (Asynchronous JavaScript and XML), this acts as a layer between the client and the server, allowing the user to request content without having to reload the page.
The most simple way of doing this is with jQuery. Be sure to include the jQuery library and put your code inside the $(document).ready(); function so that it executes when the page has finished loading.
Fortunately, this particular task is fairly simple, although it will require restructuring your website/application slightly. You will need to have the content echoed or printed onto a different page with PHP.
On your main page that will be used and seen by the users, you would simply write $("#container").load("page.html"); where container is the id of the container you want to load the content into.
If you want different content to be loaded with different buttons, you could do this (as long as you give your links the correct ids:
$(document).ready(function() {
$("#alpha").onclick(function() {
$("#container").load('page.html?page=alpha');
});
$("#beta").onclick(function() {
$("#container").load('page.html?page=beta');
});
});
Edit: I'm so sorry, I missed out the important part about the loading image, but the other answer demonstrates this well, so there is no point in repeating it.
It looks like it is opening a whole new page because it is. Your only option would be javascript. If I were wanting to do this, I would always only load the index page with nothing in your content div except the loading icon. Then once the page is loaded have jquery read the get variable and make an ajax request for the content of the page and load it into the div.
<div id="content">
<div id='page'></div>
</div>
Then, to make it easier on you since you are unfamiliar with javascript I would include the following jquery plugin: https://github.com/allmarkedup/purl
then in .js file:
$( document ).ready(function() {
var loading_annimation = "<div class='loading'></div>";
var page = $.url().param("page");
if(page){
$('#page').load(loading_annimation ).load('/special_php_file_that_includes_JUST_content.php?page='+page);
} else {
$('#page').load(loading_annimation ).load('/special_php_file_that_includes_JUST_content.php?page=index');
}
$(document).on('click','.link', function(e){
e.preventDefault();
var page = $(this).attr("data-link");
$('#page').load(loading_annimation ).load('/special_php_file_that_includes_JUST_content.php?page='+page);
});
});
Then you will need to change your links to do something like this:
<a class='link' data-link='beta' href="/index.php?page=beta">Beta</a>

Load external Web Page with jQuery

I was wondering what a good way to load an external web page (same server) would be. I have tried .load() and .get() however, The external page has a php script that spits out information every few seconds, the .load() and .get() only load it after the php is done. I have tried iFrame with does load it displaying the information being outputted by the PHP script. However, I don't really like to use iFrames. Thanks!
If your goal is for the PHP information (that is spit out every few seconds) to be updated on your site, then what you want to do is use AJAX, inside a setInterval routine.
See this post for the basics of AJAX -- it really is simpler than you might think. (You might first want to look at the simple examples linked at bottom).
Once you've got a simple ajax exchange happening, put that into a function called, for example, doAjax() -- and then create a setInterval, like this:
setInterval('doAjax();',60000);
Here is an important note when considering setInterval
Following is a simple copy/paste(able) example that will let you see exactly what I mean:
HTML/javascript: index.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style>
#timeDiv{width:40%;height:200px;background:wheat;padding:10px;}
</style>
<script type="text/javascript">
$(document).ready(function() {
doAjax();
window.setInterval(function(){
doAjax();
},2000);
}); //END document.ready
function doAjax() {
$.ajax({
type: "POST",
url: "your_php_processor.php",
success: function(myData) {
$('#thetime').html(myData);
}
});
}
</script>
</head>
<body>
<div id="timeDiv">
The time is: <span id="thetime"></span>
</div>
</body>
</html>
Now, the PHP side... your_php_processor.php
<?php
$d = date("h:i:s");
echo $d;

Categories