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>
Related
Currently I have this code as shown below.
Whereby, when I click on the button, it will show either success or fail.
I have another php script on another webpage to call from it.
Currently I call the php script, using the php file name. I would like to check is there a way for me to call the php file using a function in the url?
The reason is because, in the php script, I would have several functions to call from. I do not want to create multiple php file.
below is my code.
<script>
function bookBTN(x) {
$.getJSON('http://localhost/movieOne.php?method=getSeatNum1&seatNum=' + x, function(data) {
if (data.avail == "yes") {
alert("Success");
}
else { alert("Failure"); }
});
}
</script>
<script>
function viewBTN(x) {
$.getJSON('http://localhost/movieOne.php?method=getSeatNum2&seatNum=' + x, function(data) {
if (data.avail == "yes") {
alert("Success");
}
else { alert("Failure"); }
});
}
</script>
movieOne.php
<?php
$seatNum= $_GET["seatNum"];
getSeatNum1($seatNum);
function getSeatNum1($seatNum) {
$seatNum = $_GET["seatNum"];
$url = 'http://movie.com/movieOne?seatNum=' . $seatNum;
$result = file_get_contents($url);
echo $result;
?>
<?php
$seatNum= $_GET["seatNum"];
getSeatNum2($seatNum);
function getSeatNum2($seatNum) {
$seatNum = $_GET["seatNum"];
$url = 'http://movie.com/movieOne?seatNum=' . $seatNum;
$result = file_get_contents($url);
echo $result;
?>
When I only run http://localhost/movieOne.php?method=getSeatNum1&seatNum=' + x and having only 1 php function inside movieOne.php , it works fine.
When I run http://localhost/movieOne.php?method=getSeatNum1&seatNum=' + xand http://localhost/movieOne.php?method=getSeatNum2&seatNum=' + x , having only 1 php function inside movieOne.php , it works fine too.
However when I run http://localhost/movieOne.php?method=getSeatNum1&seatNum=' + xand http://localhost/movieOne.php?method=getSeatNum2&seatNum=' + x , and have 2 different function (as the code above), the button doesn't work.
If you want to call function from url like codeigniter do, i have an example for you
URL example: http://localhost/jastip/ajax/request.php/get_orders
(function () {
$url_function = explode('/', $_SERVER['REQUEST_URI']);
$function_name = get_defined_functions()['user'];
if (in_array($url_function[4], $function_name)) {
$index = array_search($url_function[4], $function_name);
$dynamic_fun = $function_name[$index];
$dynamic_fun();
} else {
var_dump("Page not found");
die;
}
})();
function get_orders()
{
echo "get orders";
}
function get_something()
{
echo "get something";
}
I'm not sure if it's just me or what but this seems really odd. When I click a button I have jquery send out javascript variables to a php site to be handled there. However on the php site they come up as undefined indexes. The weird part, is that they show on the html page through php's echo. NOTE: The html button is an input type="button", not a submit because I don't want to reload the page.
jquery:
var timestampst = $(timestamp).val();
var objNamest = $(objInst).val();
$.post("sendCalc.php", {
postobjNamest:objInst,
posttimestampst:timestamp},
function(data){
$("#divResult").html(data);
});
php:
//used for troubleshooting, returns Array() on the php page and Array ( [posttimestampst] => 1399973296 [postobjNamest] => test2-1
print_r($_POST);
//when the if and else are used it the php page always echos Not Working, meaning that the $_POST is not set somehow. However, the html page shows the echoed variables in the "divResult" as it should.
//when I try the code without the if and else, the php page returns Undefined Index: posttimstamp/postobjNamest. However, the html page still shows the echoed variables.
if(isset($_POST["posttimestampst"])){
$timestamp = $_POST["posttimestampst"];
echo $timestamp;
echo "<br>";
$objName = $_POST["postobjNamest"];
echo $objName;
echo "<br>";
}
else{
echo "Not Working";
}
Any help is greatly appreciated!
EDIT:
//gets selected object from a dropdown menu
selectedObj = document.getElementById("selectObj").value;
//objName in javascript taken from $objName var in php that is and the beginning of the html page.
objName = <?php echo json_encode($objName); ?>;
//objInst takes the value of the dropdown menu and assigns it as the [] in objName array
objInst = objName[selectedObj];
//timestamp is set in php and imported to java
var timestamp = <?php echo $timestamp; ?>;
EDIT 2:
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js""> </script>
</head>
<h3>Optionen und Berechnen</h3>
<form name="myForm" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<div id="divCalc">
</div>
<input id="addObject" type="button" onclick="addObj()" value="Add Object">
<br>
<br>
<div id="divAddObj" hidden="true">
</div>
<br>
<div id="divCalc">
</div>
<div id="divResult"></div>
</form>
<script type="text/javascript" name="addObject">
var objName;
var selectedObj;
var objInst;
var timestamp = <?php echo $timestamp; ?>;
//Start select dropdown
var select_element = document.createElement("select");
select_element.setAttribute("id", "selectObj");
select_element.setAttribute("name", "selectObject");
options = new Array();
objName = <?php echo json_encode($objName); ?>;
for ( var i = 0; i < (<?php echo $arrayNum; ?>); i++ ){
options.push(new Option(objName[i], i, false, false));
}
options[0].selected = true;
for ( var option in options ){
select_element.appendChild(options[option]);
}
//End select dropdown
//check selected object
selectedObj = document.getElementById("selectObj").value;
objInst = objName[selectedObj];
var timestampst = $(timestamp).val();
var objNamest = $(objInst).val();
$.post("sendCalc.php", {
postobjNamest:objInst,
posttimestampst:timestamp},
function(data){
$("#divResult").html(data);
});
</script>
Change your code to:
objNamest = objInst.value;
timestampst = timestamp.value;
$.post("sendCalc.php", {
postobjNamest: objNamest,
posttimestampst: timestampst },
function(data){
$("#divResult").html(data);
});
You are missing the data parameter of $.post().
From the docs about post():
data
Type: PlainObject or String:
A plain object or string that is sent
to the server with the request.
Your params postobjNamest & posttimestampst do not exist for the $.post() method
It should be
$.post("sendCalc.php", {
// An "on-the-fly" created JavaScript object, which is valid
data: {
postobjNamest: objInst,
posttimestampst: timestamp
},
function(data){
var content = $.parseJSON(data);
window.console.log(content.postobjNamest);
window.console.log(content.posttimestampst);
}
});
From the docs about parseJSON():
Description: Takes a well-formed JSON string and returns the resulting
JavaScript object.
And in the PHP:
$objName = $_POST['postobjNamest'];
$timestamp = $_POST['posttimestampst'];
// Returning your values to client
// Don't echo them in PHP
echo json_encode(array(
'postobjNamest' => $objName,
'posttimestampst' => $timestamp
);
From the docs about json_encode():
json_encode — Returns the JSON representation of a value
The Javascript Object:
// Declaration
var Obj = {
propertyOne: 'value', // string
propertyTwo: 52.3654, // float
methodOne: function () {
// your function code
},
methodTwo: function () {
// your function code
}
}
//Instances
var objOne = new Obj();
objOne.methodOne();
objOne.propertyTwo;
var objTwo = new Obj();
objTwo.methodOne();
objTwo.propertyTwo;
I have created an array in PHP. And I need to get that array into a javascript function. This is what I have tried.
$sql = "SELECT * FROM Questions WHERE Form_ID='$FormID' AND QuestionsDataHave='YES' ORDER BY Questions_ID+0, Questions_ID";
$GetTheValidationRule = mysqli_query($con, $sql);
$ValidatinArray = array();
$J = 0;
while($RowVal = mysqli_fetch_array($GetTheValidationRule)){
$ValidatinArray[$J] = $RowVal['Validation_Type'];
$J++;
}
And This is my javascript code.
$(document).ready(function() {
$("form").submit(function(){
var P= <?php echo json_encode($ValidatinArray); ?>;
var O = P.length;
alert(O);
return false;
});
});
But this gives me an error like this
SyntaxError: syntax error
var P= <br />
Isn't it possible to get the array in this way. Please someone help me.
UPDATE: This is the final out put of my error message
<script>
$(document).ready(function() {
$("form").submit(function(){
alert('AAAAAAAAAAAAAAAAAAA');
var IDsOfTheColumns = document.getElementsByName("DataColumnID[]");
var Data = document.getElementsByName("DataInputValue[]");
var A = IDsOfTheColumns.length;
alert(A);
<br />
<b>Notice</b>: Undefined variable: ValidatinArray in <b>C:\xampp\htdocs\PHIS\CreateTheForm.php</b> on line <b>16</b><br />
var P = null; return false;
});
});
</script>
Sorry for the late response...Try rewriting your document.ready as:
$(document).ready(function() {
$("form").submit(function(){
var P = JSON.parse('<?php echo json_encode($ValidatinArray); ?>');
var O = P.length;
alert(O);
return false;
});
});
The problem is, that in the variable $ValidatinArray is not available in the file, that prints the javascript code. Maybe this manual page helps you:
http://www.php.net/manual/en/language.variables.scope.php
Try this:
<?php
echo ' <script>
$(document).ready(function() {
$("form").submit(function(){
var P= '. json_encode($ValidatinArray) . ';
var O=P.length;
alert(O);
return false;
});
});
</script>';
?>
What you do is simply echo the js using php.
Your tag is coming from the form that you are submitting. check what your form data is before you encode it to verify the output. you can use console.log($("form));
Also using form is not a good idea since if you have more than one form and form is a global name. For forms you should give it a unique form name like "myForm" so that you can target that specific form.
Hope this helps
first of all I recommend that you verify that the variable $ValidatinArray exists and that it is being passed correctly to the file where you are doing the "echo".
the error you show indicates that from the beginning the variable that contains the array does not exist.
if the SQL query is inside a php function check that you are returning the variable.
example
<?php
function GetData(){
// ... here is the code to get the information from the database ...
return $ValidatinArray;
}
$ValidatinArray = GetData();
?>
once you have validated that this array exists we can now see the problem of passing the data to JavaScript:
It all depends on how the structure is, if you have the PHP code and the JavaScript function in the same file you can simply use this method inside the php fil:
// ... php file code
?>
<script>
$(document).ready(function() {
$("form").submit(function(){
// you can use any of the two methods that I leave you here
// Using only json_enconde
var P= <?= json_encode($ValidatinArray) ?>;
// Using json_enconde to pass the array as a string and using JSON.parse to have JavaScript convert it to an object
var P= JSON.parse('<?= json_encode($ValidatinArray) ?>');
var O = P.length;
alert(O);
return false;
});
});
</script>
In case the php file is executed at the moment of opening the page and the file that contains your function in JavaScript is in another file:
You can generate a "global" JavaScript variable from the php code as follows
// ... code php file
?>
<script>
window.variablename = <?= json_encode($ValidatinArray) ?>
</script>
<?php
inside your JS file you can receive the array like this
$(document).ready(function() {
$("form").submit(function(){
var P= window.variablename ;
var O = P.length;
alert(O);
return false;
});
});
PD: using <?= is equivalent to using echo
In php json_encode the array like this:
$inlinejs='';
$inlinejs.='var validatinArray=\''.addslashes(json_encode($ValidatinArray)).'\';'."\n";
$inlinejs.='var validatinArray=eval(\'(\' + validatinArray + \')\');'."\n";
and in javascript:
$(document).ready(function() {
$("form").submit(function(){
<?php echo $inlinejs; ?>
console.log(validatinArray);
});
});
I have a slider which uses javascript. I am trying to update the display of my web page based on the slider values. I tried to use ajax function to send the data to another PHP page to update the display. But I am not getting anything in my page. Here is my code so far.
<?php
$i = 1;
while (++$i <= $_SESSION['totalcolumns']) {
$range = $_SESSION["min-column-$i"] . ',' . $_SESSION["max-column-$i"];?>
<br><?php echo "Keyword" ?>
<?php echo $i -1 ?>
<br><input type="text" data-slider="true" data-slider-range="<?php echo $range ?>" data-slider-step="1">
<?php } ?>
<button type="button" onclick="loadXMLDoc()">Update</button>
<script>
$("[data-slider]")
.each(function () {
var range;
var input = $(this);
$("<span>").addClass("output")
.insertAfter(input);
range = input.data("slider-range").split(",");
$("<span>").addClass("range")
.html(range[0])
.insertBefore(input);
$("<span>").addClass("range")
.html(range[1])
.insertAfter(input);
})
.bind("slider:ready slider:changed", function (event, data) {
$(this).nextAll(".output:first")
.html(data.value.toFixed(2));
});
</script>
<script>
function loadXMLDoc()
{
alert "Am I coming here";
$.ajax({
type: "POST",
url: 'update.php',
data: { value : data.value },
success: function(data)
{
alert("success!");
}
});
}
</script>
I read in another post that javascript variables are available across functions and so I am trying to use the variable data.value inside my another javascript function loadXMLDoc(). But I do not see the value getting displayed in my update.php page. My update.php file is as below.
<?php
if(isset($_POST['value']))
{
$uid = $_POST['value'];
echo "Am I getting printed";
echo $uid;
}
?>
Can someone please help me on this?
In the loadXMLDoc function I don't see data defined anywhere. I think that could be one of the problems. Also, when you're doing jquery ajax requests be sure to have a fail callback. The fail callback will tell you if the request fails which can be very informative.
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
To make the data variable accessible in the XMLLoadDoc function you could try putting it in the global scope (kind of a 'no-no', but its OK for a use case like this). So, at the top, declare var masterData, then when you have data in the .bind callback set masterData = data; and then in loadXMLDoc refer to masterData
Since my AS3 and Php/Java knowledge is not good I got stuck on this problem.
I have a AS3 function that sends bitmap data to PHP file to save some image, and in this function I also added some other arguments and that new argument should give me a string value that i need.
private function saveImageForFacebook(evt:MouseEvent)
// Sends the Bitmap data to php
{
var bitmapData:BitmapData=new BitmapData(wheelCanvas.width, wheelCanvas.height);
bitmapData.draw(wheelCanvas);
var jpgEncoder:JPGEncoder = new JPGEncoder(80);
var byteArray:ByteArray = jpgEncoder.encode(bitmapData);
var header:URLRequestHeader = new URLRequestHeader ("Content-type", "application/octet-stream");
var jpgURLRequest:URLRequest = new URLRequest ("http://www.someurl.com/flash-test/saveimg.php");
jpgURLRequest.requestHeaders.push(header);
jpgURLRequest.method = URLRequestMethod.POST;
jpgURLRequest.data = byteArray;
navigateToURL(jpgURLRequest, "_blank");
// Creates the string value that I need to use in saveimg.php
var suffixUrl:String = "";
for(var i:int=0; i < customizedColorArr.length; i++)
{
if(customizedColorArr[i] != "")
{
suffixUrl += "&" + customizedPartValueArr[i] + "=" + customizedColorArr[i];
}
}
suffixUrl = wheelName + "&variant_name=" + variantName + suffixUrl;
trace(suffixUrl);
}
Somehow I need to trace "suffixUrl" value in my saveimg.php file, but i don't know how.
This is how my php file looks and where suffixUrl need to go.
<?php
if ( isset ( $GLOBALS["HTTP_RAW_POST_DATA"] )) {
$uniqueStamp = date(U);
//$filename = "temp_image.jpg";
$filename = $uniqueStamp . ".jpg";
$fp = fopen( $filename,"wb");
$result = fwrite( $fp, $GLOBALS[ 'HTTP_RAW_POST_DATA' ] );
fclose( $fp );
}
?>
<meta property="og:image" content="http://www.someurl.com/flash-test/src_server/<?php echo $filename ; ?>" />
<SCRIPT LANGUAGE="JavaScript">
function redirect () {
window.location.href = "http://www.facebook.com/sharer.php?u=http://www.someurl/flash-test/Main3D.html?"+suffixUrl, '_self';
}
</SCRIPT>
<BODY onload="redirect()">
You will see "suffixUrl" in my javascript function. That's where I'm trying to treace that value.
You don't want to send a variable to Javascript; you want to send a variable to PHP.
Move the suffix generation code block above the Bitmap sending part, and then change this line.
var jpgURLRequest:URLRequest = new URLRequest ("http://www.someurl.com/flash-test/saveimg.php?suffixUrl=" + suffixUrl);
Then, in the PHP
window.location.href = "http://www.facebook.com/sharer.php?u=http://www.someurl/flash-test/Main3D.html?" + <?php echo $_GET['suffixUrl'] ?>, '_self';
This will work, but you will also have to sanitize the input for security.
Assuming your "php file" is the one that's embedding your Flash, you can use ExternalInterface to call your redirect function from Flash.
Flash :
ExternalInterface.call("redirect", suffixUrl);
Note : You need to import flash.external.ExternalInterface;
JavaScript :
function redirect (suffixUrl) {
window.location.href = "http://www.facebook.com/sharer.php?u=http://www.someurl/flash-test/Main3D.html?" + suffixUrl;
}