Upload progress bar using session in PHP 5.4 with codeigniter - javascript

With reference to this tutorial. Tracking upload progress with php . I want to make it work in Codeigniter. I am not getting point to start to make it work in CI. I want to upload files and also track progress.
In my CI view
<?php $arr = array("id"=>"myform");
echo form_open_multipart("welcome/uploads",$arr); ?>
<input type="hidden" value="myForm" name="<?php echo ini_get("session.upload_progress.name"); ?>">
<table>
<tr>
<td>file</td>
<td><input type="file" name="images[]" multiple></td>
</tr>
<tr>
<td>name</td>
<td><input type="text" name="naam"></td>
</tr>
<tr>
<td></td>
<td><input type="submit"></td>
</tr>
</table>
<?php echo form_close(); ?>
<div id="bar_blank">
script
function toggleBarVisibility() {
var e = document.getElementById("bar_blank");
e.style.display = (e.style.display == "block") ? "none" : "block";
}
function createRequestObject() {
var http;
if (navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
http = new XMLHttpRequest();
}
return http;
}
function sendRequest() {
var http = createRequestObject();
http.open("GET", "<?php echo base_url().'index.php/welcome/progress' ?>");
http.onreadystatechange = function () { handleResponse(http); };
http.send(null);
}
function handleResponse(http) {
var response;
if (http.readyState == 4) {
response = http.responseText;
document.getElementById("bar_color").style.width = response + "%";
document.getElementById("status").innerHTML = response + "%";
if (response < 100) {
setTimeout("sendRequest()", 1000);
}
else {
toggleBarVisibility();
document.getElementById("status").innerHTML = "Done.";
}
}
}
function startUpload() {
toggleBarVisibility();
setTimeout("sendRequest()", 1000);
}
(function () {
document.getElementById("myForm").onsubmit = startUpload; //error is here
})();
According to above tutorials, its in core php. When submitting form CI request to controller dashboard/addRoom and my page gets refresh anyhow. But in tutorials, Form redirects to PHP_SELF (same php file). I am not getting any idea on it. Please help me.
Controller
function progress()
{
session_start();
$key = ini_get("session.upload_progress.prefix") . "myForm";
if (!empty($_SESSION[$key])) {
$current = $_SESSION[$key]["bytes_processed"];
$total = $_SESSION[$key]["content_length"];
echo $current < $total ? ceil($current / $total * 100) : 100;
}
else {
echo 100;
}
}
public function uploads()
{
if(!empty($_FILES['images']['name'][0]))
{
//uploadinf file code
}
}

If you want to do it with only jQuery then i have used jQuery Form Submit Plugin, which will give you the progress and more. As you said in comments you don't need any plugin then follow these steps and implement like the tutorial suggesting.
Lets assume you have controller dashboard and method addRoom is displaying the your html form:
class Dashboard extends CI_Controller {
function addRoom() {
// Detect URI: http://example.com/dashboard/addRoom/upload_file
$upload_req = $this->uri->segment("3");
if( $upload_req == "upload_file" ) {
// Do the file upload Actions
}
// Generate Form
$this->load->view("Generate_view");
}
}
View:
<?php
$ar = array("class"=>"form-horizontal");
echo form_open_multipart('dashboard/addRoom/upload_file',$ar);
?>
<input type="text" name="fileName">
<input type="file" name="upload">
<input type="submit" value="add">
<?php echo form_close(); ?>
In this case your form is still on the same controller and method even you submit or not.
Update: According to updated answer, please use codeigniter default libraries for Session and File Uploads, In case of JS error, use console tab(Chrome) to debug error, or if you are using firefox then use firebug extension to debug Javascript.

If you just want to show upload progress there are many plugins available to do so, I don't know why you specifically mentioned Session in you title.
Here is a very nice and simple plugin which will work with any PHP framework with ease.
Code Sample
<script>
/*jslint unparam: true */
/*global window, $ */
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = window.location.hostname === 'blueimp.github.io' ?
'//jquery-file-upload.appspot.com/' : 'server/php/';
$('#fileupload').fileupload({
url: url,
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo('#files');
});
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
</script>

