jquery post variable shows in html but not php - javascript

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;

Related

Populate DIV with an PHP arrayelement based on a click on a link

What I want:
A list of links show events - a click on such a link shall show further details in a special DIV on the same page.
Idea:
I read from the database all events:
$queryEventString = 'Match (e:Event) WHERE e.eventStatus = "not_processed"
RETURN e.UUID as eventUUID,
e.eventFrom as eventFrom,
e.eventType as eventType,
e.eventTime as eventTime,
e.eventSubject as eventSubject,
e.eventBody as eventBody';
$resultEvent = $client->run($queryEventString);
This gives me all available events in the DB that are not yet processed.
I assgin all found events identified by their UUID into a PHP array for further processing
foreach ($resultEvent as $eventDetail)
{
$eventInfo[$eventDetail['eventUUID']]['eventBody'] = html_entity_decode($eventDetail['eventBody']);
$eventInfo[$eventDetail['eventUUID']]['eventForm'] = $eventDetail['eventFrom'];
$eventInfo[$eventDetail['eventUUID']]['eventDate'] = date("d.m.Y H:i",
$eventDetail['eventTime']);
$eventInfo[$eventDetail['eventUUID']]['eventSubject'] = $eventDetail['eventSubject'];
}
Having that 2-dimensional array "eventInfo" I build the list
echo '<div class="event-panel">';
echo '<ul id="event-column" style="list-style: none;">';
foreach($eventInfo AS $eventKey => $eventDetail)
{
echo '<eventlink data-id="'.$eventKey.'">'.$eventKey.'</eventlink><br>';
}
echo '</ul>';
echo '</div>';
Last but not least I create a DIV to store the desired eventBody-Information:
echo <<<EOT
<div id="info-div">
<div id="info"></div>
</div>
EOT;
To populate now the DIV when a link is clicked I tried this:
$(document).ready(function (){
var passedArray = <?php echo json_encode($eventInfo); ?>;
$('#event-column eventlink').click(function (){
var p = $(this).attr('data-id');
$('#info').html().passedArray[p];
});
});
I wanted to pass the php-Array with JSON to make it available inside the function.
With the click-effect I wanted to load from this php-array the related array-element ['eventBody'] with the UUID given by the link-click.
Somehow I am stuck. I am able to pass the UUDI key to the javascript area and can write it into the DIV but I cannot identify a php-element by the given UUID and put the content into the DIV.
Any hint is appreciated, thank you.
As requested here is the code in total:
<?php
// Including jQuery
echo '<script src="http://code.jquery.com/jquery-1.11.3.min.js">/script>';
// Querying the Neo4J DB
$queryEventString = 'Match (e:Event) WHERE e.eventStatus = "not_processed"
RETURN e.UUID as eventUUID,
e.eventFrom as eventFrom,
e.eventType as eventType,
e.eventTime as eventTime,
e.eventSubject as eventSubject,
e.eventBody as eventBody';
$resultEvent = $client->run($queryEventString);
// Parsing result and build the 2-dimensional array $eventInfo
foreach ($resultEvent as $eventDetail)
{
$eventInfo[$eventDetail['eventUUID']]['eventBody'] = html_entity_decode($eventDetail['eventBody']);
$eventInfo[$eventDetail['eventUUID']]['eventForm'] = $eventDetail['eventFrom'];
$eventInfo[$eventDetail['eventUUID']]['eventDate'] = date("d.m.Y H:i", $eventDetail['eventTime']);
$eventInfo[$eventDetail['eventUUID']]['eventSubject'] = $eventDetail['eventSubject'];
}
// Displaying list of events with UUID as forwarded parameter (-> JS)
echo '<div class="event-panel">';
echo '<ul id="event-column" style="list-style: none;">';
foreach($eventInfo AS $eventKey => $eventDetail)
{
echo '<eventlink data-id="'.$eventKey.'">'.$eventKey.'</eventlink><br>';
}
echo '</ul>';
echo '</div>';
// Creating a DIV Container to hold $eventInfo[eventUUID][eventBody]
echo <<<EOT
<div id="info-div">
<div id="info"></div>
</div>
EOT;
// JavaScript Part
echo <<<EOT
<script type="text/javascript">
$(document).ready(function (){
var passedArray = <?php echo json_encode($eventInfo); ?>;
console.log(passedArray);
$('#event-column eventlink').click(function (){
var p = $(this).attr('data-id');
$('#info').html().passedArray[p];
});
});
</script>
EOT;
?>
2nd EDIT:
I have stripped down everything to this functioncode, which is at the end of the php-file and no longer wrapped in the php-tags. So its like standard html. This way I avoid the uncaught syntax error.
<script type='text/javascript'>
$(document).ready(function (){
var passedArray = '<?php echo json_encode(array($test_array)); ?>';
console.log(passedArray);
$('#event-column eventlink').click(function (){
var p = $(this).attr('data-id');
console.log(p);
console.log(passedArray[p]['eventBody']);
$('#info').text(passedArray[p]);
});
});
</script>
Outcome:
I can console.log the array, which shows as a test:
[[{"UUID":"60762d3eb9949596701a2dfb700cd2c9","eventBody":"Hallo"},{"UUID":"620c16ced5097bf60f718abca7d979f8","eventBody":"Ciao"}]]
I see also that when I click a link that the UUID key is passed to the Javascript-Script:
60762d3eb9949596701a2dfb700cd2c9
But when I want to assign the related eventBody-element I receive this error:
Uncaught TypeError: passedArray[p] is undefined
As I have the array and the key I assume it must be a syntax error in this line:
console.log(passedArray[p]['eventBody']);
So two questions left:
How would I access one element of the given array?
How can I then populate the DIV with the element ['UUID']['eventBody']? Not sure if this is the way to go: $('#info').html().passedArray[p];
Resolution (with Uwe's help):
function findme(p) {
var passedArray = '<?php echo json_encode($test_array); ?>';
passedArray = JSON.parse(passedArray);
// here we search that object in your array which has the key value pair of
// UUID : p
var result = passedArray.find((obj) => {
return obj.UUID === p;
});
document.getElementById("result").innerHTML = result.eventBody;
}
thanks to your support here (Kudos to Uwe) here is the solution:
As we use jQuery we need to include this in the head:
echo '<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>';
The Javascript-Function (written in HTML, not in PHP tags):
function findme(p) {
var passedArray = '<?php echo json_encode($eventInfo); ?>';
passedArray = JSON.parse(passedArray);
// here we search that object in your array which has the key value pair of
// UUID : p
var result = passedArray.find((obj) => {
return obj.UUID === p;
});
document.getElementById("result").innerHTML = result.eventBody;
}
I was not able to find a way to write the whole code within PHP tags, as the double echo (Start and inside the array handover) and the additional PHP?-tags always generates syntax errors - thus the JS function is written as HTML-code outside the PHP code.
In the PHP the UUID of the array is passed onClick to the JS function - looks like
echo ' Find the element by UUID Brackets -- '.$UUID.'';
Please pay attention to the escaped quotation marks - important to avoid an error in JS that allows no identifiers starting with a number.
The DIV is marked by
echo '<p id="result"></p>';
For testing I made an array like this:
$eventInfo= array();
$eventInfo[] = array('UUID' => '60762d3', 'eventBody' => 'Text 1');
$eventInfo[] = array('UUID' => '620c16c', 'eventBody' => 'Text 2');
$eventInfo[] = array('UUID' => '6076299', 'eventBody' => 'Text 3');
$eventInfo[] = array('UUID' => '620c16c', 'eventBody' => 'Text 4');

AJAX change a div value on click inside PHP loop

I'm looking to change the content of a div based on a link being clicked on a php page. The link is created through a loop and I need to pass several parameters through the URL. The div is also created through the loop so the id of the div will be variable. I'm having trouble with the AJAX to make this happen.
Below is my php:
<?php
if ($result3->num_rows > 0) {
while($row3 = $result3->fetch_assoc()) {
$tripDestination = $row3["tripDestination"];
$sessionID = $row3["$sessionID"];
$price = $row3["price"];
echo "" . $tripDestination . ' - ' . $price . "";
echo "<br />";
echo "<div id=\"trips\"></div>";
}
}
?>
I need to pass two variables in the URL: sessionID and tripDestination. I was able to load static content, but it needs to be dynamic. Here's my AJAX so far
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url: "sqlUpload.php?sessionID=35&tripDestination=SFO", success: function(result){
$("#div1").html(result);
}});
});
});
</script>
Thanks in advance!
I might think about sending the information from a data attribute on the link:
PHP:
<?php
if ($result3->num_rows > 0) {
while($row3 = $result3->fetch_assoc()) {
$tripDestination = $row3["tripDestination"];
$sessionID = $row3[$sessionID];
$price = $row3["price"];
// Store the organized data
$data = array(
'tripDestination'=>$tripDestination,
'sessionID'=>$sessionID,
'price'=>$price
);
?>
<!-- You can store the array into json on the data attribute -->
<a href="#" class="data-set" data-information='<?php echo json_encode($data) ?>'><?php echo $tripDestination.' - '.$price ?></a>
<br />
<div class="data-response"></div>
<?php
}
}
?>
JavaScript:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// When user clicks the <a> that has the "data-set" class
$('.data-set').on('click',function(e){
// I like to prevent default here, just incase
e.preventDefault();
// Assign current obj
var getObj = $(this);
// Fetch the json from the attribute
var getData = getObj.data('information');
// Send
$.ajax({
// Just send to the page, no query string
url: "sqlUpload.php",
// I would send POST, personally
type: 'GET',
// This is the data being sent
data: getData,
success: function(response){
// Presumably you want to put the response into the
// accompanying div, then you can just do next()
getObj.next('.data-response').html(response);
}});
});
});
</script>

