Pass JavaScript function through Ajax to PHP file - javascript

What I am trying to do:
I am working on a script intending to offer the user choices and depending on which choice they make, come up with a new choice. I have made two scripts for this, one for my HTML and the structure of my page and one for my PHP (getting the information from my server) and JavaScript (building the generated choices).
I am then using AJAX to communicate between these two scripts, or at least, that's what I am trying to do, but I am very new when it comes to AJAX and I cannot make it work.
I am trying to pass or somehow start the function 'generateProblems' from my page when one of the 3 buttons are pressed, preferably with the param 'id'.
Here's part of my index.html:
<div id="testpile" class="inner cover">
<div id="buttons">
<p><a id="rat" class="btn btn-default" role="button">Rationel</a></p>
<p><a id="emo" class="btn btn-default" role="button">Emotionel</a></p>
<p><a id="per" class="btn btn-default" role="button">Personel</a></p>
</div>
</div>
<div id="testdrop" class="mastfoot">
<p>Drop numbers here</p>
</div>
<script type="text/javascript">
$("#buttons").find(".btn").click(function() {
var id = this.id;
$("#testpile").load("include/responseget.php");
$.post("include/responseget.php", {
choice: "id",
});
});
</script>
And here's my PHP / Javascript:
<?php include 'login.php';
//Query til at finde information til generation af question
$stmt = $conn->prepare("SELECT DISTINCT ResponseTitle, ResponseText FROM response Limit 8;");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$rTitle_array[] = $row['ResponseTitle'];
$rText_array[] = $row['ResponseText'];
}
json_encode($rTitle_array);
json_encode($rText_array);
// close connection
mysqli_close($conn);
?>
<script type="text/javascript">
$(function() {
var phase = 0;
var rTitle = <?php echo json_encode($rTitle_array); ?>;
var rText = <?php echo json_encode($rText_array); ?>;
function generateProblems(param) {
var problemDef = param;
$("#buttons").hide();
var numbers = [1, 2, 3, 4, 5, 6, 7, 8];
for (var i = 0; i < 8; i++) {
$('<div>' + rTitle[i] + '</div>').data('number', rTitle[i]).attr('id', 'problem' + rTitle[i]).appendTo('#testpile').draggable({
containment: '.site-wrapper',
stack: '#testpile div',
cursor: 'move',
revert: true
});
$('<div>' + rText[i] + '</div>').data('number', rText[i]).attr('id', 'problem' + rText[i]).appendTo('#testpile');
}
$('#testdrop').droppable({
drop: handleDropEvent,
accept: '#testpile div'
});
function handleDropEvent(event, ui) {
var problemNumber = ui.draggable.data('number');
var problemCombination = problemDef + problemNumber;
ui.draggable.draggable('disable');
ui.draggable.draggable('option', 'revert', false);
phase++;
alert('ProblemCombination is "' + problemCombination + '", phase is "' + phase + '" ');
$("#testpile").children().hide();
generateProblems(problemCombination);
}
}
});
</script>
What am I doing wrong? The code worked pretty well before I split it up, but now clicking one of the buttons generate nothing.

This is not the right way to do. Keep your php away from html/js. You can't access to your html from another script which is not directly included in it.
Re-add your javascript part to index.html
In your php script return
something at the end like return json_encode($rTitle_array);
In your
jquery/ajax post, get the returned value and use it
A sample from the jquery doc:
var posting = $.post( url, { s: term } );
// Put the results in a div
posting.done(function( data ) {
var content = $( data ).find( "#content" );
$( "#result" ).empty().append( content );
});

Related

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>

Creating a JSON array from PHP and sending a GET request via JQuery

