How to check empty in my input text form with calculate? - javascript

I have 2 Input Text in my form how to fix calculate
<?php
$txtA="";
$txtB="";
$textA=0;
$textB=0;
$Total=0;
$txtA = $_POST["TextA"];
$txtB = $_POST["TextB"];
if(empty($txtA)){
$textB=$txtB*0.4;
$Total=$textB;
if(empty($txtB)){
$textA=$txtA*0.4;
$Total=$textA;
if(!empty($txtA) AND !empty($txtB)){
$textA=$txtA*0.65;
$textB=$txtB*0.35;
$Total=$textA + $textB;
Always no data for this code i beginner in php and still learning

You need to know if the value is setted, so we use isset($_POST['yourVariable'])
And you don't need to declare variables when your are defining them with $_POST value, with this said your code ends like this:
<?PHP
$Total=0;
$txtA = $_POST["TextA"];
$txtB = $_POST["TextB"];
if(isset($txtB) && !isset($txtA)){
$textB=$txtB*0.4;
$Total=$textB;
}elseif(isset($txtA) && !isset($txtB)){
$textA=$txtA*0.4;
$Total=$textA;
}
//&& == AND
if(isset($txtA) && isset($txtB)){
$textA=$txtA*0.65;
$textB=$txtB*0.35;
$Total=$textA + $textB;
}
?>

Related

Get a variable from a concatenated variable PHP and JavaScript

I'm not sure how to title this post properly... But I hope you can still help!
<?php
$result = rand(1, 898);
include_once($_SERVER['DOCUMENT_ROOT'].'/016-name.inc.php');
$con = "number".$result;
?>
<h2>Guess That Pokemon!</h2>
<p>Guess the following Pokemon by it's image only.</p>
<input type="text" placeholder="Guess" style="width:75%;" onkeyup="guess()" id="inputGuess"/>
<img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/home/<?=$result?>.png" />
<script>
function guess(){
var inputGuess = document.getElementById('inputGuess');
if (inputGuess.value == '<?=$con?>'){
alert('Correct');
}
}
</script>
Inside /016-name.inc.php (shortened for the sake of simplicity, but you can see where I'm going...)
<?php
$number1 = "bulbasaur";
$number2 = "ivysaur";
$number3 = "venusaur";
$number4 = "charmander";
$number5 = "charmeleon";
$number6 = "charizard";
$number7 = "squirtle";
$number8 = "wartortle";
$number9 = "blastoise";
$number10 = "caterpie";
What I'm trying to do is get the inputted result in JavaScript, and then try to match the word they enter for the number in the variable.
for example, if the input is Squirtle then I need to try and find the variable of the pokemon number and convert it to the pokemon name to check if it's correct.
This is what it's returning:
Expected behaviour:
I've had quite a bad history with posts on stack overflow not being specific enough, etc, but I hope this is enough to try and fix my problem.
Thanks,
Kaden
I think you should use the so called variable/dynamic variable :
https://www.php.net/manual/en/language.variables.variable.php
using the double dollar sign $$
function guess(){
var inputGuess = document.getElementById('inputGuess');
if (inputGuess.value == '<?=$$con?>'){
alert('Correct');
}
}
Let's put it simply :
$result = rand(1, 898); // let say it worths 421 when the code is run
$con = "number".$result; // so it will worth "number421"
$$con will worth $number421
Thanks to Tangentially Perpendicular for providing the solution in this comment:
Don't store your names in separately numbers variables. Use an array. Then finding the element you want is trivial. See php.net/manual/en/language.types.array.php

Image OnClick to Javascript function

I am making a registration page that allows you to register an account to a mysql database for my uni project.
In this page you can also 'select' your avatar picture. Here is the code below:
<u>Select your avatar:</u><br>
<?php
// open this directory
$image_dir = opendir("images/avatars");
// get each entry
while( $image = readdir( $image_dir ) )
{
$dirArray[] = $image;
}
// close directory
closedir($image_dir);
// count elements in array
$indexCount = count($dirArray);
// loop through the array of files and print them all in a list
for($index=0; $index < $indexCount; $index++)
{
$extension = substr($dirArray[$index], -3);
if( $extension == "jpg" || $extension == "gif" )
{
//echo("<a href='#'>");
echo("<img id='$index' onClick='SetAvatar($index)' img src='images/avatars/$dirArray[$index]' class='o'> ");
//echo("</a>");
}
}
?>
<script>
function SetAvatar(id) {
var image = document.getElementById(id);
if( CurSelectedImage != null && id != CurSelectedImage )
{
var image_to_unselect = document.getElementById(CurSelectedImage);
image_to_unselect.Selected = false;
image_to_unselect.style.border = null;
}
if( image.Selected != true )
{
image.style.border = 'medium solid blue';
image.Selected = true;
SelectedImage = id;
}
else
{
image.style.border = null;
image.Selected = false;
SelectedImage = null;
}
}
</script>
This selects the avatar picture, makes the border blue and stores the selected image id in a variable but how would I pass the variable with the selected image id back to php so I can save it??
Thanks
can you show your CSS codes too ?
or you can find here jQuery select and unselect image
your answer
You have to think about your application design. Mixing PHP and Javascript isn't the best idea. Use a API instead of mixing code. You can call this API with Ajax. I think this is a good design choice:
Create a getImages API in PHP: You output the data in a json array.
You calling this api with javascript and generating the DOM with the json
You creating a click handler in javascript and calling again a API in PHP
You getting the json data in PHP and saving it in your db
:)
My suggestion would be to use a CSS class. Remove any existing instances of the class then add the class to the selected image.
function SetAvatar(id) {
//remove existing border(s) a while loop is used since elements is a live node list which causes issues with a traditional for loop
var elements = document.getElementsByClassName("selected-avatar");
while (elements.length > 0) {
var element = elements.item(0);
element.className = element.className.replace(/(?:^|\s)selected-avatar(?!\S)/g , '');
}
var image = document.getElementById(id);
image.className += " selected-avatar";
}
To pass the avatar value, I'd suggest using a form to pass all of your registration data to process_register (if you are not already). You can add an input of type hidden to your form and populate the value through javascript on submit.
html:
<form id="registration-form" action="process_register.php" method="put">
<input id="registration-avatar" type="hidden" />
<button id="registration-submit">Submit</button>
</form>
javascript:
document.getElementById("registration-submit").onclick = function(){
var avatarValue; //you'll need to write some code to populate the avatarValue based on the selected avatar image
document.getElementById("registration-avatar").value = avatarValue;
document.getElementById('registration-form').submit();
};
Then in php you can get the values using $_POST
http://php.net/manual/en/reserved.variables.post.php

Uncaught TypeError: Cannot read property 'style' of null concerning a script in an echo

I'm trying to change the color of a div on an onclick event.
Here is the error I'm getting:
Uncaught TypeError: Cannot read property 'style' of null
Here is the code:
function changeSelection (newClick) {
document.getElementById(newClick).style.backgroundColor="#4bc970";
document.getElementById(newClick).style.color="#FFFFFF";
if(oldClick!="" && document.getElementById(oldClick)!=null && oldClick != newClick){
document.getElementById(oldClick).style.backgroundColor="#d2d2d2";
document.getElementById(oldClick).style.color="#332836";
}
oldClick = newClick;
}
The echo is found on another php page.
echo ("<tr><td><div class='courseDiv' onclick=changeSelection(".$classID.");><p class='textInsideLeftTable'>".$className. "</p><p class='arrow'>></p></div></td></tr>");
Any input will be appreciated.
More Code :
<?php
require("connect.php");
session_start();
$stmt = $db->prepare('SELECT * FROM users INNER JOIN studentparent ON users.parentID = studentparent.parentID INNER JOIN studentsclasses ON studentparent.studentID = studentsclasses.studentID INNER JOIN classes ON classes.classID = studentsclasses.classID WHERE users.parentID=:parentID');
$stmt->execute(array(
':parentID' => $_SESSION['parentID']
)) or die(var_dump($stmt->errorInfo()));
$result = $stmt->fetchAll();
foreach ($result as $row) {
$className = $row['classCode'];
$classID = $row['classID'];
echo ("<tr><td><div class='courseDiv' onclick=\"changeSelection('".$classID."');\"><p class='textInsideLeftTable'>".$className. "</p><p class='arrow'>></p></div></td></tr>");
}
?>
ANSWER :
I inversed the "" with ''. Also, I forgot to give it the div id. I was trying to change the value and not the div value.
I hope it makes sens.
echo ('<tr><td><div id="div_'. $classID .'"onclick="changeSelection(\'div_'.$classID.'\');" class="courseDiv"><p class="textInsideLeftTable">'.$className. '</p><p class="arrow">></p></div></td></tr>');
You need to add single quotes around it, so that JavaScript will treat it as a string instead of a variable.
changeSelection('".$classID."')
document.getElementById(newClick) gives you null means that the id passed as newClick doesn't exists or it is not found in the current context.
add statement console.log(newClick); to your changeSelection() on the first line. And check console(F12 developer tools) to see whats the value being passed.
So My knowledge of PHP is pretty limited but as far as i remember, shouldn't you use
changeSelection('"$classID"')
instead of
changeSelection('".$classID."')
why are there two dots before and after the $classId, if you have stored Id of your div tag, in a variable called classId all you need is $classId to get its value and document.getElementById("classId_value") should return you the element.

How to use explode function to delimit and display different values

I’m making a random sentence generator for my English class. I’m close but because of my limited php and javascript knowledge I need to ask for help. I’m not bad at reading the code, I just get stuck writing it.
I want to use explode to break up a string of comma seperated values. The string is a mix of English and Spanish, on the .txt file they would seperated like:
The book, El libro
The man, El hombre
The woman, La mujer
etc.
I would like to break these two values into an array and display them in separate places on my web page.
I`m going to use a random text generator script that I found, it’s working great with no problems. I just need to modify it using explode to read, separate the values into an array, and be able to display the separate values of the array.
<?php
/* File, where the random text/quotes are stored one per line */
$settings['text_from_file'] = 'quotes.txt';
/*
How to display the text?
0 = raw mode: print the text as it is, when using RanTex as an include
1 = Javascript mode: when using Javascript to display the quote
*/
$settings['display_type'] = 1;
/* Allow on-the-fly settings override? 0 = NO, 1 = YES */
$settings['allow_otf'] = 1;
// Override type?
if ($settings['allow_otf'] && isset($_GET['type']))
{
$type = intval($_GET['type']);
}
else
{
$type = $settings['display_type'];
}
// Get a list of all text options
if ($settings['text_from_file'])
{
$settings['quotes'] = file($settings['text_from_file']);
}
// If we have any text choose a random one, otherwise show 'No text to choose from'
if (count($settings['quotes']))
{
$txt = $settings['quotes'][array_rand($settings['quotes'])];
}
else
{
$txt = 'No text to choose from';
}
// Output the image according to the selected type
if ($type)
{
// New lines will break Javascript, remove any and replace them with <br />
$txt = nl2br(trim($txt));
$txt = str_replace(array("\n","\r"),'',$txt);
// Set the correct MIME type
header("Content-type: text/javascript");
// Print the Javascript code
echo 'document.write(\''.addslashes($txt).'\')';
}
else
{
echo $txt;
}
?>
The script that displays the result:
<script type="text/javascript" src="rantex.php?type=1"></script>
Can someone please help me modify the rantex.php file so that I can use explode to separate the different comma separated values, and use a different script to call them in different places on my web page?
Thank you, and please excuse my noobness.
The following seems unnecessary, since file() will have already removed new line characters:
// New lines will break Javascript, remove any and replace them with <br />
$txt = nl2br(trim($txt));
$txt = str_replace(array("\n","\r"),'',$txt);
To break your line, you may instead use:
list($english, $spanish) = explode(', ', trim($txt));
It seems you are trying to use PHP to serve a static page with some random sentences, right? So why not use PHP to serve valid JSON, and handle to display logic on the client?
Heres a quick implementation.
// Get the data from the text file
$source = file_get_contents('./quotes.txt', true);
// Build an array (break on every line break)
$sentences = explode("\n", $source);
// Filter out empty values (if there is any)
$filtered = array_filter($sentences, function($item) {
return $item !== "";
});
// Build a hashmap of the array
$pairs = array_map(function($item) {
return ['sentence' => $item];
}, $filtered);
// Encode the hashmap to JSON, and return this to the client.
$json = json_encode($pairs);
Now you can let the client handle the rest, with some basic JavaScript.
// Return a random sentence from your list.
var random = sentences[Math.floor(Math.random() * sentences.length)];
// Finally display it
random.sentence
[edit]
You can get the JSON data to client in many ways, but if you don't want to use something like Ajax, you could simply just dump the contents on your webpage, then use JavaScript to update the random sentence, from the global window object.
// Inside your php page
<p>English: <span id="english"></span></p>
<p>Spanish: <span id="spanish"></span></p>
<script>
var sentences = <?= json_encode($pairs); ?>;
var random = sentences[Math.floor(Math.random() * sentences.length)];
var elspa = document.getElementById('spanish');
var eleng = document.getElementById('english');
elspa.innerText = random.sentence.split(',')[1];
eleng.innerText = random.sentence.split(',')[0];
</script>
Ok, so I have this figured out, I take 0 credit because I paid someone to do it. Special thanks to #stormpat for sending me in the right direction, if not for him I wouldn't have looked at this from a JSON point of view.
The .PHP file is like so:
<?php
$f_contents = file('quotes.txt');
$line = trim($f_contents[rand(0, count($f_contents) - 1)]);
$data = explode(',', $line);
$data['eng'] = $data[0];
$data['esp'] = $data[1];
echo json_encode($data);
?>
On the .HTML page in the header:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
(function ($) {
$(function()
{
function load_random_data() {
$.get('random_line.php', function(data) {
var data = $.parseJSON(data);
$('#random_english').text(data.eng);
$('#random_spanish').text(data.esp);
});
}
load_random_data();
$('#get_random').click(function(e){
e.preventDefault();
load_random_data();
});
});
})(jQuery);
</script>
This splits the different variables into classes, so to call them into my html page I call them by their class, for instance I wanted to drop the variable into a table cell so I gave the individual td cell a class:
<td id="random_spanish"></td>
<td id="random_english"></td>
Plus as a bonus the coder threw in a nifty button to refresh the json classes:
<input type="button" value="Get random" id="get_random" />
So now I don`t have to have my students refresh the whole web page, they can just hit the button and refresh the random variables.
Thanks again everyone!

populate dropdown onload by passing php array to javascript function

im trying to pass a php array to javascript function onload that will display the js array in a drop down list but now im already doing it for sometime i guess i need to pop it again
first i pass it from one php file to another using this code
header("location: Rules.php?varFields=".serialize($varFields));
secondly i transfer to another variable as it had been passed to the said php file
<?php
$varArray = unserialize($_GET['varFields']);
?>
third part is im tyring to pass it into a jS functon that will then display it to a drop down list
<body id="body" onclick="cmbRuleField(\'' + <?php echo json_encode($varArray);?> + '\');" >
and here is the external javascript code
function cmbRuleField(varArray)//ruleField
{
var varDisplay = JSON.stringify(varArray);
var sel = document.getElementById("ruleField") // find the drop down
for (var i in varDisplay)
{ // loop through all elements
var opt = document.createElement("option"); // Create the new element
opt.value = varDisplay [i]; // set the value
opt.text = varDisplay [i]; // set the text
sel.appendChild(opt); // add it to the select
}
}
for the first two part i already tested it and it is working but for the last parts i cant make it work
I think this part looks suspicious
<body id="body" onclick="cmbRuleField(\'' + <?php echo json_encode($varArray);?> + '\');" >
maybe
<body id="body" onclick="cmbRuleField(<?php echo json_encode($varArray);?>)">
is more like it.
One more tip, you can see the output on the rendered page to determine what the written out code looks like. So if you see something like:
<body id="body" onclick="cmbRuleField('['a', 'b']')">
you know there is a problem. You want a native Javascript array to be passed like this
<body id="body" onclick="cmbRuleField(['a', 'b'])">
EDIT
After talking on chat it became clear the top portion of OP's code needed a tweak as well.
header("location: Rules.php?varFields=".http_build_query($varFields));
The problem has to do with quotes not being terminated here:
...
<body id="body" onclick="cmbRuleField(\'' + <?php echo json_encode($varArray);?> + '\');" >
...
The JSON created using json_encode will have a lot of double quotes. Try this:
<script>
var array = <?php echo json_encode($varArray);?>;
</script>
<body id="body" onclick="cmbRuleField(array);">
There is a much easier way. Encode the $varArray as direct HTML options before sending to the browser. For instance:
<select id="ruleField">
<?php for ($i = 0; $i < count($varArray); $i++) { ?>
<option value="<?php= $varArray[$i].val ?>"><?php= $varArray[$i].name ?></option>
<?php } ?>
</select>
Might be because you are calling JSON.stringify on something that is already a string?
Also what is myCars?
..
for (var i in myCars)
..
Possibly rename it to varArray.
or rename varDisplay to varArray.
and lastly try calling JSON.parse instead:
function cmbRuleField(varArray)//ruleField
{
var varDisplay = JSON.parse(varArray);
var sel = document.getElementById("ruleField") // find the drop down
for (var i in myCars)
{ // loop through all elements
var opt = document.createElement("option"); // Create the new element
opt.value = varDisplay [i]; // set the value
opt.text = varDisplay [i]; // set the text
sel.appendChild(opt); // add it to the select
}
}
If that didn't work post the html output here so peeps can create a fiddle :)

Categories