I am thinking of writing a desktop HTA program.
However, at startup I would need to make 1 ajax php database call to a website, which will need a success element callback.
Is this possible? Would I need to overcome any crossbrowser issues? Would firewalls cause any problems?
Possible - yes. See code below. Crossbrowser is not applicable in HTA -- you're always using the IE rendering engine. But I think you may mean cross-domain issues, which are also not applicable in HTA. Microsoft chose to disable all of the Javascript cross-domain protection because an HTA (HTML-Application) is treated as an application not a web page.
There are lots of considerations for firewalls, but it's unlikely that a firewall would block HTA AJAX calls more restrictively than HTML AJAX. If you have a web page that calls your PHP page, it will probably also work in HTA. Good luck!
<html><head>
<script language="javascript" type="text/javascript">
var XHR = new ActiveXObject("Msxml2.XMLHTTP");
function callAjax(url){
XHR.onreadystatechange=(callback);
txtStatus.value += "opening: " + url + "\n";
XHR.open("GET",url,true); //"POST" also works
XHR.send(); // XHR.send("name1=value1&name2=value2");
}
function callback(){
if(XHR.readystate == 4) txtStatus.value += "DONE\n" + XHR.responseText;
}
</script>
</head>
<body onload="callAjax(txtURL.value)">
<textarea id=txtURL style="width:100%" rows=1>http://www.google.com</textarea>
<textarea id=txtStatus style="width:100%" rows=20></textarea>
</body></html>
Related
First question using the site so please bear with me if I haven't followed every rule in the book.
I come from a C++ background and don't have a great deal of experience with php/AJAX so I know that I probably have approached some of the following coding tasks in a sub-optimal/ improper way for writing code in different languages but anyway...
I have a Web site which uses a member login system written in PHP (connected to a mysql database), and the site is written using .php files to accomodate for this login system.
I want to use AJAX and JS on my .php pages to make them have a better user experience and I know this is possible (as I have done it), but I wanted to know if there are any negative/technical reasons why I shouldn't (and whether there are any better ways of doing this) as php is server side and AJAX is Client side.
Any advice would be appreciated.
Thanks
EDIT
I've added some code to show the type of things I would like to add to my php site
<?php
require "class.loginsys.php";
$LS = new LoginSystem();
$LS->init();
?>
<!-- HTML page structure -->
<!DOCTYPE html>
<html>
<head>
<title>OnyxProjectsPage</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type = "text/javascript">
function createTable()
{
var xhr;
if (window.XMLHttpRequest) // Mozilla, Safari, ...
{
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) // IE 8 and older
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "createDatabase.php");
//xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send();
xhr.onreadystatechange = display_data;
function display_data()
{
if (xhr.readyState == 4)
{
if (xhr.status == 200)
{
alert("Table Created");
}
else
{
alert('There was a problem with the request.');
}
}
}
}
</script>
</head>
<body>
<!-- Header background bar -->
<div id="container" style="width: 1920px">
<div id="header" style="background-color:#4c4c4c;">
<form class="well-home span6 form-horizontal" name="ajax-demo" id="ajax-demo">
<div class="controls">
<button type="button" onclick="createTable()">Create Testplan</button>
</div>
</form>
</body>
</html>
Using AJAX / JavaScript is not more dangerous than regular PHP. You can argue, that people can disable JavaScript and thus not be able to perform your expected result.
Usually, using AJAX will, as you mentioned, satisfy the user-experience, since they don't have to reload the page everytime a request is send.
The best solution, in my opinion, would be:
Check if the User enabled Javascript in his browser (keyword: noscript). If so, you can do use Frameworks like jQuery. Using this you can take advantage of the build-in ajax-function (take a look here). Otherwise prepare a fallback/failsafe mode for to serve every visitor.
LT;DR
Mix both of them. In any case, check and validate on serverside before inserting data in a database (or everything related to that kind of stuff), even if you checked it on the clientside already.
Personally, I prefer a combination of both, however not in same example as DasSaffe supplied.
I would write your PHP/HTML log-in page and when a user attempts to log in it runs your PHP script through an ajax request. If the PHP script returns success then ajax can redirect the user successfully.
The nice thing about this is that you can handle empty fields/invalid log-ins without ever leaving the page. If you use PHP only you will have to redirect the user to your script and then redirect back if there is an error.
Then you have to think, if I redirect my user back to the log-in page how do I tell the user that there was an error?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function ShowFile(sFilePath){
var oFileSystem = new ActiveXObject("Scripting.FileSystemObject");
frmEditHTML.tarHTMLText.value = oFileSystem.OpenTextFile(sFilePath.value).ReadAll();
}
function SaveAfterEditing(sFilePath){
var oFileSystem = new ActiveXObject("Scripting.FileSystemObject");
var oFile = oFileSystem.CreateTextFile(frmEditHTML.filPath.value,1);
oFile.WriteLine(sFilePath.value);
oFile.Close();
}
</script>
</head>
<body>
<form name="frmEditHTML">
Select the File you want to Edit
<input type=file name="filPath" onchange="ShowFile(this)">
<textarea name="tarHTMLText" cols=60 rows=20></textarea>
<input type="button" value="Save" name="cmdSave" onclick="SaveAfterEditing(this.form['tarHTMLText'])">
</form>
</body>
</html>
I read this link and this link but they could not help!
I don't want to use ActiveX as then this function will be restricted to IE.
IE Tab in FireFox is also causes problems!
How can I replicate this whole function in PHP without using ActiveX ?
Please Help!
Short answer:
With PHP you can't convert this script exactly as it is, since ActiveX is client side and PHP is server side. Javascript can't do this for you either, since modern browsers are sandboxed, and JavaScript cannot access local file systems.
Not so short answer:
You have other options, however, depending on which behavior (and implementation method) you wish to mimic.
You can use a Java Applet that is able to do pretty much what you could do with ActiveX. Works consistently across browsers but user have to have installed Java Runtime Environment.
You can use a mix of PHP + Javascript (AJAX). You upload a file to the server and then control PHP actions with Javascript (HTTP Requests via Ajax).
Hackish way
There is an hackish simple way to handle this situation. Requires a server somewhere though.
Create a page that uploads a file to the server.
Then send the file back to the browser, via AJAX (or any request, doesn't matter).
Manipulate the file in the client side (browser) with javascript.
Give the file to the user to download.
Ok , so what I'm trying to do is trigger PHP code, only when the if condition is true (in javascript) , I understand that php is server side, and javascript is client side. The include of the php code works perfect except 1 thing , it gets triggered on page load actually , not when the if condition happens. If you can help me how to do this will be rly appreciated. I want the php file to be included ONLY when the if condition is true
thanks in advance
here's the code am using :
<html>
<script src="//cdnjs.cloudflare.com/ajax/libs/visibility.js/0.5/visibility.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script>
var seconds=20;
var flag=false;
$(document).ready(function(){
if (!flag)
Visibility.every(1000, tick);
function tick()
{
display();
if (seconds>0)
{
seconds--;
}
else
{
if (!flag){
document.getElementById('more').innerHTML +="<?php include_once('Code.php');
?>";
document.getElementById('more').style.visibility='visible';
flag=true;
}
}
}
function display()
{
$("#timer").html(seconds);
}
});
</script>
<div id="TrafficHeader" style="height:100px; background-color:grey; padding:20px;">
<div id="timer"></div>
<div id="more" style="visibility: hidden;">View Next Ad</div></div>
<iframe id="myframe" src="<?php echo ''.$URL;?>" height="100%" width="100%" frameborder="0">
</iframe>
</body>
</html>
This is not possible, at least not the way you are going about it.
The reason is that the if condition is evaluated on the client machine long after the server finish evaluating your php script.
First server has to finish procesing your php script, then imagine it has to pack it and then send the whole package to the client, which then unpacks it and renders the html and evaluates the javascript in html, or asks for external files like images, css or other script files.
If you are trying to include some extra javascript ,than you can add extra script tag in the head programatically. If you want to do something on the server, you can call a script on a server just as easily.
Here is how you can exeecute that script from javascript only if the if is true:
...
if (!flag){
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "http://link/to/your/code.php?and=special¶meters=sent", false );
xmlHttp.send( null );
document.getElementById('more').innerHTML += xmlHttp.responseText;
document.getElementById('more').style.visibility='visible';
flag=true;
}
...
The php code is server side so it's executed before the javascript so javascript CAN'T control what php does. You need to use an Ajax script to make javascript can request a php file from the server, and then it'll work.
You can't do it that way... you said it yourself, PHP is server-side. In order to run PHP, you have to have the browser query something against your web server. This will most definitely not work as you intended... it'll always be included:
innerHTML +="<?php include_once('../../Includez/Traffic/Traffic_Code.php'); ?>";
You can, however, cause the JavaScript to fetch something more from the server which can run some PHP code and return something new to your page...
Did you try solution with "load"?
<div id="special_block"></div>
<script>
var a = 1;
if (a == 1){
$('#special_block').load('code.php');
}
</script>
I am building an application that grabs html source from various sites.
Using xpath or simple html dom, I can then quite easily parse this html and dumb it to a database etc.
Unfortunately this approach does not work for one particular site.
This is because the site loads its content with JavaScript and so most of its content is not visible in the html source.
Having googled this over and over and read loads of threads covering the subject here on Stackoverflow. I'm still not sure how to go about solving this problem.
Here is the important part of the code this site is using to display its content.
<script type="text/javascript" src="/jquery-1.3.2.min.js"></script>
<script>
var example = {
getServiceCall:function(url) {
{
var srtPos=url.indexOf('Filter');
var endPos=url.indexOf('/',srtPos);
var filter = $.getUrlVar("Filter");
var filterInServiceUrl=url.slice(srtPos,endPos).split(":");
url = (filter)
? url.slice(0,srtPos) + filter + url.slice(endPos,url.length)
: url.slice(0,srtPos) + filterInServiceUrl[1] + url.slice(endPos,url.length);
}
document.writeln('<scri'+'pt src="'+url+'" type="text/javascript"> </sc' + 'ript>');
},
};
$.extend({
getUrlVars: function(){
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
},
getUrlVar: function(name){
}
});
</script>
<div id="content">
<script language="javascript" type="text/javascript">
function doPerItem(html){ $("#content").html(html.toString()); }
example.getServiceCall('http://www.example.com/?callback=doPerItem');
</script>
</div>
Using Inspect Element in Google Chrome I can see that there is a file that contains html source that I want.
How can I use php to make the same request/arguments to the remote serve and then save the response to a file?
I will then be in a position to parse it with xpath or simple html dom just like the other sites.
Your help will much appreciated.
I don't know of any PHP-based remote access tool (including cURL) which interprets JavaScript. Selenium (normally used for testing) might do this, but Selenium-RC did not work for me at all with PHP and had bugs in the IDE.
You cannot practically use Ajax because that doesn't resolve JavaScript either (maybe you can resolve it somehow with eval() which has its security concerns), and JSONP will only work if the remote server is deliberately offering an API for getting its data (you could write your own proxy and then give the data as JSONP but then you'd still have the problem of resolving JavaScript).
What you could do (though it has real security risks for your site):
Write a file in PHP which simply gets the remote site's contents, using file_get_contents() and then outputs it (i.e., make a proxy).
Dynamically insert a hidden iframe via JavaScript to load your proxy page and then wait for the iframe's load event.
Get the resulting HTML of the hidden iframe from the parent and send back the result to the server.
You can't avoid step 1 unfortunately because you can't listen in on an iframe unless it comes from the same domain as yours.
Note that if the site you are visiting crafts their JavaScript in a certain way, they could access your containing HTML, and do things like grab your user's cookies so as to steal passwords, find out your domain or what's showing on your page, etc.
There may be better solutions out there, but I'm not aware of any.
For example, I have a php function:
function DeleteItem($item_id)
{
db_query("DELETE FROM {items} WHERE id=$item_id");
}
Then, I have something like the following:
<html>
<head>
<script type="text/javascript">
function DeleteItem($item_id)
{
alert("You have deleted item #"+$item_id);
}
</script>
</head>
<body>
<form>
Item 1
<input type="button" value="Delete" onclick="DeleteItem(1)" />
</form>
</body>
</html>
I want to be able to call the PHP function DeleteItem() from the javascript function DeleteItem() so that I can use Drupal's db_query() function, so I don't have to try to establish a connection to the database from javascript.
Does anyone have any suggestions on how this might be done? P.S. I understand that PHP processes on the server-side and javascript processes on the client-side, so please no responses saying that. There has got to be some kind of trick one can do in order to have this work out. Or maybe there is a better way of doing what I am trying to accomplish.
Since you are aware that PHP processes on the server-side and javascript processes on the client-side, you must also realize you can't call a PHP "function" from javascript. Your client side code can redirect to a PHP page, or invoke a PHP program using AJAX. That page or program must be on the server and it should do a lot more than just the one line you have in your function. It should also check for authentication, authorization, etc. You don't want just any client side script anywhere to call your PHP.
You need to write a PHP script which will execute the function. To call it, either:
use XMLHttpRequest (aka Ajax) to send the request
change the page's location.href and return HTTP status code 204 No Content from PHP
You will want to use ajax for that.
Also, database connection from within javascript is something you should not even consider as an option - terribly insecure.
A very simple example:
//in javascript
function DeleteItem($item_id) {
$.post("delete.php", { id: $item_id}, function(data) {
alert("You have deleted item #"+$item_id);
});
}
//in php file
db_query("DELETE FROM {items} WHERE id=" . $_REQUEST["id"]);
you can't actually call PHP functions within JavaScript per se. As #Christoph writes you need to call a PHP script via a normal HTTP request from within JavaScript using the magic that is known as AJAX (silly acronym, basically means JS can load external HTTP requests on the fly).
Take a look at jQuery's AJAX functionality on how to reliably make a HTTP request via JS, see http://docs.jquery.com/Ajax
All the normal security rules apply, i.e. make sure you filter incoming data and ensure it's what you're expecting (the $item_id in your example). Bear in mind there's nothing to stop someone manually accessing the URL requested by your JS.
First, use jQuery.
Then, your code will have to be something like:
<input ... id="item_id_1" />
<script>
$(document).ready(function() {
$('input').click(function(){
var item_id = $(this).attr('id');
item_id = item_id.split('_id_');
item_id = item_id[1];
$.get('/your_delete_url/' + item_id);
});
});
</script>