I'm pulling data from Google Calendar events and wanting to display it in my HTML markup. I've got the data being pulled successfully from Google and thought I was passing it into and array the proper way and encoding into JSON. I was also able to make the GET request via JQuery and confirmed it by checking the console to see if it was received. The problem was trying to display it in the HTML markup.
But, after further debugging, it seems my JSON array isn't correct. Almost as if it duplicates itself everytime it looks for more data from Google.
Here is my code:
<?php
header('Content-type: application/json');
error_reporting(E_ALL);
ini_set("display_errors", 1);
include('google-api-php-client-master/autoload.php');
date_default_timezone_set('America/New_York');
//TELL GOOGLE WHAT WE'RE DOING
$client = new Google_Client();
$client->setApplicationName("My Calendar");
$client->setDeveloperKey('my_api_key');
$cal = new Google_Service_Calendar($client);
$calendarId = 'my_calendar_id';
//TELL GOOGLE HOW WE WANT THE EVENTS
$params = array(
'singleEvents' => true, //CAN'T USE TIME MIN WITHOUT THIS, IT SAYS TO TREAT RECURRING EVENTS AS SINGLE EVENTS
'orderBy' => 'startTime',
'timeMin' => date(DateTime::ATOM),//ONLY PULL EVENTS STARTING TODAY
);
$events = $cal->events->listEvents($calendarId, $params);
$count = 0;
$items_to_show = 3;
$data = array();
foreach ($events->getItems() as $event)
{
if($count <= $items_to_show)
{
//Convert date to month and day
$eventDateStr = $event->start->dateTime;
if(empty($eventDateStr))
{
// it's an all day event
$eventDateStr = $event->start->date;
}
$temp_timezone = $event->start->timeZone;
if (!empty($temp_timezone))
{
$timezone = new DateTimeZone($temp_timezone); //GET THE TIME ZONE
}
else
{
$timezone = new DateTimeZone("America/New_York"); //Set your default timezone in case your events don't have one
}
if ($count >= $items_to_show)
{
break;
}
$eventdate = new DateTime($eventDateStr,$timezone);
$data[$count]['newmonth'] = $eventdate->format("M");
$data[$count]['newday'] = $eventdate->format("j");
$data[$count]['newtime'] = $eventdate->format("g:i A");
echo json_encode($data);
++$count; //INCREASE COUNT AND START AGAIN.
}
}
?>
Here is my JSON array (there are only 3 events on the calendar) but it looks like it duplicates or resets everytime it looks for more:
[{"newmonth":"Jan","newday":"16","newtime":"3:00 PM"}][{"newmonth":"Jan","newday":"16","newtime":"3:00 PM"},{"newmonth":"Jan","newday":"17","newtime":"2:00 PM"}][{"newmonth":"Jan","newday":"16","newtime":"3:00 PM"},{"newmonth":"Jan","newday":"17","newtime":"2:00 PM"},{"newmonth":"Jan","newday":"18","newtime":"3:00 AM"}]
Here is my JQuery that I want to display in the HTML automatically:
$(document).ready(function()
{
function load()
{
$.ajax
({
type: 'GET',
url: 'googlesidebar.php',
// data: {key: 'value'},
dataType: 'json',
success: function(data)
{
console.debug(data);
for (var i = 0; i < data.length; i++)
{
$('.newmonth').append(data[i].newmonth),
$('.newday').append(data[i].newday),
$('.newtime').append(data[i].newtime)
};
setTimeout(load, 5000);
},
error: function(data)
{
//called when there is an error
console.log(data.message);
}
});
};
load();
});
HTML Markup:
<!DOCTYPE html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div class="newmonth"></div>
<div class="newday"></div>
<div class="newtime"></div>
<footer>
</footer>
<script src="ajax.js"></script>
<script src="js/main.js"></script>
</body>
</html>
Any help would be greatly appreciated!

php: make array from pictures in a folder and display them interchangeably?

The following code is supposed to make an array from pictures found in a directory that end in .png using php, then allow buttons to change the pointer on the array and allow the page to display the current picture that the pointer is on. This doesnt seem to be working at all. Am I doing this correctly?
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
img {float:left; }
</style>
</head>
<body>
<?PHP
$pages = array ();
$dirname = "assets/pictures/";
$images = glob($dirname."*.png");
foreach($images as $image) {
$pages[] = $image;
}
?>
<?PHP
echo '<img src="'.current($pages).'" class="photo"/>';
function shownext() {
$mode = next($pages);
}
function showprev() {
$mode = prev($pages);
}
function showfirst() {
$mode = reset($pages);
}
function showlast() {
$mode = end($pages);
}
?>
first
previous
next
last
</body>
</html>
onclick will allow you to call a javascript function, while your showprev...showlast functions are all php functions. They are not available in javascript's scope.
Also, in your php code:
You are closing the loop right after $pages[] = $image, I think you intend to display (print/echo) all images.
You don't need a loop to copy $pages to $images. You can easily copy it: $pages = $images.
You should be aware that current only makes sense inside a loop and you are calling it after loop is closed.
I think though, that you are confusing server-side (i.e. php) and client-side (i.e. javascript) execution environments.
onclick , uses to trigger javascript functions.
You cant directly put your php functions on onclick="" events. Alternatively, if you want to use jQuery, you could use $.ajax to request the values on PHP. From there, after you got the image paths, manipulate the next, prev, first, last on the client side. Consider this example:
<?php
if(isset($_POST['getimages'])) {
$dirname = "assets/pictures/";
$images = glob($dirname."*.png");
// collect the images
foreach($images as $image) {
$pages[] = $image;
}
echo json_encode($pages);
exit;
}
?>
<img src="" alt="" id="images" width="200" height="200" />
<br/>
First
Previous
Next
Last
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var current_pointer = 0;
var images = [];
$.ajax({
url: 'index.php', // call the php file that will process it, i just used this in the same page
type: 'POST',
dataType: 'JSON',
data: {getimages: true},
success: function(response) {
// after a successful response from PHP
// use that data and create your own array in javascript
images = response;
$('#images').attr('src', images[current_pointer]);
}
});
// simple pointer to navigate the array you got from PHP
$('a.navigate').on('click', function(){
var current_val = $(this).attr('id');
switch(current_val) {
case 'first':
current_pointer = 0;
break;
case 'last':
current_pointer = images.length-1;
break;
case 'next':
current_pointer = (current_pointer >= images.length-1) ? images.length-1 : current_pointer+1;
break;
case 'previous':
current_pointer = (current_pointer < 0) ? 0 : current_pointer-1;
break;
}
$('#images').attr('src', images[current_pointer]);
});
});
</script>
The problem is echo '<img src="'.current($pages).'" class="photo"/>';
This will get echoed once, no matter howoften you change $pages afterwards. You also can't call PHP functions with JavaScript's onclick.
PHP will generate the page on server side! On a fully laoded page, most interaction with the user is done via JavaScript.
To achieve your desired result, you have to export the array to JavaScript and change the image src via JavaScript, a little research will help you.