You're missing (I don't see it in your code) that the tutorial in your question declare and use an hidden iframe in the target attribute of the the upload form, this is a way to handle uploads preventing the form page to refresh (the action url will be loaded into the iframe).
google for hidden iframe upload (and eventually for formdata upload which nowadays should be a better way to handle uploads and show progress with few javascript)
here an old example which use the hidden iframe Ajax File Upload Response Handling
update
You should change the code in your view to $arr = array("id"=>"myForm")
Currently I see it is array("id"=>"myform") (all lowercase)
getElementById is case sensitive and you use .getElementById("myForm").onsubmit
When you use some javascript and something isn't working as expected the browser's javascript console is the first place to look, you should see an error like (chrome):
Uncaught TypeError: Cannot set property 'onsubmit' of null
This is because getElementById fail to find an element with id myForm and return null, in the html/DOM it is really named myform.
update
So, I got the thing working, instead of welcome controller I've created a new Upload controller (uppercase because I'm using CI 3 dev, should be easy to adapt it to old versions), below the working files.
The url will be http://your-host/optional-dir/index.php/upload.
application/controllers/Upload.php:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Upload extends CI_Controller {
public function index() {
$this->load->helper(array('form', 'url'));
$this->load->view('upload');
}
function progress() {
session_start();
$key = ini_get("session.upload_progress.prefix") . "myForm";
if (!empty($_SESSION[$key])) {
$current = $_SESSION[$key]["bytes_processed"];
$total = $_SESSION[$key]["content_length"];
echo $current < $total ? ceil($current / $total * 100) : 100;
} else {
echo 100;
}
}
public function uploads() {
if(!empty($_FILES['images']['name'][0])) {
//uploadinf file code
}
}
}
application/views/upload.php:
<!DOCTYPE html>
<html>
<head>
<title>upload</title>
<style>
#bar_blank {
border: solid 1px #000;
height: 20px;
width: 300px;
}
#bar_color {
background-color: #006666;
height: 20px;
width: 0px;
}
#bar_blank, #hidden_iframe {
display: none;
}
</style>
</head>
<body>
<?php $arr = array("id"=>"myForm", "target"=>"hidden_iframe");
echo form_open_multipart("upload/uploads",$arr); ?>
<input type="hidden" value="myForm" name="<?php echo ini_get("session.upload_progress.name"); ?>">
<table>
<tr>
<td>file</td>
<td><input type="file" name="images[]" multiple></td>
</tr>
<tr>
<td>name</td>
<td><input type="text" name="naam"></td>
</tr>
<tr>
<td></td>
<td><input type="submit"></td>
</tr>
</table>
<?php echo form_close(); ?>
<iframe id="hidden_iframe" name="hidden_iframe" src="about:blank"></iframe>
<div id="status"></div>
<div id="bar_blank">
<div id="bar_color"></div>
</div>
<?php include_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'upload.js.php'); ?>
</body>
</html>
./application/views/upload.js.php:
<script>
function toggleBarVisibility() {
console.log('toggleBarVisibility');
var e = document.getElementById("bar_blank");
e.style.display = (e.style.display == "block") ? "none" : "block";
}
function createRequestObject() {
console.log('createRequestObject');
var http;
if (navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http = new XMLHttpRequest();
}
return http;
}
function sendRequest() {
console.log('sendRequest');
var http = createRequestObject();
http.open("GET", "<?php echo base_url().'index.php/upload/progress' ?>");
http.onreadystatechange = function () { handleResponse(http); };
http.send(null);
}
function handleResponse(http) {
console.log('handleResponse');
var response;
if (http.readyState == 4) {
response = http.responseText;
document.getElementById("bar_color").style.width = response + "%";
document.getElementById("status").innerHTML = response + "%";
if (response < 100) {
setTimeout("sendRequest()", 1000);
} else {
toggleBarVisibility();
document.getElementById("status").innerHTML = "Done.";
}
}
}
function startUpload() {
console.log('startUpload');
toggleBarVisibility();
setTimeout("sendRequest()", 1000);
}
(function () {
console.log('init');
document.getElementById("myForm").onsubmit = startUpload; //error is here
})();
</script>
notice
I'm using a raw include_once for convenience, because php base_url is used inside the javascript, probably would be better have a small inline javascript in the view's html which declare a javascript variable with the base_url value then include the static javascript from an assets directory as usual.

