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
Related
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!
I am trying to build a quiz environment. The user selects an answer and then clicks submit. Upon submit, the following jquery is called:
$(document).ready(function() {
$('.btn-large').click(function() {
$.post("correct_quiz.php",
{
choices : $('input[name=choice][type=radio]:checked').serialize()
},
function(data) {
var temp = '#correct' + data;
var temp2 = '#correct3';
$(temp).show(); // Make the wrong/right icons visible
});
});
});
This jquery makes a green or red icon appear, based on whether the answer was correct or not. The correct_quiz.php script contains:
<?php
$root = "/users/stadius/maapc/public_html/";
include($root . "connect_to_database.php");
$choices = $_POST['choices']; // This will for example output "choice=3"
echo substr($choices,7,7); // This will then output "3"
?>
I ran into a problem, when I try the above jquery code with variable temp2 the script works like I want. But when I try it with variable temp it doesn't. When I debug, I see that they contain exactly the same string though: both are '#correct3' (when I choose the 3rd answer).
So why is this not working when I use variable temp, and is working when using temp2?
I think your problem is in this line:
echo substr($choices,7,7);
Try to use:
$list = explode('=', $choices);
echo $list[1];
instead of substr
I'm trying to create a simple image slider on the front page of my drupal website. I wrote a module with the basic outline as follows
<?php
function slider_init(){
drupal_add_js(drupal_get_path('module', 'slider') .'/slider.js');
}
function slider_block($op = 'list', $delta = 0, $edit = array()) {
$block = array();
switch ($op) {
case "list":
// Generate listing of blocks from this module, for the admin/block page
$block[0]["info"] = t("slider");
break;
case "view":
// Generate content for blocks from this module
$block_content = "";
$block_content .= "hello";
//Query for the projects
$icons = db_query("SELECT * FROM {alumni_frontpage_projects}");
//Initiation arrays from each table column: title, description, url, icon link
$links = array();
$title = array();
$description = array();
$url = array();
//Generate arrays from each table column: title, description, url, icon link
while($icon_data = db_fetch_array($icons)){
$links[] = $icon_data['slider_image_location'];
$title[] = $icon_data['title'];
$description[]= $icon_data['description'];
$url[] = $icon_data['url'];
}
//Count elements in array and randomly choose one
$res = count($links)-1;
$seed = rand(0,$res);
//Generate HTML and Javascript of Slider
//Check that content isn't empty
if ($block_content == "") {
$block_content = t("Sorry No Content");
}
$block["content"] = $block_content;
break;
case "save":
break;
case "configure":
break;
}
return $block;
}
Now, everything is fine. I generate a block and I can place it wherever I want. Great. But I would really like to use javascript in this block so that I can pass the arrays and use onclick events to slide through some images from the arrays i queried. So I found out that I will have to pass the variables into javascript and I'll have to identify the javascript file i want to use in the module.
//add variable to the Javascript
drupal_add_js(array('slider_settings' => array('variable_name' => $variable_name)), 'setting');
//add Javascript file to module
drupal_add_js(drupal_get_path('module', 'slider') .'/slider.js');<br>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I put these in the hook_init BUT NOTHING HAPPENS!!!!! I tested to see basic alerts. If I put hard code into the _block, such as:
$block_content .= '
<script type="text/javascript">
var x
x = 50;
document.write(x); //prints the value of x
</script>';
Then I see '50' prints.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If I try to pass a variable to the hard coded script. That DOES NOT WORK either.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If I try to write 50 through the previous code, but from a separate file called slider.js which is in the same folder using "drupal_add_js(drupal_get_path('module', 'slider') .'/slider.js');", That DOES NOT WORK either (even though I'm not passing a variable)
So what the heck is going on!! Is it possible I'm missing some important core drupal files? Is there a way to trouble shoot this further?
Thanks!
drupal_add_js should work in hook_init().First Check whether your hook function is correctly named as ModuleName_init() or not.
First off, thanks for anyone's help on this. I have an input id #Mailer_Code. I want to submit a specific value based on whether this mailer code value matches the user's value or not, and create 2 different IDs based on whether this value is valid or not.
In general terms:
ID is 1234;
if Mailer_Code is yourock, then ContactID is DWID
if Mailer_Code is not yourock, then ContactID is WWID
I would really appreciate if "yourock" was some sort of comma separated list so the Mailer_Code could be any of the specified values. ie. #Mailer_Code = "yourock, or yourawesome, or supercool, etc." (not case sensitive)
Also, if the #Mailer_Code is anything other than the list of allowed values, it simply returns a #Mailer_Code of "none" and WW1234.
So far I'm here:
if ( $('#Mailer_Code').val = "yourock" ) {
contactSource = "DW";
mailer_true_false = "true";
}
else {
contactSource = "WW";
mailer_true_false = "false";
$("#Mailer_Code").val('0');
}
Any help is much appreciated. Thanks for reading.
The following should get you started.
Note that instead of a comma separated list of valid values I added them to an array. jQuery has a very useful array function inArray that makes checking the values a simple matter.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div>
<span id="Mailer_Code">yourock</span>
<span id="Id">1234</span>
</div>
<span id="ContactId"></span>
<script type="text/javascript">
var arr = [ "yourock", "youareawesome", "youarethebest" ];
var inListPrefix = "DW";
var outListPrefix = "WW";
var mailerCode = $("#Mailer_Code").text();
var pre = "";
if (jQuery.inArray(mailerCode, arr) >= 0)
{
pre = inListPrefix;
}
else
{
pre = outListPrefix;
$("#Mailer_Code").text("none");
}
$("#ContactId").text(pre + $("#Id").text());
</script>
</body>
</html>
I have a variable account_number in which account number is stored. now i want to get the value of the element having id as account_number. How to do it in javascript ?
I tried doing document.getElementById(account_number).value, but it is null.
html looks like this :
<input class='transparent' disabled type='text' name='113114234567_name' id='113114234567_name' value = 'Neeloy' style='border:0px;height:25px;font-size:16px;line-height:25px;' />
and the js is :
function getElement()
{
var acc_list = document.forms.editBeneficiary.elements.bene_account_number_edit;
for(var i=0;i<acc_list.length;i++)
{
if(acc_list[i].checked == true)
{
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
alert(document.getElementById("'" + ben_name.toString() + "'").value);
}
}
}
here bene_account_number_edit are the radio buttons.
Thanks
Are you storing just an integer as the element's id attribute? If so, browsers tend to behave in strange ways when looking for an element by an integer id. Try passing account_number.toString(), instead.
If that doesn't work, prepend something like "account_" to the beginning of your elements' id attributes and then call document.getElementById('account_' + account_number).value.
Why are you prefixing and post-fixing ' characters to the name string? ben_name is already a string because you've appended '_name' to the value.
I'd recommend doing a console.log of ben_name just to be sure you're getting the value you expect.
the way to use a variable for document.getElementById is the same as for any other function:
document.getElementById(ben_name);
I don't know why you think it would act any differently.
There is no use of converting ben_name to string because it is already the string.
Concatenation of two string will always give you string.
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
try following code it will work fine
var ben_name=acc_list[i]+ "_name";
here also
alert(document.getElementById("'" + ben_name.toString() + "'").value);
try
alert(document.getElementById(ben_name).value);
I have tested similar type of code which worked correctly. If you are passing variable don't use quotes. What you are doing is passing ben_name.toString() as the value, it will definitely cause an error because it can not find any element with that id viz.(ben_name.toString()). In each function call, you are passing same value i.e. ben_name.toString() which is of course wrong.
I found this page in search for a fix for my issue...
Let's say you have a list of products:
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_1">149.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_2">139.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_3">49.95</p>
add to cart
</div>
The designer made all the prices have the digits after the . be superscript. So your choice is to either have the cms spit out the price in 2 parts from the backend and put it back together with <sup> tags around it, or just leave it alone and change it via the DOM. That's what I opted for and here's what I came up with:
window.onload = function() {
var pricelist = document.getElementsByClassName("rel-prod-price");
var price_id = "";
for (var b = 1; b <= pricelist.length; b++) {
var price_id = "price_format_" + b;
var price_original = document.getElementById(price_id).innerHTML;
var price_parts = price_original.split(".");
var formatted_price = price_parts[0] + ".<b>" + price_parts[1] + "</b>";
document.getElementById(price_id).innerHTML = formatted_price;
}
}
And here's the CSS I used:
.rel-prod-item p.rel-prod-price b {
font-size: 50%;
position: relative;
top: -4px;
}
I hope this helps someone keep all their hair :-)
Here's a screenshot of the finished product