So I'm new to Js & php and I'm trying to print out a piece of code from a call back function
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","callback_json.php",true);
xmlhttp.send();
}
</script>
<title>Simple Cross Domain Ajax</title>
</head>
<body>
<h1>.....</h1>
<h2>.....</h2>
<button onclick="loadXMLDoc();">Get Data</button>
<div id="myDiv"><h2>...</h2></div>
</body>
</html>
and my php file goes like
<?php
$ch = curl_init();
$url='someurl';
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
echo "<script type='text/javascript' src='syntaxhighlighter/scripts/shCore.js'></script><script type='text/javascript' src='syntaxhighlighter/scripts/shBrushJava.js'></script><link href='syntaxhighlighter/styles/shCore.css' rel='stylesheet' type='text/css' /><link href='syntaxhighlighter/styles/shThemeDefault.css' rel='stylesheet' type='text/css' />";
echo "<pre class='brush:java;'>";
echo $data;
echo "</pre>";
echo '<script type="text/javascript">SyntaxHighlighter.highlight();</script>';
?>
And it seems syntax highlighter works on my php file but not after call back...I did some research and I know I'm supposed to use SyntaxHighlighter.highlight() instead of all() in the code but I've already done that. Is there any problem with my code structure?
<script> tags added by innerHTML are not executed by the browser. You need to execute them manually:
var scripts = document.getElementById("myDiv").getElementsByTagName("script");
if (scripts && scripts.length) {
for (var i =0; i<scripts.length; i++) {
eval(scripts[i].innerHTML);
}
}
Alternatively you can re-append the script nodes to the page instead of evaling it:
// ...
for (var i =0; i<scripts.length; i++) {
var s = document.createElement('script');
s.innerHTML = eval(scripts[i].innerHTML);
document.body.appendChild(s);
}
but this is exactly the same as evaling the code anyway (no really, think hard about it both methods execute the code unchecked).
A better way is to avoid script injection altogether by adding the Syntaxhighlighter files at the top of the page and calling SyntaxHighlighter.highlight() after you've innerHTMLed the code.
Related
I am trying to create a online editor for multiple server. I want to edit a custom file on a server and I need to get it via sftp. My current code looks like this:
<?php
$user="user";
$pass = 'pass';
$c = curl_init("sftp://$user:$pass#0.0.0.0/path/to/file/file.txt");
curl_setopt($c, CURLOPT_PORT, 3206);
curl_setopt($c, CURLOPT_PROTOCOLS, CURLPROTO_SFTP);
curl_setopt($c, CURLOPT_FILE, $fh);
curl_exec($c);
curl_close($c);
//the next line is not working and from now on am I stuck
$text = file_get_contents($fh);
?>
<!-- HTML form -->
<form action="" method="post">
<textarea name="text"><?php echo htmlspecialchars($text) ?></textarea>
<input
type="submit" />
<input type="reset" />
</form>
I want to edit this file on the website and then reupload it to the sftp server in the same directory (overweite the existing one). I do not know how to continue. Thanks for the help.
First off if it's a file containing some programming language, check ACE.js.
It's simply an incredible JS module for use as a web IDE and it has all the features any programmer looks for in an IDE, it's so good I would ALMOST consider switching to it as my primary IDE.
Then use this PHP code:
<?php
$_POST = json_decode(file_get_contents('php://input'), true);
$filename = 'sftp://user#location/file/name.js';
//Use SSH public key authentication
$handle = fopen($filename,'w') or die('Cannot open file: '.$filename);
$data = $_POST['src'];
fwrite($handle, $data);
fclose($handle);
?>
and use this JS code to call the PHP script:
<script src="../scripts/ace/ace.js" type="text/javascript"></script>
<script>
var editor = ace.edit("editor");
editor.setTheme('<?php echo $theme; ?>');
editor.getSession().setMode("<?php echo $language; ?>");
editor.setShowPrintMargin(false);
editor.setReadOnly(true);
<?php //Save shortcut binding ?>
editor.commands.addCommand({
name: 'Save',
bindKey: {win: 'Ctrl-S', mac: 'Command-S'},
exec: function(editor) {
var xhr = new XMLHttpRequest();
xhr.open("POST", './scripts/save_file.php', true);
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.send(
JSON.stringify(
{src:editor.getValue()}
)
);
}
});
</script>
I have problem with logging visit duration.
I wrote test html file like this:
<!DOCTYPE html>
<html>
<body>
<script language="JavaScript" type="text/javascript">
function enter() {
this.chrono = new Date().getMilliseconds();
alert("test");
}
function leave() {
this.chrono = new Date().getMilliseconds() - this.chrono;
var myAjax = new Ajax.Request('visitor_log/ajax_store_visit_duration.php?visit_duration=' + this.chrono.toString(),{
method: 'get',
onComplete:handlerFunction
});
return null;
}
window.onload = enter;
window.onbeforeunload = leave;
</script>
</body>
</html>
PHP file (visitor_log/ajax_store_visit_duration.php):
<?php
if(isset($_GET["visit_duration"]))
{
$text = $_GET["visit_duration"];
log($text);
}
else die("error");
function log($text)
{
$myFile = "test.txt";
$fh = fopen($myFile, 'wb');
fwrite($fh, $text);
fclose($fh);
}
?>
When I type in browser:
http://localhost/visitor_log/ajax_store_visit_duration.php?visit_duration=123
it creates text file as I want, but it seems that AJAX call in onbeforeunload event is not working.
Whats wrong with my code?
Edit:
I created test function to find problem with AJAX call.
function testajax(){
this.chrono = new Date().getMilliseconds() - this.chrono;
var blockingRequest = new XMLHttpRequest();
blockingRequest.open("GET", "visitor_log/ajax_store_visit_duration.php?visit_duration=" + 123, false); // async = false
blockingRequest.send();
return null;
}
window.onload = testajax;
</script>
</body>
This is not working too.
Ok, so purposefully NOT using jQuery:
here's the PHP:
<?php
function loggit($text) {
$myFile = "/tmp/test.txt";
$fh = fopen($myFile, 'wb');
fwrite($fh, $text);
fclose($fh);
}
if(isset($_GET["visit_duration"])) {
$text = $_GET["visit_duration"];
loggit($text);
}
else die("error");
?>
here's the HTML:
<!DOCTYPE html>
<html>
<body>
<script language="JavaScript" type="text/javascript">
function enter() {
this.chrono = new Date().getMilliseconds();
}
function leave() {
this.chrono = new Date().getMilliseconds() - this.chrono;
alert("test" + this.chrono);
var blockingRequest = new XMLHttpRequest();
blockingRequest.open("GET", "http://localhost/_TempFiles/temp.php?visit_duration=" + this.chrono.toString(), false); // async = false
blockingRequest.send();
return null;
}
window.onload = enter;
window.onbeforeunload = leave;
</script>
</body>
</html>
you want to use an async request (see the false sent to blockingrequest.open) - but beware this is a BLOCKING request (hence the name).
Also I changed the name of the php function from "log" to "loggit" log is the php natural logarithm function...
If I embed my XHR file into my HTML document directly, everything works fine. As soon as I src it via
<script type="text/javascript" src="js/ajax_gallery.js">ajax_json_gallery('gallery');</script>
Nothing works, and I get no errors. I'm assuming it's something to do with the XHR being created in a separate file to the HTML. I just don't like XHR script cluttering up my HTML, I just want to load as an external JS file.
I've moved my main 3 scripts, galleryHandle.php, XHR.js, ajax_gallery.html all to the same dir level to keep things simple. And the gallery images are in a folder called "gallery", also on the same level.
Here's my code:
HTML
<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="css/gallery.css" />
</head>
<body>
<div id="pagetop"></div>
<div id="thumbnailbox"></div>
<div id="pictureframe"></div>
<script type="text/javascript" src="XHR.js">ajax_json_gallery('gallery');</script>
</body>
</html>
JavaScript
function ajax_json_gallery(folder) {
"use strict";
var httpRequest = new XMLHttpRequest();
document.getElementById("pagetop").innerHTML = "dynamic ajax json gallery";
var thumbnailbox = document.getElementById("thumbnailbox");
httpRequest.open("POST", "galleryHandle.php", true);
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4 && httpRequest.status === 200) {
var data = JSON.parse(httpRequest.responseText);
var pictureframe;
pictureframe.innerHTML = "<img src='"+data.img1.src+"'>";
thumbnailbox.innerHTML = "";
for (var obj in data) {
if (data[obj].src){
thumbnailbox.innerHTML += '<div onclick="putinframe(\''+data[obj].src+'\')"><img src="'+data[obj].src+'"></div>';
}
}
}
};
httpRequest.send("folder="+folder);
thumbnailbox.innerHTML = "Loading...";
}
function putinframe(src) {
"use strict";
var pictureframe = document.getElementById("pictureframe");
pictureframe.innerHTML = '<img src = " '+src+' " >';
}
PHP
<?php
header("Content-Type: application/json");
//bring in folder name
$folder = $_POST["folder"];
//start componding json
$jsonData = '{';
//compound directory path
$dir = $folder."/";
//open directory
$dirHandle = opendir($dir);
//init while looop
$i = 0;
while ($file = readdir($dirHandle)) {
if(!is_dir($file) && strpos($file, '.jpg')){
$i++;
$src = "$dir$file";
$jsonData .= '"img'.$i.'":{ "num":"'.$i.'","src":"'.$src.'", "name":"'.$file.'" },';
}
}
closedir($dirHandle);
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
?>
I understand there are some redundancies in my code but it's just a tutorial I'm going through to learn the basics of JSON building with POST, XHR.
Anyway, help appreciated as always.
Thanks
Explanation
FROM W3C:
<script type="text/javascript" src="myscript.js">
alert('I am pointless as I won\'t be executed');
</script>
Upon meeting this element in a page, browsers will then load the file myscript.js and execute it. Any content inside the script element itself will be skipped when you provide a src attribute. The [last] example will load the file myscript.js and execute the code in it but will not execute the alert inside the script element at all.
Solution
Try the following in your head tags:
HTML
<script type="text/javascript" src="XHR.js"></script>
<script type="text/javascript">
ajax_json_gallery('gallery');
</script>
<script type="text/javascript" src="XHR.js">
You can't have src attribute and javascript both in a single tag. Separate them out. Like this...
<script type="text/javascript" src="XHR.js"></script>
<script type="text/javascript">ajax_json_gallery('gallery');</script>
I am sending ajax request to the server as :
Client Side Code :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script language="">
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var imgVal='img_id'+1;
xmlhttp.open("GET","imageprovider.php",false);
xmlhttp.send();
if(xmlhttp.readyState==4)
{
alert(xmlhttp.responseText);
document.getElementById('img').appendChild(xmlhttp.responseText);
}
</script>
</head>
<body>
<div id='img'>
</div>
</body>
And here is the server side code that shows a simple image with base64 encode.How can i get the response from client the above code and show it.
Server Side PHP Code :
<?php
$img_src = "images/1.png";
$imgbinary = fread(fopen($img_src, "r"), filesize($img_src));
$img_str = base64_encode($imgbinary);
echo '<img src="data:image/jpg;base64,'.$img_str.'" />';
?>
Try replacing
document.getElementById('img').appendChild(xmlhttp.responseText);
with
document.getElementById('img').innerHTML = xmlhttp.responseText;
Or, if you need to continue using .appendChild(), try replacing
document.getElementById('img').appendChild(xmlhttp.responseText);
with
var o = document.createElement('img');
o.src = xmlhttp.responseText;
document.getElementById('img').appendChild(o);
And replacing
echo '<img src="data:image/jpg;base64,'.$img_str.'" />';
with
echo 'data:image/jpg;base64,'.$img_str;
you capture the response
you inject the response into the DOM
Whith jQuery the code would be something like this:
$.ajax({
url: "imageprovider.php",
context: document.body,
success: function(data){
$('#objectToAddImage').html(data);
}
});
Nevertheless I would advise against passing the image as a base64 as the browser will have no way to cache it. If passing the image as a base64 encode is not an absolute requirement of your project I would recommend the server simple pass a link to the actual image.
I have two dropdowns and I want the second dropdown to get populated on the basis of the data selected from the 1st dropdown
Here is my main.php:
<?php
include('connection.php');
$query_religion="SELECT DISTINCT religion FROM religion_caste_table";
$result_religion = mysql_query($query_religion, $con);
?>
<html>
<body>
<select name="religion" id="religion" style="width: 100px" onChange="showcaste(this.value)">
<?php
while($q_rel_data = mysql_fetch_array($result_religion))
{?>
<option value="<?php echo $q_rel_data[0]; ?>">
<?php echo $q_rel_data[0]; ?>
</option>
<?php }?>
</select>
<div id="view"></div>
<select name="caste" id="caste" style="width: 100px"></select>
</body>
</html>
And this is getcaste.php:
<?php
include('connection.php');
$string=$_GET["religion"];
$sql="SELECT caste FROM religion_caste_table WHERE religion = '".$string."'";
$result = mysql_query($sql,$con);
$myarray=array();
$str="";
while($result_caste=mysql_fetch_array($result))
{
$str=$str . "\"$result_caste[caste]\"".",";
}
$str=substr($str,0,(strLen($str)-1)); // Removing the last char , from the string
echo $str;/*Stop hiding from IE Mac */
//echo $string;
mysql_close($con);
?>
<html>
</html>
now for the javascript ajax file,(religion_caste.js)
function showcaste(string)
{
if (string=="")
{
document.getElementById("caste").innerHTML="";
return;
}
alert(string);
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("view").innerHTML=xmlhttp.responseText;
//now how to catch the string from (getcaste.php), split it and save it into array
// and to populate the second dropdwn by the array;
}
}
xmlhttp.open("GET","getcaste.php?religion="+string,true);
xmlhttp.send();
}
For more better assistance, the database table contains two fields, religion and caste, where the first attribute is religion, and caste being the second.
If somehow I can catch the string str, then it could have solved the matter.
document.getElementById("view").InnerHTML=xmlhttp.responseText provides the string "str1","str2",... to be viewed in <div id="view">
But if I write the following code:
var string=(document.getElementById("view").InnerHTML);
alert(string);
Then a msgbox pops up with such view:
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
"Catholic","Protestant"
If I could just get the string, I would be happy.
So in your place a would do a little remake in getcaste.php first - place all results from your query into an array and then use implode to get a string using delimiter - ;. (Optionaly you could use a json and decode it in js). In religion_caste.js use split to get an array back from it (; as delimiter);
Now use for cycle to cycle through all values, and every cycle add one option into select
example:
var select = document.getElementById("caste");
for (var key in values)
{
var OptNew = document.createElement('option');
OptNew.text = values[key];
OptNew.value = key;
try
{
select.add(OptNew, null); // doesn't work in IE
}
catch(ex)
{
select.add(OptNew); // IE only
}
}
Edit:
so json in php is easy - json_encode
json in js is a little bit more difficult. New browsers should support JSON.parse, for old ones you have to use this code(Not 100% sure here since I always use jQuery). Alternatively you could use jQuery and jQuery.parseJSON