the tutorial i have seen actually you have to write AJAX in your view, and call the controller via ajax not via form submission with button. so than your page will not get refreshed. take a close look on the tutorial you have provided the link, and when you scroll down you will see javascript where it send HTTP requests via AJAX for example
function createRequestObject() {
var http;
if (navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
http = new XMLHttpRequest();
}
return http;
}
this is a 1 function where it create XMLHttpRequests to get response from file where you have to get response via XMLHttpRequest from your controller.
Regards

Related

Return current response from PHP file while AJAX request is working [duplicate]

<form enctype="multipart/form-data" action="upload.php" method="POST">
<input name="uploaded" type="file" />
<input type="submit" value="Upload" />
</form>
<?php
if(isset($_REQUEST['submit'])){
$target = "data/".basename( $_FILES['uploaded']['name']) ;
move_uploaded_file($_FILES['uploaded']['tmp_name'], $target);
}
?>
I know Javascript, AJAX and JQuery etc very well and I believe an upload progress bar can be created using PHP, AJAX and Javascript etc.
I am surprised how to get the size of upload (meaning each second I want to know, how much of the file is uploaded and how much is remaining, I think it should be possible using AJAX etc) file during upload is in process.
Here is link to the PHP manual but I didn't understand that:
http://php.net/manual/en/session.upload-progress.php
Is there any other method to show the upload progress bar using PHP and AJAX but without use of any external extension of PHP? I don't have access to php.ini
Introduction
The PHP Doc is very detailed it says
The upload progress will be available in the $_SESSION superglobal when an upload is in progress, and when POSTing a variable of the same name as the session.upload_progress.name INI setting is set to. When PHP detects such POST requests, it will populate an array in the $_SESSION, where the index is a concatenated value of the session.upload_progress.prefix and session.upload_progress.name INI options. The key is typically retrieved by reading these INI settings, i.e.
All the information you require is all ready in the PHP session naming
start_time
content_length
bytes_processed
File Information ( Supports Multiple )
All you need is to extract this information and display it in your HTML form.
Basic Example
a.html
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
var intval = null;
var percentage = 0 ;
function startMonitor() {
$.getJSON('b.php',
function (data) {
if (data) {
percentage = Math.round((data.bytes_processed / data.content_length) * 100);
$("#progressbar").progressbar({value: percentage});
$('#progress-txt').html('Uploading ' + percentage + '%');
}
if(!data || percentage == 100){
$('#progress-txt').html('Complete');
stopInterval();
}
});
}
function startInterval() {
if (intval == null) {
intval = window.setInterval(function () {startMonitor()}, 200)
} else {
stopInterval()
}
}
function stopInterval() {
if (intval != null) {
window.clearInterval(intval)
intval = null;
$("#progressbar").hide();
$('#progress-txt').html('Complete');
}
}
startInterval();
</script>
b.php
session_start();
header('Content-type: application/json');
echo json_encode($_SESSION["upload_progress_upload"]);
Example with PHP Session Upload Progress
Here is a better optimized version from PHP Session Upload Progress
JavaScript
$('#fileupload').bind('fileuploadsend', function (e, data) {
// This feature is only useful for browsers which rely on the iframe transport:
if (data.dataType.substr(0, 6) === 'iframe') {
// Set PHP's session.upload_progress.name value:
var progressObj = {
name: 'PHP_SESSION_UPLOAD_PROGRESS',
value: (new Date()).getTime() // pseudo unique ID
};
data.formData.push(progressObj);
// Start the progress polling:
data.context.data('interval', setInterval(function () {
$.get('progress.php', $.param([progressObj]), function (result) {
// Trigger a fileupload progress event,
// using the result as progress data:
e = document.createEvent('Event');
e.initEvent('progress', false, true);
$.extend(e, result);
$('#fileupload').data('fileupload')._onProgress(e, data);
}, 'json');
}, 1000)); // poll every second
}
}).bind('fileuploadalways', function (e, data) {
clearInterval(data.context.data('interval'));
});
progress.php
$s = $_SESSION['upload_progress_'.intval($_GET['PHP_SESSION_UPLOAD_PROGRESS'])];
$progress = array(
'lengthComputable' => true,
'loaded' => $s['bytes_processed'],
'total' => $s['content_length']
);
echo json_encode($progress);
Other Examples
Tracking Upload Progress with PHP and JavaScript
PHP-5.4-Upload-Progress-Example
This is my code its working fine Try it :
Demo URL (broken link)
http://codesolution.in/dev/jQuery/file_upload_with_progressbar/
Try this below code:
HTML:
<!doctype html>
<head>
<title>File Upload Progress Demo #1</title>
<style>
body { padding: 30px }
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }
.progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
.percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
<h1>File Upload Progress Demo #1</h1>
<code><input type="file" name="myfile"></code>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploadedfile"><br>
<input type="submit" value="Upload File to Server">
</form>
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
bar.width("100%");
percent.html("100%");
status.html(xhr.responseText);
}
});
})();
</script>
</body>
</html>
upload.php :
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
May I suggest you FileDrop.
I used it to make a progess bar, and it's pretty easy.
The only downside I met, is some problems working with large amounts of data, because it dosen't seem to clear up old files -- can be fixed manually.
Not written as JQuery, but it's pretty nice anyway, and the author answers questions pretty fast.
While it may be good fun to write the code for a progress bar, why not choose an existing implementation. Andrew Valums wrote an excellent one and you can find it here:
http://fineuploader.com/
I use it in all my projects and it works like a charm.
First of all, make sure you have PHP 5.4 installed on your machine. You didn't tag php-5.4 so I don't know. Check by calling echo phpversion(); (or php -v from the command line).
Anyway, assuming you have the correct version, you must be able to set the correct values in the php.ini file. Since you say you can't do that, it's not worth me launching into an explanation on how to do it.
As a fallback solution, use a Flash object uploader.
XMLHTTPREQUSET2
var xhr = new XMLHttpRequest();
xhr.open('GET', 'video.avi', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var blob = this.response;
/*
var img = document.createElement('img');
img.onload = function(e) {
window.URL.revokeObjectURL(img.src); // Clean up after yourself.
};
img.src = window.URL.createObjectURL(blob);
document.body.appendChild(img);
/*...*/
}
};
xhr.addEventListener("progress", updateProgress, false);
xhr.send();
function updateProgress (oEvent) {
if (oEvent.lengthComputable) {
var percentComplete = oEvent.loaded / oEvent.total;
console.log(percentComplete)
} else {
// Unable to compute progress information since the total size is unknown
}
}

