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;
Related
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.
its the code for posting a javascript variable into php...
but its not working..sugesstion...
i want to take value of id from javascript and post into a php.
<!DOCTYPE html>
<html>
<body>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$("form").submit(function() {
var id = $("input[type=submit]").attr('id');
alert(id);
$.ajax({
type: 'post',
url:('abcde.php')
data: {id1: id},success: function(response){}
alert(id1);
});
});
});
</script>
</head>
<form action="abcde.php" method="POST">
<!-- other form fields -->
<input type="submit" id="a" name="idVal" value="a">
</form>
</body>
</html>
<?php
if(isset($_POST['id']) ){
$id=$_POST['id'];
echo $id;
}
?>
ohh boy, 1st: it's
data: {'id': id}
secondly, your code is really wrong on this part, you are not doing anything in success, and you just randomly put an alert() in, with a variable that doesn't even exist.
So instead of success: function(response){}, it should be success: function(response){alert(response);} and forget about the alert(id1);
Other errors I saw from looking at it quickly: you are submitting your form from AJAX and HTML as well. You should block the default behavior with a function at the beginning of .submit(funcition() {...}. There already is a function for that, but I can't remember.
Lastly, you are sending the form data to the same page you are submitting from. You will get an answer from AJAX with the same page you are looking at. You should extract the php code to a different file and make abcde.php a simple abcde.html file.
One last thing: instead of alerts, you should use Console.log and watch the browser's console for debugging. You will see a bunch of errors, which makes debugging a lot easier.
You should, instead of blindly coding, be more mindful about what is responsible for what. You should be thinking more about the side-effects of you are introducing to your code. This will come with experience, we've all been there. Make sure one 'thing' is only responsible for ONE task.
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
I've tried to load external html page on same server using jQuery .load() by clicking on div , but it just doesn't work ! I tried using examples of $.get or $.post from Jquery API website . but every time I found this error in my chrome console :
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.
every correct answers on Stackoverflow also had same results .
I know a little of JavaScript,Jquery and php . can somebody help me out here ?
Extra Notes : I've also tested my codes in XAMP local server ;
I've tried many ways , the last time my code was :
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$('#reslink').click(function(e){
e.preventDefault();
$.ajax({
type: "GET",
url: "2.html",
data: { },
success: function(data){
$('#maincont').html(data);
}
});
});
});
</script>
</head>
<body>
link1
<div id="maincont">
</div>
</body>
</html>
new:
I tested the same code in online free webhost and it just worked there ! I still cand understand the reason why it didnt work in xamp server !
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 :)