I want to convert the following client side javascript code to server side PHP in order to protect some code. Below is a sample code of what I would like to have in PHP (and not using echo on each line, as this does not hide anything apart from the opening and closing PHP tags!)
function calc() {
var aa = document.a.lsofa.value * 40.77;
var bb = document.a.ssofa.value * 29.26;
var z90 = "Text here.";
var ctt = aa + bb;
ctt = parseInt(ctt);
tot = ctt;
if (tot < 1) {
var rslt = "Please enter relevant quantities in the form above.";
}
else {
var rslt = "Complete. We would require " + ctt.toString() + z95 + "";
}
document.a.answer.value = rslt
Also the onclick event of the form would need to be changed (I would like to keep the converted code on the same page an just call this function on form submit).
Any help would be appreciated.
You mean something like this:
header('Content-type: application/json');
$aa = $_GET["lsofa"] * 40.77;
$bb = $_GET["ssofa"] * 29.26;
$z90 = "Text here.";
$ctt = aa+bb;
$ctt = intval(ctt);
$tot = $ctt; // not useful
if ($tot<1) {
echo json_encode(array('result' => "Please enter relevant quantities in the form above."));
} else {
echo json_encode(array('result' => "Complete. We would require " . $ctt . $z95));
}
called with
$(function() {
$("#myForm").on("submit",function(e) {
e.preventDefault(); // stop submission
$.get("calc.php",$(this).serialize(),function(data) {
alert(data.result);
});
});
});
Related
Everybody . I'm doing some mini web-app but I'm new in programming
,I followed tutorial from "Learn Google Spreadsheets" on Youtube but get a little bit confuse
My App is very simple
1.User login Page (Check Usercode and Pass from firebase) --- DONE!
2.Get data (get Usercode and find data row from spreadsheet) --- DONE!
3.Pass Object to Table --- Need help
var ss= SpreadsheetApp.openById('1l2Q7C5qBF7EsDInlHi1Bv76jeRJwWjixKteBkc8i3ik');
var PayrollSheet = ss.getSheetByName("ข้อมูลล่าสุด") ;
var Route = {} ;
Route.path = function(route,callback){
Route[route] = callback ;
}
function doGet(e) {
Route.path("Login",LoadLogin) ;
Route.path("Table",LoadTable) ;
if(Route[e.parameters.v]){
return Route[e.parameters.v]() ;
}else {
return render("Login") ;
}
}
function LoadLogin(){
return HtmlService.createTemplateFromFile('Login').evaluate() ;
}
function LoadTable(Usercode){
var TargetRow = GetRow(Usercode) ;
var Data = PayrollSheet.getRange(TargetRow,1,1,18).getValues().flat();
var Round = PayrollSheet.getRange(1,2,1,2).getValues().flat();
return render("Table",{array:Data,round:Round}) ;
}
function render(file,argsObject){
var tmp = HtmlService.createTemplateFromFile(file);
if(argsObject){
var keys = Object.keys(argsObject) ;
keys.forEach(function(key){
tmp[key] = argsObject[key] ;
});
} // END IF
return tmp.evaluate() ;
}
Javascript in html file
<script>
function LoginUser() {
var usercodeIn = document.getElementById("Usercode").value;
var passwordIn = document.getElementById("Password").value;
google.script.run.withSuccessHandler(function(User){
if(User != 'FALSE') // Found User
{
document.getElementById("errorMessage").innerHTML = "welcome " + User ;
google.script.run.LoadTable(usercodeIn) ;
}
else if(User == 'FALSE') //Not Found User
{
document.getElementById("errorMessage").innerHTML = "Wrong Password!";
}
}).checkLogin(usercodeIn,passwordIn);
}
</script>
After Login successful I try to run Loadtable(usercode) to render Table.html with data base on usercode but It only login and show success prompt , but not render Table.html
This is sound pretty easy, but I really don't know what to do ,So please help Thank you
Provided there are no Date objects in argsObject you could simply do tmp.argsObject = argsObject.
Code.gs
function render(file,argsObject){
var tmp = HtmlService.createTemplateFromFile(file);
if(argsObject){
tmp.argsObject = argsObject.
}
return tmp.evaluate() ;
}
Then in your templeted HTML.
<table>
<? for (let i = 0; i < argsObject.array.length; i++) { ?>
<tr><td><?= argsObject.array[i] ?></td></tr>
<? } ?>
</table>
Reference
Templated HTML
I have an HMTL form with 3 fields on it, Firstname, Lastname and image upload file. When submit is pressed it calls the following JS script.
//main function to be called on submit
function processData() {
var firstName = document.querySelector('#first-name'),
lastName = document.querySelector('#last-name'),
imageUser = document.querySelector('#image-user');
var formSubmitData = {
'firstName': firstName.value,
'lastName': lastName.value,
'imageUser': imageUser.value
};
var dataString = JSON.stringify(formSubmitData);
if (navigator.onLine) {
sendDataToServer(dataString);
} else {
saveDataLocally(dataString);
}
firstName.value = '';
lastName.value = '';
imageUser.value = '';
}
//called on submit if device is online from processData()
function sendDataToServer(dataString) {
var myRequest = new XMLHttpRequest();
//new code added so data is sent to server
//displays popup message - data sent to server
myRequest.onreadystatechange = function() {
if (myRequest.readyState == 4 && myRequest.status == 200) {
console.log('Sent to server: ' + dataString + '');
window.localStorage.removeItem(dataString);
} else if (myRequest.readyState == 4 && myRequest.status != 200) {
console.log('Server request could not be completed');
saveDataLocally(dataString);
}
}
myRequest.open("POST", "write_test.php", true);
//Send the proper header information along with the request
myRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myRequest.send(dataString);
alert('Sent: ' + dataString + ''); //remove this line as only for example
}
As you will see it sends a POST request to the php page. The "datastring" is encoded as JSON.
I use the following PHP code to send the data to the SQL server, but all it does is create a blank record with no data but it does create a new record.
<?php
//TRYING NEW CODE TO EXTRACT DATA FROM dataString
$json = json_decode(file_get_contents("php://input"), true);
$data = json_decode($json, true);
echo '<pre>' . print_r($data, true) . '</pre>';
// INSERT into your contact table.
$sql="INSERT INTO contacts (firstName, lastName)VALUES('$firstName','$lastName')";
How do I get it to create records in SQL with data that has been submitted from the form??
I have no final solution as I don't have the form code. Hope you are ready to learn.
I'm worried about user image - don't send any image for testing, but a string (like path) or nothing, please.
js - change for double quotes:
var formSubmitData = {
"firstName" : firstName.value,
"lastName" : lastName.value,
"imageUser" : imageUser.value
};
php - leave only this
<?php
$data = json_decode(file_get_contents("php://input")); // test only version
print_r($data); // test only version
/*
and close the rest as a comment - SQL is fine, don't worry
$data = json_decode(file_get_contents("php://input",true)); // final ver
echo print_r($data, true); // final ver
...
*/
If you receive the right output, delete the trial version and good luck.
If not - go back to var formSubmitData to the values on the right - they are so naked ... without any quotes
And of course, take care of security (injection) and order, set the required at the inputs - you don't need empty submits
Good afternoon. I am trying to pass the values associated with a list of checkboxes to a javascript function that then calculates the total for all values associated with selected checkboxes.
The HTML code is embedded within PHP. When I try to call the javascript function, I get a null result. Could anyone provide some pointers on where I am going wrong. Code below. All help is appreciated! Thank you.
The variables are pulled from the results of an SQL query executed just before the copied code below.
"<form action = 'book.php' method = 'POST'>
<tr><td>$seat</td>"
."<td>$zone</td>"
."<td>$price</td>"
."<td><input type = 'checkbox' id = 'seat['$seat']' value = '$price'></td></tr>"
//."<input type = 'hidden' id = '$seat' value = '$price' action = 'checkDetails()'>"
;
}
echo "</table>"
."Email address for booking ".
"<input type = 'text' name = 'email id'>"
." "
."<button type = 'submit' name = 'book' action = 'book.php'>Book</button></form>"
." "."<button name = 'check price' onclick = 'checkDetails()'>Check Prices</button>";
}
catch (PDOException $e) {
echo "PDOException: ".$e->getMessage();
}
echo "<script language = 'javascript'>
function checkDetails() {
var seat = document.forms[0];
var i;
for (i = 0; i < seat.length; i++) {
if (seat[i].checked) {
var total = document.getElementById('seat[i]');
alert('Your total is ' + total);
}
}
}
</script>";
You are looping through the forms length.
Since this is rendered in php why dont you set the length of of I programmatically
var i;
var length = <?= $seat?>;
for (i = 0; i < length; i++) {
if ( document.getElementById('seat[i]').checked) {
var total = document.getElementById('seat[i]');
alert('Your total is ' + total.value);
}
the following code is looping through the form and not the elements
var seat = document.forms[0];
var i;
for (i = 0; i < seat.length; i++) {
I have added custom javascript code to the header.php file of my wordpress site. I have tested this code on a basic html file and it works fine, but I cannot seem to make the vote recording function work on a wordpress post. The other components of the script are working fine (hover, vote display from a .txt file), but I cannot get the function to record the vote working. All files have read/write access.
I would greatly appreciate it if anyone could assist me or point me in the right direction to solve this.
Here is the part of the script that records the vote, I am fairly new to php and was wondering if there is something I can add/replace to modify so the code so it will work properly on Wordpress.
$('.ratings_stars').bind('click', function() {
var star = this;
var widget = $(this).parent();
var clicked_data = {
clicked_on : $(star).attr('class'),
widget_id : $(star).parent().attr('id')
};
$.post(
'http://localhost/url/wordpress/wp-content/ratings.php',
clicked_data,
function(INFO) {
widget.data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});
});
function set_votes(widget) {
var avg = $(widget).data('fsr').whole_avg;
var votes = $(widget).data('fsr').number_votes;
var exact = $(widget).data('fsr').dec_avg;
window.console && console.log('and now in set_votes, it thinks the fsr is ' + $(widget).data('fsr').number_votes);
$(widget).find('.star_' + avg).prevAll().andSelf().addClass('ratings_vote');
$(widget).find('.star_' + avg).nextAll().removeClass('ratings_vote');
$(widget).find('.total_votes').text( votes + ' votes recorded (' + exact + ' rating)' );
}
Here is a visual example for reference
Thank you for taking time to look at this, if there is any additional information that I can provide please let me know.
Here is the ratings.php that was mentioned in the script that was placed in the header.php.
ratings.php:
<?php
$rating = new ratings($_POST['widget_id']);
isset($_POST['fetch']) ? $rating->get_ratings() : $rating->vote();
class ratings {
var $data_file = 'http://localhost/url/wordpress/wp-content/ratings.data.txt';
private $widget_id;
private $data = array();
function __construct($wid) {
$this->widget_id = $wid;
$all = file_get_contents($this->data_file);
if($all) {
$this->data = unserialize($all);
}
}
public function get_ratings() {
if($this->data[$this->widget_id]) {
echo json_encode($this->data[$this->widget_id]);
}
else {
$data['widget_id'] = $this->widget_id;
$data['number_votes'] = 0;
$data['total_points'] = 0;
$data['dec_avg'] = 0;
$data['whole_avg'] = 0;
echo json_encode($data);
}
}
public function vote() {
preg_match('/star_([1-5]{1})/', $_POST['clicked_on'], $match);
$vote = $match[1];
$ID = $this->widget_id;
if($this->data[$ID]) {
$this->data[$ID]['number_votes'] += 1;
$this->data[$ID]['total_points'] += $vote;
}
else {
$this->data[$ID]['number_votes'] = 1;
$this->data[$ID]['total_points'] = $vote;
}
$this->data[$ID]['dec_avg'] = round( $this->data[$ID]['total_points'] / $this->data[$ID]['number_votes'], 1 );
$this->data[$ID]['whole_avg'] = round( $this->data[$ID]['dec_avg'] );
file_put_contents($this->data_file, serialize($this->data));
$this->get_ratings();
}
}
?>
Here is the complete javascript code added to the header.php, the mouseover/mouseout seem to be working properly, so I think the javascript should be running.
Javascript added to header.php:
<?php wp_head(); ?>
<script type="text/javascript">
$(document).ready(function() {
$('.rate_widget').each(function(i) {
var widget = this;
var out_data = {
widget_id : $(widget).attr('id'),
fetch: 1
};
$.post(
'http://localhost/url/wordpress/wp-content/ratings.php',
out_data,
function(INFO) {
$(widget).data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});
$('.ratings_stars').hover(
function() {
$(this).prevAll().andSelf().addClass('ratings_over');
$(this).nextAll().removeClass('ratings_vote');
},
function() {
$(this).prevAll().andSelf().removeClass('ratings_over');
set_votes($(this).parent());
}
);
$('.ratings_stars').bind('click', function() {
var star = this;
var widget = $(this).parent();
var clicked_data = {
clicked_on : $(star).attr('class'),
widget_id : $(star).parent().attr('id')
};
$.post(
'http://localhost/url/wordpress/wp-content/ratings.php',
clicked_data,
function(INFO) {
widget.data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});
});
function set_votes(widget) {
var avg = $(widget).data('fsr').whole_avg;
var votes = $(widget).data('fsr').number_votes;
var exact = $(widget).data('fsr').dec_avg;
window.console && console.log('and now in set_votes, it thinks the fsr is ' + $(widget).data('fsr').number_votes);
$(widget).find('.star_' + avg).prevAll().andSelf().addClass('ratings_vote');
$(widget).find('.star_' + avg).nextAll().removeClass('ratings_vote');
$(widget).find('.total_votes').text( votes + ' votes recorded (' + exact + ' rating)' );
}
</script>
To solve this all I had to do was place my ratings.php file and ratings.data.txt within my wordpress theme folder and link the custom javascript to these files within my header.php file. The javascript now operates properly. This is not the proper way to do this though, ideally I should use the wp_enqueue_scripts hook in the header.php and have the custom css and js in the css/js folders. But for now this temporary fix works and I can continue experimenting.
So I am trying to make a simple autocomplete form but keep getting a error when I try to test the program.
When I try to test the program my console spits out [11:25:26.267] SyntaxError: JSON.parse: unexpected character # /search.php:22 which is this line. I am pretty sure my syntax is fine but I could be mistaken. Any and all help would be most gratefully appreciated. Thank you to anyone who takes the time to read and/or answer even if you cannot help!
for (var i = 0; i < response.length; i++)
My Full code is as follows.
Edit: Now with page that echos the json. When I do console.log(req.responsetext) i get [11:38:04.967] ReferenceError: req is not defined. But i define req as a new xml request on window load so I am kind of stumped.
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Auto Complete</title>
</head>
<body>
<script>
window.onload = function () {
var req = new XMLHttpRequest(); //the HTTP request which will invoke the query
var input = document.getElementById('search'); //where to grab the search from
var output = document.getElementById('results'); //where to display the sugestions
input.oninput = getSuggestions;
function getSuggestions() {
req.onreadystatechange = function () {
output.innerHTML = ""; //CLEAR the previous results!! only once the server can process new ones though
if (this.readyState == 4 && input.value != "") {
var response = JSON.parse('(' + req.responseText + ')');
for (var i = 0; i < response.length; i++)
addSuggestion(response[i].terms);
}
}
req.open('GET', 'getterms.php?query=' + input.value, true); //GET request to getterms.php?=
req.send(null);
}
addSuggestion = function (suggestion) {
var div = document.createElement('div');
var p = document.createElement('p');
div.classList.add('suggestion'); //suggestion[x]...
p.textContent = suggestion;
div.appendChild(p);
output.appendChild(div);
div.onclick = function() {
input.value = p.innerHTML; //set the search box
getSuggestions(); //GET new suggesions
}
}
}
</script>
<input type='text' id='search' name='search' autofocus='autofocus'>
<div id='results'></div>
</body>
</html>
edit this is my php page that echos the json.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
if (!isset($_GET['query']) || empty($_GET['query']))
header('HTTP/1.0 400 Bad Request', true, 400);
else {
$db = new PDO(
my database
);
$search_query = $db->prepare("
SELECT * FROM `words` WHERE `word` LIKE :keywords LIMIT 5
");
$params = array(
':keywords' => $_GET['query'] . '%',
);
$search_query->execute($params);
$results = $search_query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
}
?>
Get rid of the ( and ) in the JSON.parse!
JSON.parse('(' + req.responseText + ')')
should be
JSON.parse( req.responseText );
hopefully the responseText is valid JSON