Echoed Javascript Code from PHP Via AJAX Not Running

My code is meant to get the author of an inputted book using the Google Books API via AJAX. If nothing is inputted it prints "Empty". What it actually does is print out the Javascript code when a book is inputted. When nothing is inputted, it prints "Empty" as it should. How could I modify my code to make the echoed Javascript execute and hence get the author of an inputted book?
Just to see, I replaced the echo part with echo "<script>document.getElementById('txtBox').innerHTML = 'Hello';</script>";. It also prints out the javascript code, so I don't think it has something to do with using the API.
getAuthor.html
<!DOCTYPE html>
<html>
<body>
<!-- Input -->
<div class="form">
<form onsubmit="makeRequest(); return false">
<input type="text" id="inputText" name="inputText">
<input type="submit">
</form>
</div>
<br>
<!-- Output -->
<div class="txtBox">
<textarea id="txtBox">
</textarea>
</div>
<!-- AJAX to create output using jEcho.php file-->
<script>
function makeRequest() {
httpRequest = new XMLHttpRequest();
console.log(httpRequest.responseText);
httpRequest.onreadystatechange = function() {
document.getElementById("txtBox").innerHTML = httpRequest.responseText;
};
httpRequest.open("POST", "jEcho.php", true);
httpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
httpRequest.send("inputText=" + document.getElementById("inputText").value);
}
</script>
</body>
</html>
jEcho.php
<?php
$input = $_POST["inputText"];
if ($input == "") {
echo "Empty";
} else {
// used to parse
// e.g. The Rosie Project -> The+Rosie+Project
$temp = str_replace(" ", "+", $input);
// create appropiate source
$scriptSource = "https://www.googleapis.com/books/v1/volumes?q=$temp&callback=handleResponse";
echo "<script>
function handleResponse(response) {
var item = response.items[0];
document.getElementById('txtBox').innerHTML = item.volumeInfo.authors[0];
}
</script>
<script src='$scriptSource'></script>";
}
?>
Links
Echoing Javascript From PHP:
How to call a JavaScript function from PHP?
Echoing javascript from PHP
Google Books API:
https://developers.google.com/books/docs/v1/getting_started
https://developers.google.com/books/docs/v1/using
<script> elements are only run when your page is first loaded. Script elements created later on, either by assigning to an element's .innerHTML, creating them using document.createElement(), or otherwise, are not executed.
If you want to have a PHP script send back code to be evaluated, you'll have to do that directly, e.g:
httpRequest.onreadystatechange = function() {
eval(httpRequest.responseText);
};
(And remove the <script> tags from the response.)
Try setting header in jEcho.php file (not tested)
header('Content-Type: application/javascript');
I'm not allowed to comment so:
I'm not certain what has caused it for but could <script src='$scriptSource'></script>"; be called before the handleResponse function. I'm not too sure what is causing it, at the moment, that is my best idea.
Also could you not just have the url already in the code like this: (jEcho.php)
<?php
$input = $_POST["inputText"];
if ($input == "") {
echo "Empty";
} else {
// used to parse
// e.g. The Rosie Project -> The+Rosie+Project
$temp = str_replace(" ", "+", $input);
// create appropiate source
//$scriptSource = "https://www.googleapis.com/books/v1/volumes?q=$temp&callback=handleResponse";
echo "
<script src='https://www.googleapis.com/books/v1/volumes?q=$temp&callback=handleResponse'></script>
<script>
function handleResponse(response) {
var item = response.items[0];
document.getElementById('txtBox').innerHTML = item.volumeInfo.authors[0];
}
</script>";
}
?>

Sending PHP array to Javascript

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);
});
});

How can I call PHP functions by JavaScript?

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>

Categories