Executing a php script located on server via ajax - javascript

I have a website hosted on server, now what I want is to run a .php script (Also located on the same server) when someone presses the submit button in the website.
Following is the ajax code
$.ajax({url: "/test.php",
success: function(response){
console.log("Success",response);
}
});
My test.php consists of
<?php
//exec('sudo -u www-data python /var/www/html/test.py');
echo "PHP Script Ran";
mkdir("/var/www/html/test", 0700);
?>
When I navigate to ip_address/test.php, the echo message is displayed correctly but the mkdir command doesn't seem to be executed as there is no folder created in my server's directory.
Also I want to know, how can I run this test.php script when someone presses the submit button in my website.
The Javascript code is
var $ = jQuery;
var timestamp = Number(new Date());
var form = document.querySelector("form");
var database = firebase.database();
form.addEventListener("submit", function(event) {
var ary = $(form).serializeArray();
var obj = {};
for (var a = 0; a < ary.length; a++) obj[ary[a].name] = ary[a].value;
console.log("JSON",obj);
firebase.database().ref('users/' + timestamp).set(obj);
database.ref('users/' + timestamp).once('value').then(function(snapshot) {
console.log("Received value",snapshot.val());
$.ajax({
url: "/test.php",
success: function(response){
console.log("Success",response);
}
});
});
});
Any help on this would be much appreciated.
Thanks

In this case it's recommended to use mkdir within try...catch function and capture the error if it's the case.
On the other hand mkidr will return a boolean value: true if the directory creation was successful or false in the case of a failure.
1.version
try {
mkdir("/var/www/html/test", 0700, true);
} catch ($ex Exception) {
echo $ex->getMessage();
}
2.version
if (!mkdir("/var/www/html/test", 0700, true)) {
echo 'Failed to create folder...';
}
If mkdir cannot create the folder two things you need to check: if the folder exist and if it has the right permissions. By this i mean if the user group is set to apache (because apache, through web browser is executing the mkdir command) and second if apache (www-data) has the necessary permissions to execute this command.

Revise your php.ini in the server, the tag disable_functions = "..." and making sure that mkdir not this included in the list.

Related

How can I read file names from a folder and store them into a javascript array?

I'm trying to make a website and all I want is to have an array in my javascript file that has the names of every file in my "images/" folder.
I've tried everything. I've scoured stackoverflow over and over again and nothing has worked. I've tried ajax and php functions, and I've tried using MAMP and XAMPP as my local web server (I'm on mac, by the way, in case that's important). Whenever I try to load images and just log the file name to the console, nothing happens. I have no idea what to do.
I'm fairly certain the problem is that access to my directories is blocked, and it's the local web server that's not working, not the code (though I could be wrong).
Here are some more specific examples of solutions I've tried that haven't worked:
Attempt 1
index.php:
...
<?php
$images = array_values(array_diff(scandir($dir), array('..', '.')));
$imagesJS = json_encode($images);
?>
<script type="text/javascript">
var images = "<?= $imagesJS ?>";
</script>
</script src="js/bodyScript"></script>
...
bodyScript.js:
console.log(images); // returns null on attempt
Attempt 2
bodyScript.js:
var folder = "images/";
$.ajax({
url : folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.(jpe?g|png|gif)$/) ) {
images.push(val); // add file name to array (doesn't work)
console.log(val); // log to console for debugging purposes (also doesn't work)
}
});
}
});
Attempt 3
bodyScript.js:
$.ajax({
url : "images/",
success: function(data){
$(data).find("td > a").each(function(){
console.log($(this).attr("href")); // nothing gets logged
});
}
});
Thank you
pseudo code
JavaScript:
$.ajax({
url : "http://mysite/getdirectories.php",
success: function(data){
console.log(data);
}
});
PHP (getdirectories.php)
$images = array_values(array_diff(scandir($dir), array('..', '.')));
exit(json_encode($images))

How to log PHP file run with jQuery AJAX in browser console?