Retrieving JSON from PHP File, and Append inside div

Im trying to do near real time graph update within my site. To do this im trying to basically reload a php file every 30 seconds. I made the data of PHP dynamically echo out json code as shown below. Ad inside the file is also <meta http-equiv="refresh" content="30"> which refreshes the file to recheck database.
{"todayCalculateCR":"5%"}{"todayEPC":"0.20"}{"todayCTR":"34%"}{"yesterdayCalculateCR":"35%"}{"yesterdayEPC":"0.03"}{"yesterdayCTR":"24%"}{"monthCalculateCR":"14%"}{"monthEPC":"0.07"}{"monthCTR":"24%"}
Basically now i want some jquery code to place on my index.php page to load this file, interpret the json code and append the data to the correct divs.
Example:
<div class="yesterdayEPC">0.03</div>
Ive been looking on jquery.com and on stack overflow for ways to basically take the above json data and append it.
$.get( "dashboard-stats.php", function( data ) {
$( "body" )
.append( "yesterdayEPC: " + data.yesterdayEPC ) // John
.append( "Time: " + data.yesterdayEPC ); // 2pm
}, "json" );
This is brief of PHP file making json:
$month_visits = mysql_num_rows(mysql_query("SELECT * FROMlocker_reportsWHEREuid= '$user_id' ANDmonth= '$month_date'"));
$month_clicks = mysql_num_rows(mysql_query("SELECT * FROMreportsWHEREuid= '$user_id' ANDmonth= '$month_date' ANDstatus= '1'"));
$month_leads = mysql_num_rows(mysql_query("SELECT * FROMreportsWHEREuid= '$user_id' ANDmonth= '$month_date' ANDstatus= '2'"));
if($month_leads == "" || $month_clicks == "")
{
echo json_encode(array("monthCalculateCR"=>"n/a"));
echo json_encode(array("monthEPC"=>"n/a"));
}
else
{
$monthCalculateCR = number_format($month_clicks / $month_leads)."%";
echo json_encode(array("monthCalculateCR"=>"".$monthCalculateCR.""));
$monthEPC = number_format($month_leads / $month_clicks, 2)."";
echo json_encode(array("monthEPC"=>"".$monthEPC.""));
}
if($month_visits == "")
{
echo json_encode(array("monthCTR"=>"n/a"));
}
else
{
$monthCTR = number_format($month_clicks / $month_visits, 2) * 100 . "%";
echo json_encode(array("monthCTR"=>"".$monthCTR.""));
}
Try with the setTimeout function to call the $.get() jQuery method to recall the php file that echos the JSON.
reload();
function reload(){
$.get( "yourFile.php", function( data ) {
//update table based on data
var jsonData = $.parseJSON(data);
$('#myDiv').append('callback called').append(data);
});
setTimeout(reload, 30000);
}
I fixed my problem by basically making the json in 1 bracket.
Then using a tutorial I found out I can do below.
Todayclicks: <span id="clicks">
<script>
var JSONObject = {"todayEarnings":"2.60","todayVisits":"62","todayClicks":"26","todayLeads":"3","todayCalculateCR":"9%","todayEPC":"0.12","todayCTR":"42%","yesterdayEarnings":"0.40","yesterdayClicks":"35","yesterdayVisits":"148","yesterdayLeads":"1","yesterdayCalculateCR":"35%","yesterdayEPC":"0.03","yesterdayCTR":"24%","monthEarnings":"3.00","monthClicks":"65","monthVisits":"242","monthLeads":"4","monthCalculateCR":"16%","monthEPC":"0.06","monthCTR":"27%"}
document.getElementById("clicks").innerHTML=JSONObject.todayClicks;
</script>