Call PHP from JavaScript function [duplicate]

I am trying to call a PHP function from an external PHP file into a JavaScript script. My code is different and large, so I am writing a sample code here.
This is my PHP code:
<?php
function add($a,$b){
$c=$a+$b;
return $c;
}
function mult($a,$b){
$c=$a*$b;
return $c;
}
function divide($a,$b){
$c=$a/$b;
return $c;
}
?>
This is my JavaScript code:
<script>
var phpadd= add(1,2); //call the php add function
var phpmult= mult(1,2); //call the php mult function
var phpdivide= divide(1,2); //call the php divide function
</script>
So this is what I want to do.
My original PHP file doesn't include these mathematical functions but the idea is same.
If some how it doesn't have a proper solution, then may you please suggest an alternative, but it should call values from external PHP.
Yes, you can do ajax request to server with your data in request parameters, like this (very simple):
Note that the following code uses jQuery
jQuery.ajax({
type: "POST",
url: 'your_functions_address.php',
dataType: 'json',
data: {functionname: 'add', arguments: [1, 2]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
and your_functions_address.php like this:
<?php
header('Content-Type: application/json');
$aResult = array();
if( !isset($_POST['functionname']) ) { $aResult['error'] = 'No function name!'; }
if( !isset($_POST['arguments']) ) { $aResult['error'] = 'No function arguments!'; }
if( !isset($aResult['error']) ) {
switch($_POST['functionname']) {
case 'add':
if( !is_array($_POST['arguments']) || (count($_POST['arguments']) < 2) ) {
$aResult['error'] = 'Error in arguments!';
}
else {
$aResult['result'] = add(floatval($_POST['arguments'][0]), floatval($_POST['arguments'][1]));
}
break;
default:
$aResult['error'] = 'Not found function '.$_POST['functionname'].'!';
break;
}
}
echo json_encode($aResult);
?>
Try This
<script>
var phpadd= <?php echo add(1,2);?> //call the php add function
var phpmult= <?php echo mult(1,2);?> //call the php mult function
var phpdivide= <?php echo divide(1,2);?> //call the php divide function
</script>
use document.write
for example,
<script>
document.write(' <?php add(1,2); ?> ');
document.write(' <?php milt(1,2); ?> ');
document.write(' <?php divide(1,2); ?> ');
</script>
You need to create an API :
Your js functions execute AJAX requests on your web service
var mult = function(arg1, arg2)
$.ajax({
url: "webservice.php?action=mult&arg1="+arg1+"&arg2="+arg2
}).done(function(data) {
console.log(data);
});
}
on the php side, you'll have to check the action parameter in order to execute the propre function (basically a switch statement on the $_GET["action"] variable)
index.php
<body>
...
<input id="Div7" name="Txt_Nombre" maxlenght="100px" placeholder="Nombre" />
<input id="Div8" name="Txt_Correo" maxlenght="100px" placeholder="Correo" />
<textarea id="Div9" name="Txt_Pregunta" placeholder="Pregunta" /></textarea>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$(".Txt_Enviar").click(function() { EnviarCorreo(); });
});
function EnviarCorreo()
{
jQuery.ajax({
type: "POST",
url: 'servicios.php',
data: {functionname: 'enviaCorreo', arguments: [$(".Txt_Nombre").val(), $(".Txt_Correo").val(), $(".Txt_Pregunta").val()]},
success:function(data) {
alert(data);
}
});
}
</script>
servicios.php
<?php
include ("correo.php");
$nombre = $_POST["Txt_Nombre"];
$correo = $_POST["Txt_Corro"];
$pregunta = $_POST["Txt_Pregunta"];
switch($_POST["functionname"]){
case 'enviaCorreo':
EnviaCorreoDesdeWeb($nombre, $correo, $pregunta);
break;
}
?>
correo.php
<?php
function EnviaCorreoDesdeWeb($nombre, $correo, $pregunta)
{
...
}
?>
This work perfectly for me:
To call a PHP function (with parameters too) you can, like a lot of people said, send a parameter opening the PHP file and from there check the value of the parameter to call the function. But you can also do that lot of people say it's impossible: directly call the proper PHP function, without adding code to the PHP file.
I found a way:
This for JavaScript:
function callPHP(expression, objs, afterHandler) {
expression = expression.trim();
var si = expression.indexOf("(");
if (si == -1)
expression += "()";
else if (Object.keys(objs).length > 0) {
var sfrom = expression.substring(si + 1);
var se = sfrom.indexOf(")");
var result = sfrom.substring(0, se).trim();
if (result.length > 0) {
var params = result.split(",");
var theend = expression.substring(expression.length - sfrom.length + se);
expression = expression.substring(0, si + 1);
for (var i = 0; i < params.length; i++) {
var param = params[i].trim();
if (param in objs) {
var value = objs[param];
if (typeof value == "string")
value = "'" + value + "'";
if (typeof value != "undefined")
expression += value + ",";
}
}
expression = expression.substring(0, expression.length - 1) + theend;
}
}
var doc = document.location;
var phpFile = "URL of your PHP file";
var php =
"$docl = str_replace('/', '\\\\', '" + doc + "'); $absUrl = str_replace($docl, $_SERVER['DOCUMENT_ROOT'], str_replace('/', '\\\\', '" + phpFile + "'));" +
"$fileName = basename($absUrl);$folder = substr($absUrl, 0, strlen($absUrl) - strlen($fileName));" +
"set_include_path($folder);include $fileName;" + expression + ";";
var url = doc + "/phpCompiler.php" + "?code=" + encodeURIComponent(php);
$.ajax({
type: 'GET',
url: url,
complete: function(resp){
var response = resp.responseText;
afterHandler(response);
}
});
}
This for a PHP file which isn't your PHP file, but another, which path is written in url variable of JS function callPHP , and it's required to evaluate PHP code. This file is called 'phpCompiler.php' and it's in the root directory of your website:
<?php
$code = urldecode($_REQUEST['code']);
$lines = explode(";", $code);
foreach($lines as $line)
eval(trim($line, " ") . ";");
?>
So, your PHP code remain equals except return values, which will be echoed:
<?php
function add($a,$b){
$c=$a+$b;
echo $c;
}
function mult($a,$b){
$c=$a*$b;
echo $c;
}
function divide($a,$b){
$c=$a/$b;
echo $c;
}
?>
I suggest you to remember that jQuery is required:
Download it from Google CDN:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
or from Microsoft CDN: "I prefer Google! :)"
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
Better is to download the file from one of two CDNs and put it as local file, so the startup loading of your website's faster!The choice is to you!
Now you finished! I just tell you how to use callPHP function. This is the JavaScript to call PHP:
//Names of parameters are custom, they haven't to be equals of these of the PHP file.
//These fake names are required to assign value to the parameters in PHP
//using an hash table.
callPHP("add(num1, num2)", {
'num1' : 1,
'num2' : 2
},
function(output) {
alert(output); //This to display the output of the PHP file.
});
If you actually want to send data to a php script for example you can do this:
The php:
<?php
$a = $_REQUEST['a'];
$b = $_REQUEST['b']; //totally sanitized
echo $a + $b;
?>
Js (using jquery):
$.post("/path/to/above.php", {a: something, b: something}, function(data){
$('#somediv').html(data);
});
Void Function
<?php
function printMessage() {
echo "Hello World!";
}
?>
<script>
document.write("<?php printMessage() ?>");
</script>
Value Returning Function
<?php
function getMessage() {
return "Hello World!";
}
?>
<script>
var text = "<?php echo getMessage() ?>";
</script>
I wrote some script for me its working .. I hope it may useful to you
<?php
if(#$_POST['add'])
{
function add()
{
$a="You clicked on add fun";
echo $a;
}
add();
}
else if (#$_POST['sub'])
{
function sub()
{
$a="You clicked on sub funn";
echo $a;
}
sub();
}
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<input type="submit" name="add" Value="Call Add fun">
<input type="submit" name="sub" Value="Call Sub funn">
<?php echo #$a; ?>
</form>
Try looking at CASSIS. The idea is to mix PHP with JS so both can work on client and server side.
I created this library JS PHP Import which you can download from github, and use whenever and wherever you want.
The library allows importing php functions and class methods into javascript browser environment thus they can be accessed as javascript functions and methods by using their actual names. The code uses javascript promises so you can chain functions returns.
I hope it may useful to you.
Example:
<script>
$scandir(PATH_TO_FOLDER).then(function(result) {
resultObj.html(result.join('<br>'));
});
$system('ls -l').then(function(result) {
resultObj.append(result);
});
$str_replace(' ').then(function(result) {
resultObj.append(result);
});
// Chaining functions
$testfn(34, 56).exec(function(result) { // first call
return $testfn(34, result); // second call with the result of the first call as a parameter
}).exec(function(result) {
resultObj.append('result: ' + result + '<br><br>');
});
</script>
I made a version only using js, without using any dependencies. I think this is the shorest solution but probably not the best one since it doens't check for any errors.
javascript
var a = 1;
var b = 2;
function add(){
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "YOUR_SERVER/function.php?a="+a+"&b="+b, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
var c = add(a, b)
function.php file
<?php echo $_GET["a"] + $_GET["b"]?>
c = 3
I created this library, may be of help to you.
MyPHP client and server side library
Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!-- include MyPHP.js -->
<script src="MyPHP.js"></script>
<!-- use MyPHP class -->
<script>
const php = new MyPHP;
php.auth = 'hashed-key';
// call a php class
const phpClass = php.fromClass('Authentication' or 'Moorexa\\Authentication', <pass aguments for constructor here>);
// call a method in that class
phpClass.method('login', <arguments>);
// you can keep chaining here...
// finally let's call this class
php.call(phpClass).then((response)=>{
// returns a promise.
});
// calling a function is quite simple also
php.call('say_hello', <arguments>).then((response)=>{
// returns a promise
});
// if your response has a script tag and you need to update your dom call just call
php.html(response);
</script>
</body>
</html>

Receiving data from JavaScript into PHP

Working example below, hopefully this will help others learn!
I'm using AJAX in javascript to send a JSON string to PHP.
I'm not familiar with AJAX, javascript or php, so this is taking me a while to get started.
I have a html file with a username field, password field, and login button.
Then I have a javascript file that takes the username pass and sends it to a php file.
I know the php file is being accessed because I am seeing the test echo in console.
I just cant figure out how to access the data I'm sending to the php.
script.
function attemptLogin(){
var inputUserName = JSON.stringify(document.getElementById("userName").value);
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', 'ajax.php', true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send(inputUserName);
}
ajax.php
<?php
echo"TestInPHP";
?>
For now all I want to do is echo the username back to console, I'm sure the syntax is something simple, I just cant figure out what it is.
Here is an edit for the working code thanks to SuperKevin in the
comments below. This code will take the string in the username and
password fields in HTML by the JS, send it to PHP and then sent back
to the JS to output to the browser console window.
index.html
<input type="text" name="userID" id="userName" placeholder="UserID">
<input type="password" name="password" id = passW placeholder="Password">
<button type="button" id = "button" onclick="attemptLogin()">Click to Login</button>
script.js
function attemptLogin(){
var inputUserName =
JSON.stringify(document.getElementById("userName").value);
// console.log(inputUserName);
var inputPassword = JSON.stringify(document.getElementById("passW").value);
var cURL = 'ajax.php?fname='+inputUserName+'&pass='+inputPassword;
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', cURL, true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send();
}
ajax.php
<?php
echo $_GET['fname'];
echo $_GET['pass'];
?>
Here's a simple example of how you would make a vanilla call.
This is our main file, call it index.php.
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "delete.php", true);
xhttp.send();
</script>
Here's our server script. delete.php
<?php
echo "HELLO THERE";
Now, if you wanted to pass data to your script you can do the following:
xhttp.open("GET", "delete.php?fname=Henry&lname=Ford", true);
xhttp.send();
To access this data you can use the global $_GET array in php. Which would look like this:
$fname = $_GET['fname'];
$lname = $_GET['lname'];
Obviously, you have to sanitize the data, but that's the gist of it.
For a much more in depth tutorial visit W3Schools Tutorial PHP - AJAX.
You can see all the data sent to your php with :
<?php
print_r($_GET); //if it's send via the method GET
print_r($_POST); //if it's send via the method POST
?>
So, in your case it will be something like :
<?php
echo $_GET['username'];
?>
If you're not using jQuery then don't pay attention to my answer and stick to the pure javascript answers.
With jQuery you can do something like this:
First Page:
$.ajax({
url: 'sportsComparison.php',
type: 'post',
dataType: 'html',
data: {
BaseballNumber = 42,
SoccerNumber = 10
},
success: function(data) {
console.log(data);
});
which will send the value 42 and 10 to sportsComparison.php with variable names BaseballNumber and SoccerNumber. On the PHP page they can then be retrieved using POST (or GET if that's how they were sent originally), some calculations performed, and then sent back.
sportsComparison.php:
<?php
$BaseballValue = $_POST["BaseballNumber"];
$SoccerValue = $_POST["SoccerNumber"];
$TotalValue = $BaseballValue * $SoccerValue;
print "<span class='TotalValue'>".$TotalValue."</span>";
?>
This will return a span tag with the class of TotalValue and the value of 420 and print it in the console.
Just a simple way to do ajax using jQuery. Don't forget commas in the parameter list.

ajax responseText contains php source code

I am trying to make a ajax call and validate a input html field. But, instead of getting simple echo message. I am getting complete source code in responseText.
JavaScript
function checkUsername() {
document.getElementById("username").className = "thinking";
usernameRequest = createRequest();
if (usernameRequest == null)
alert("Unable to create request");
else {
var theName = document.getElementById("username").value;
var username = escape(theName);
var url= "checkName.php?username=" + username;
usernameRequest.onreadystatechange = showUsernameStatus;
usernameRequest.open("GET", url, true);
usernameRequest.send(null);
}
}
function showUsernameStatus() {
alert(usernameRequest.responseText);
if (usernameRequest.readyState == 4)
{
if (usernameRequest.status == 200) {
if (usernameRequest.responseText == "okay") {
document.getElementById("username").className = "approved";
document.getElementById("register").disabled = false;
}
else {
document.getElementById("username").className = "denied";
document.getElementById("username").focus();
document.getElementById("username").select();
document.getElementById("register").disabled = true;
}
}
}
}
checkName.php
<?php
$takenUsernames = array('bill', 'ted');
sleep(2);
if (!in_array($_REQUEST['username'],$takenUsernames )) {
echo 'okay';
} else {
echo 'denied';
?>
Previously, I tried to integrate PHP into tomcat, but I was advice it was not a good practice. TRIAL TO INTEGRATE PHP
What I can make out of this situation is that Tomcat is not parsing PHP file and instead it is returning the source code. I believe there should be a means for me to let tomcat parse php files and send the right response.
I have also tried with simple php code, with one statment <?php echo 'HELLO'; ?> and I still get the source code.
Thanks in advance.
NOTE : I do not know php, I am working an example from HEAD FIRST AJAX
you need to install PHP for Tomcat & set its path to compile it.see the below link for php configuration settings.
http://php-java-bridge.sourceforge.net/doc/tomcat6.php
http://www.studytrails.com/blog/php-on-a-java-app-server-apache-tomcat-using-quercus/

post data to PHP page in external server and load content from JavaScript in local computer

I want to post data to a PHP file in a server (www.domaine.com) using a JavaScript located in computer / mobile app
example : test.php
<?php
$x = $_POST['count'];
for ($i = 0; $i < $x; $x++)
echo $x;
?>
data to be post using JavaScript and PSOT method to test.php
example
input
test.php / post data : count=5
output
01234
I want JavaScript to get me the output (01234) after posting (count=5) to (test.php) located in external server (www.domaine.com)
I basically develop in C# but as I'm obliged to do a cross-platform mobile app I switched to JavaScript (won't use Xamarin) for C# I was able to do everything using WebBrowser but not anymore in JavaScript, isn't there any object equivalent to WebBrowser in .NET ?
I need it for a mobile app that will load data from GPS Tracking website, API returns data in both XML and JSON
note : I don't have access to the external server
Here I'll give you a pretty good example of how these things are usually managed.
Still, it's up to you and your programming experience to grasp the meaning of it.
html and js example:
<form action="" id="formId" method="post" accept-charset="utf-8">
<label for="inputNumber">Input something: </label>
<input type="number" id="inputNumber" name="count"></input>
</form>
<span id="submit">Submit</span>
<script>
var getPhpResponse = function( data ) {
console.log("manage php response HERE");
}
$("#submit").click(function(){
$("#formId").submit();
});
$(document).ready(function () {
$("#formId").bind("submit", function (event)
{
$.ajax({
async: true,
data: $("#formId").serialize(),
success: function(data, textStatus) {
getPhpResponse( data )
},
type:"POST",
url:"name/and/location/of/php/file.php"
});
return false;
});
});
</script>
file.php example:
<?php
$x = $_POST['count'];
echo '{"response":"';
for ($i = 0; $i < $x; $i++)
{
echo $i;
}
echo '"}';
Poxriptum:
There should be further input validation, one can't trust the type="number" just yet.
That the submit button is a span instead of an input is a personal choice that makes difference just for styling purposes.
You should read up on AJAX and JSON.
Consider using a PHP framework, such as CakePHP; it may serve you well.
This answer assumes you have access to the server. If you don't, then you should be reading the API documentation instead of asking questions on SO without even detailing which API you are talking about.
Edit:
Here is the $less version.
<form action="" id="formId" method="post" accept-charset="utf-8">
<label for="inputNumber">Input something: </label>
<input type="number" id="inputNumber" name="count"></input>
</form>
<span id="submit">Submit</span>
<script>
document.getElementById("submit").onclick = function () {
var url = 'name/and/location/of/php/file.php';
var userInput = encodeURIComponent(document.getElementById("inputNumber").value);
var data = "count=" + userInput;
makeRequest( data, url );
};
var getPhpResponse = function( data ) {
console.log("manage php response HERE");
console.log(data);
parsed = JSON.parse(data);
console.log(parsed);
}
var xhr = new XMLHttpRequest();
var makeRequest = function( data, url ) {
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.send(data);
};
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if ( xhr.readyState == 4 )
{
if ( xhr.status == 200 || window.location.href.indexOf("http") == -1 )
{
getPhpResponse(xhr.responseText);
}
else
{
console.log("Manage error here");
}
}
}
</script>

Categories

Resources