I have a PHP file that does data processing. It's run by $.ajax(), sometimes on big files that take a long time to process. I need to log some info about the ongoing process in the browser console that is displayed on the go, not just when the PHP file has finished running.
From the research I did, I get that there are two difficulties:
Getting PHP to spit out something before it's done
Getting jQuery/JS to display it on the go
To address #1, I've tried:
echo "started"."<br>";
foreach (array("done this", "done that","had a coffee","burp") as $msg) {
sleep(3);
echo $msg."<br>";
flush();
ob_flush();
}
flush(); ob_flush(); is supposed to do the job, although as you can test here it does not strictly display ever 3s as it's expected to. Any suggestion to get it to display as expected?
As for how to address #2, I have explored a solution involving XMLHttpRequest, but I'm not familiar with the subject so not sure neither what to look for nor if it's the right direction...
Here is the test code of what I'm trying to get to run:
$("#run").click(function(e) {
$.ajax({
url: "http://constances-web-dev.vjf.inserm.fr/constances-web/ajax-test.php",
xhr: function() {
// get the native XmlHttpRequest object
var xhr = $.ajaxSettings.xhr();
xhr.addEventListener('readystatechange', function(e) {
console.log(e)
});
// set the onprogress event handler
//xhr.onprogress = function(evt){ console.log(evt.target.response) } ;
// set the onload event handler
return xhr;
},
success: function(msg) {
console.log(msg);
},
error: function(msg) {
console.log("Erreur: " + msg);
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="run">go</button>
Subsidiary question: Is there an (easy) way to go around the cross-origin restriction in order to get an AJAX example to work in a SO snippet?
as a work around I've added a log to file to my write2log function
static function log2File($string, $logFileName) {
if (substr($string,0,1 ) == "\n")
exec("echo '".date('Y-m-d_H:i:s')." ".addslashes(substr($string,1))."' >> ".$logFileName,$output,$status);
else
exec("echo -n ".addslashes($string)."' >> ".$logFileName,$output,$status);
}
I can then tail -f the log to watch how things are going
but this takes ssh access to the server so
i'd still be interested in figuring out how to log to console

Use catalyst and Ajax to refresh an SVG block

I am building a web app in which I have a number of clickable maps, stored as static SVG files, that I would like to be able to swap dynamically based on a menu-click. So far, I have javascript code to call my Catalyst controller, and I would like it to return the contents of the SVG file in the response body. So far I can get the javascript to catch the menu clicks and call the controller, and in the controller I am able to get the name of the file out of my database. I am stuck at that step, though, and have been thus far unable to find out how to read the contents of that file in the controller and return it to the javascript controller. Any help would be appreciated!
UPDATE:
The (Edited) code below works, but I'm not sure if this is the best way. I would definitely be open to suggestions on ways to improve my process. Thanks!
Javascript:
$(document).on("click",".map_select", function(e){
$(document.getElementById("som_map")).load("[% c.uri_for('/maps/update_map/') %]" + this.title);
})
HTML
<svg id="som_map" class="mapmain" width="720px" height="430px">
</svg>
PERL
sub update_map :Path :Local :Args(1) {
my ( $self, $c, $map_id ) = #_;
my $fields = $c->model('DB::Map')->find($map_id);
my $map_file = $fields->get_column('map_file');
my $svg;
my $path = "root/static/svg/$map_file";
open my $fh, '<', $path;
{
local $/ = undef;
$svg = <$fh>;
}
close $fh;
$c->res->body($svg);
}
SVG files are stored in root/static/svg/
Unless you have a reason to do it, I would use your web server (Apache, nginx, ...) serve the file for you instead of handling the file I/O inside of your controller.
In your load function in javascript pass in a function that returns a URL for you:
$(document.getElementById("som_map")).load(getSVGUrl(this.title));
Then define that function to call Catalyst to get the appropriate URL for the given mapId:
function getUrl(mapId) {
var returnUrl;
jQuery.ajax({
url: "[% c.uri_for('/maps/update_map/') %]"
+ mapId,
success: function(result) {
if(result.isOk == false)
returnUrl = result.message;
},
async: false,
dataType: 'text/plain'
});
return returnUrl;
}
This function should call your application and just expect to get the URL back. It should be fast enough that making it synchronous does not matter.
Finally, your Catalyst function should just return the URL to the document:
sub update_map :Path :Local :Args(1) {
my ( $self, $c, $map_id ) = #_;
my $fields = $c->model('DB::Map')->find($map_id);
my $map_file = $fields->get_column('map_file');
$c->res->body("<appropriate URL path to document>/$map_file");
}
This will get your application out of the document handling business, trim down your controller, and allow your web server to do what it does best - serve documents.

accessing php variables using javascript

I've done created a webpage, set up appache2 on ubuntu server so I can view this page over the internet. I've installed php5 and MySQL and would like to access information in the database on the webpage that I've created.
Right now, I've got a file test.php that accesses the database and puts some of the information into variables. I've scripted using javascript something that will change the webpage content at the click of a button.
Now, the webpage crashes whenever the button is pushed as it says the variables are undefined or null references. Fair enough, but my question is how does one access variables on a .php file through the webpage? Can a browser use information in the .php file if I script it into the page?
I was told that the php file would be parsed automatically. I'm guessing that server side this page is being accessed but I can use it through web browser.
Edit:
//check connection
if (mysqli_connect_errno()){
echo "failed to connect to MySQL: " . mysqli_connect_error();
}
$grab = mysqli_query($con, "SELECT * FROM table");
$row = mysqli_fetch_array($grab);
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$n1 = $name[0];
$c1 = $color[0];
$p1 = $price[0];
?>
Ok so I changed the php file to this, so now all it is doing is defining variables. I installed a couple of MySQL mods and no problems now.
next issue is how do I get use php variables in javascript
function load(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
xmlhttp.onreadystatecahnge = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("itemNameLink1").innerHTML = "<?php echo $n1;?>;
}
}
}
So onload this ajax function should run and change itemNameLink1 to the php variable $n1, only it doesn't and I just get an empty string. Everything should be set up right but using the php variable seems impossible. would it be any easier with the jquery get command, I'm guessing that unless I sort this out I'm gonna struggle.
I'm also assuming a few things, I've checked error logs and the php file is active assuming I've connected right it should be accessing the database. I'm very new so I do not know how to test this.
I'm also assuming that when php file is in the server webpage file directory. that it is automatically working. again very new to setting up a server so using ubuntu server and being familiar with all the commands that I need to use or how apache2 operates is difficult for me.
PHP Is executed on the server, your client receives the result as a plain text/html document.
Your browser runs the javascript when it received the plain document, so you can't access PHP vars directly with javascript.
But you could set javascript variables when the page is generated on the server like this
<?php $myPhpVar = 'Hello World'; ?>
<script>
//This line would result in var test = "Hello World"; when send to client
var test = "<?=$myPhpVar?>";
alert(test);
</script>
Furthermore you can execute requests to your server with javascript (so you can read the result from test2.php as example, and use that somewhere on your page). http://en.wikipedia.org/wiki/Ajax_(programming)
Pure javascript: http://en.wikipedia.org/wiki/XMLHttpRequest
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
var DONE = this.DONE || 4;
if (this.readyState === DONE){
alert(this.readyState);
}
};
var action = 'doSomethingOnServer';
request.open('GET', 'test2.php?action=' + action, true);
request.send(null);
Jquery: http://api.jquery.com/jquery.ajax/
<script>
var action = 'doSomethingOnServer';
$.ajax({
url: "test2.php?action=" + action,
}).done(function(result) {
alert(result);
});
<script>
For testing if your php works on your server create a file info.php (or something). and add this to the file
<?php phpinfo(); ?>
If you access that page you should get a page with a lot of information about your php configuration.
I'm not sure how you did install your php, but on a development machine you can change a few things in your php.ini that makes life easier
display_startup_errors = 1
display_errors = 1
error_reporting = E_ALL
See http://php.net/manual/en/errorfunc.configuration.php#ini.error-reporting when you change your php.ini don't forget to restart your apache
JSON Example:
data.php
<?php
$db_result = array(array('name' => 'record1'), array('name' => 'record2'));
echo json_encode($db_result);
?>
index.php
<script>
$.ajax({url: 'data.php', dataType: 'json'}).done(function(result) {
//result = an object from your database (in this case an array with objects with the property name)
alert(result);
alert(result[0].name);
}
</script>

Run Bash Script with Node from client request

I need to make a server-side script run when a user from the browser clicks a button...
I've been researching for a while, and can't figure it out.
What we have:
Node.js server (on localhost) running on Fedora Red Hat
NO PHP
Most pages are html + javascript + jQuery
To be more clear, here is what we'd like to happen:
-->User goes to http:// localhost /index.html
-->User selects colors, pushes "submit" button.
-->Selected colors go to the bash script (on the server) ./sendColors [listOfColors]
-->The bash script does it's thing.
================
Things I've tried
child_process.spawn
I WISH I could do this on the html page:
var spawn = require('child_process').spawn;
ls = spawn(commandLine, [listOfColors]);
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
ls.on('close', function (code) {
console.log('child process exited with code ' + code);
});
but this script is server-side, not client-side, so I can't run it on the html page (I believe). The error I get when I try to run this is that require is undefined.
browserify
I've tried installinst browserify, but the machine we are using isn't connected to the internet, and cannot use npm install. I've manually copied over the files to usr/lib and "required" it fine, but then it said that it couldn't find require "through", which is in browserify's index.js...
getRuntime
tried this thing:
var bash_exit_code = 0; // global to provide exit code from bash shell invocation
function bash(command)
{
var c; // a character of the shell's stdout stream
var retval = ""; // the return value is the stdout of the shell
var rt = Runtime.getRuntime(); // get current runTime object
var shell = rt.exec("bash -c '" + command + "'"); // start the shell
var shellIn = shell.getInputStream(); // this captures the output from the command
while ((c = shellIn.read()) != -1) // loop to capture shell's stdout
{
retval += String.fromCharCode(c); // one character at a time
}
bash_exit_code = shell.waitFor(); // wait for the shell to finish and get the return code
shellIn.close(); // close the shell's output stream
return retval;
}
said it didn't know what Runtime was
RequireJS
I've looked into RequireJS, but didn't understand how to use it in my case
eval
I've tried eval also... but I think that's for algebric expressions... didn't work.
ActiveX
even tried activeX:
variable=new ActiveXObject(...
said it didn't know what ActiveXObject is
================
Currently what I'm trying
HttpServer.js:
var http = require('http');
...
var colors = require('./colorsRequest.js').Request;
...
http.get('http://localhost/colorsRequest', function(req, res){
// run your request.js script
// when index.html makes the ajax call to www.yoursite.com/request, this runs
// you can also require your request.js as a module (above) and call on that:
res.send(colors.getList()); // try res.json() if getList() returns an object or array
console.log("Got response ");// + res.statusCode);
});
colorsRequest.js
var RequestClass = function() {
console.log("HELLO");
};
// now expose with module.exports:
exports.Request = RequestClass;
index.html
...
var colorsList = ...
...
$.get('http://localhost/colorsRequest', function(colors) {
$('#response').html(colorsList); // show the list
});
I'm getting
GET http://localhost/colorsRequest 404 (Not Found)
Anyone got any ideas?
Here's a simple boilerplate for the server (which uses Express, so you might need to install that first: npm install express):
var spawn = require('child_process').spawn;
var express = require('express');
var app = express();
app.use(express.static(__dirname));
app.get('/colorsRequest', function(req, res) {
var command = spawn(__dirname + '/run.sh', [ req.query.color || '' ]);
var output = [];
command.stdout.on('data', function(chunk) {
output.push(chunk);
});
command.on('close', function(code) {
if (code === 0)
res.send(Buffer.concat(output));
else
res.send(500); // when the script fails, generate a Server Error HTTP response
});
});
app.listen(3000);
You can pass it a color, and it will run the shellscript run.sh (of which it assumes is located in the same directory as the server JS file) with the color passed as argument:
curl -i localhost:3000/colorsRequest?color=green
# this runs './run.sh green' on the server
Here's a boilerplate HTML page (save it as index.html, put it in the same directory as the server code and the shell script, start the server, and open http://localhost:3000 in your browser):
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<select>
<optgroup label="Pick a color:">
<option>green</option>
<option>blue</option>
<option>yellow</option>
<option>orange</option>
</optgroup>
</select>
<script>
$('select').on('change', function() {
$.get('/colorsRequest', { color : $(this).val() });
});
</script>
</body>
</html>
You are on the right way with your first approach, the child_process.spawn variant. Ofcourse you can't put this in the HTML page, as it is then executed in the browser, not in the server, but you can easily create a request in the browser (AJAX or page load, depending on what you need), that triggers running this script in the server.

Categories