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 :)
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
In my parent.htm there's a dropdown list, which is filled dynamically from the database using a JQuery function updateMyList() in parent.js.
If the user wants to add another option to the list, the form child.htm is loaded inside <div id="overlay"> of the parent.htm. To insert new data an AJAX request is called from child.js, which is included in child.htm.
If the request was successful, child.htm is unloaded via $("#overlay").html("") from child.js. When this happens, i'd like to call parent.js's updateMyList(), but i can't find a way to trigger it.
Using opener from inside child.js didn't work (TypeError: opener is null) and i can't find a way to tell if $("#overlay").html() has been changed back to "".
Any help would be greatly appreciated!
Sorry if this is a double post, i'm running out of ideas for search terms...
edit: here's a simplified code:
parent.htm:
<head>
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="parent.js"></script>
<script>
$(document).ready(function () {
$('#new-option').click(function(){
$("#overlay").load("child.htm");
});
});
</script>
</head>
parent.js:
$(document).ready(function(){
function updateMyList(){
//send AJAX and write options
});
// and do much more...
});
child.htm:
<head>
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="js/child.js"></script>
</head>
child.js:
$(document).ready(function(){
// do more stuff
$('#save-option').click(function(){
$.post("./inc/savenewoption.php", {
//save user entries
}, function(data){
alert(data);
})
.done(function() {
updateMyList(); // <- this won't work
$("#overlay").html("");
});
});
});
It doesn't work because updateMyList() is inside a different function (one of your $(document).ready() ones). In my experience the only reason you put code into a $(document).ready() function is because Javascript can fire before the document has completely loaded. Trying to fire Javascript on elements before they are in the document will cause errors.
The updateMyList() function doesn't fire until the ajax request is complete, so it should be safe to have it located outside $(document).ready().
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;
I have a small web page with a single div whose content needs to be updated periodically. The server sends JavaScript with a function that contains the new data to be updated in the div. Here's the first part of the code that the server sends:
<html>
<head>
<script>
function bar() {
document.getElementById("foo").innerHTML = "0";
}
</script>
</head>
<body onLoad="bar()">
<div id="foo"></div>
</body>
After a delay (2 seconds), the server sends in the remaining code below:
<script type="text/javascript">
function bar() {
document.getElementById("foo").innerHTML = "1";
}
</script>
</script>
</html>
The trouble is that I never see the div show "0" in it - the browser waits until the entire page is loaded, and straightaway displays "1" in the div. How do I get the div to show "0" in it while the server has not sent the entire page?
I am not looking at using any jQuery or AJAX code - please limit your answers to JavaScript only.
You can not use onload -> that gets fired only after the whole page has completely loaded.
Also you have to add some more bytes to the first response, because most browsers only start incremental rendering of the page after a certain ammount of data being received.
This should work:
<html>
<head>
<script>
function bar(x) {
document.getElementById("foo").innerHTML = x;
}
</script>
</head>
<body>
<!-- AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA -->
<div id="foo"></div>
<script type="text/javascript">
bar(0);
</script>
</body>
--- DELAY ---
<script type="text/javascript">
bar(1);
</script>
</script>
</html>
Here is a working example in node.js:
var http=require('http');
var server=http.createServer(function(req,res){
res.write('<html><head> <script> function bar(x) { document.getElementById("foo").innerHTML = x; }</script> </head> <body><!-- AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA --> <div id="foo"></div><script>bar(0);</script> </body>');
setTimeout(function(){
res.end('<script type="text/javascript"> bar(1); </script></html>');
},2000);
});
server.listen(8080);
it first shows "0" then after 2 seconds "1"
I'm not sure it's possible to do it the way you're trying. The browser will always wait till the page has fully loaded, so it will always wait till you send that second batch.
If you don't want to use AJAX or jQuery, you could try a hacky version to get what you want.
What you can do is specify a callback function on your page to populate the div with a parameter, so something like
callback = function(data) {
document.getElementById('foo').innerHTML = data;
}
Then, you set a timeout on your page to send a request to your server to dynamically load a javascript file that calls that function. So again:
myTimeout = function() {
var script = document.createElement('script');
script.src = "http://myserver.com/mydynamicscript";
document.getElementByTagName('head').appendChild(script);
}
setTimeout(myTimeout, 2000);
The script that you're loading can either be static, or some servlet/php file that returns a javascript file, i.e. it sets it's content-type header to "text/javascript".
In that script, you would then generate this:
callback("whatever I want to put in my div...");
Once that has been loaded, it will call the previous function you declared earlier, and load the content in that div.
It's effectively a hacky form of AJAX, but not AJAX.
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.