PHP in JavaScript using document.write();

I have quite a script that adds items into a table. I need to pull information from a MySQL database based on the UPC that is passed through the JavaScript.
I tried: document.write("<?php echo '375'; ?>"); just to see if it would work, and once the script got to that line, the page refreshed and displayed a blank white page.
The full JavaScript is below:
//setup before functions
var field = document.getElementById("UPC");
var typingTimer; //timer identifier
var doneTypingInterval = 1000; //time in ms, 1 seconds
//on keyup, start the countdown
$('#UPC').keyup(function(){
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
//on keydown, clear the countdown
$('#UPC').keydown(function(){
clearTimeout(typingTimer);
});
function doneTyping () {
//user is "finished typing," do something
if (field.value.length != 0) {
document.getElementById("noScan").className="hidden";
document.getElementById("checkout").className="";
document.getElementById("void").className="";
var upc=document.getElementById("UPC").value;
var price = document.write("<?php echo '375'; ?>");
var weight = parseInt(document.getElementById("weight").value);
var table=document.getElementById("ScannedItems");
var total = weight * price;
var row=table.insertRow(-1);
var cell1=row.insertCell(0);
var cell2=row.insertCell(1);
var cell3=row.insertCell(2);
var cell4=row.insertCell(3);
var cell5=row.insertCell(4);
var cell6=row.insertCell(5);
cell1.innerHTML=upc;
cell2.innerHTML="Example Description";
cell3.innerHTML = "$" + price.toFixed(2);
cell4.innerHTML = weight + " lbs";
cell5.innerHTML = "$" + total.toFixed(2);
cell5.setAttribute('data-total', total); // caches the total into data
cell6.innerHTML="<a class='add'><span class='glyphicon glyphicon-plus' style='padding-right:15px;'></span></a><a class='delete'><span class='glyphicon glyphicon-minus'></span></a>";
field.value ='';
var total = cell5.getAttribute('data-total');
var salesTax = Math.round(((total / 100) * 8.25)*100)/100;
var totalAmount = (total*1) + (salesTax * 1);
document.getElementById('displaysubtotal').innerHTML="$" + (Math.floor(total * 100) / 100).toFixed(2);
document.getElementById('displaytax').innerHTML="$" + salesTax;
document.getElementById('displaytotal').innerHTML="$" + totalAmount;
}
}
// Duplicate a scanned item
var $table = $('#ScannedItems');
$('#ScannedItems').on('click', '.add', function () {
var $tr = $(this).closest('tr').clone();
$table.append($tr);
});
// Remove a line item
var $table = $('#ScannedItems');
$('#ScannedItems').on('click', '.delete', function () {
var $tr = $(this).closest('tr').remove();
});
I must figure out how to get information from my database for this project or it is going to fail.
Javascript executes on the client side, PHP executes on the server side. So PHP is done executing before JS starts.
So in order to fetch new data, you'll need to initiate a call to your server. You can do this by either refreshing the page with the results you need or by creating an AJAX call.
To make it more clear, take a closer look at the example you gave. View the source code in your browser. It will come out as document.write("375");. That's because PHP echo'ed the string '375' into your JS code on the server side before sending the page to the browser (which is where the JS code executes).
PHP can generate JS code, but JS cannot generate PHP code (in the usual sense).
PHP is executed on the server before serving generate HTML to a clients browser. Any PHP code inserted by the javascript on the client will not run.
If you want to have code inserted dynamically from PHP, you might investigate how to use AJAX calls to run a separate PHP server-side script and insert the returned content.
You can perfectly use php inside javascript, because php executes before javascript reachs the browser. So the browser receives the page with the php result executed which builds the javascript sentence... the browser doesnt know that the javascript sentence was writen by you or by the php server.
document.write("<?php echo '375'; ?>");
try changing it to...
document.write("<?php echo("375"); ?>");
the "" are first seen by php server so the above should work.
or just in case you can escape the "
I also have this piece of code fully functional:
frameDoc.document.write sentence
<?php
echo("frameDoc.document.write(\"");
require('secciones/seccion_head2.html');
echo("\");");
?>
frameDoc.document.write sentence
BUT!!! inside the required html you cant use more than one line!!!!

Categories

Resources