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!
Related
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
Last time I asked for help in PHP and I got great response. Thanks to all of you for that. Now I am learning and creating website using MVC PHP. I want to ask you that can I create a custom function to use html tags? I am trying to remember that where I saw an example of it. Actually I've seen it before in and open source project.
It was like something this:
htmltag(script(src=address, type=javascript))
Its output was in html like:
<script src="address" type="javascript"></script>
So can I create something like this? I am trying to do this way:
public function script($var1, $var2){
$var1 = array(
'type'=>'',
'charset' => '',
'src' => ''
);
$var2 = false;
print("<script $var1>$var2</script>");
}
So can anyone guide me with this? Do I need to create class first? I will be waiting for your reply friends.
Javascript works with DOM, see the reference
function htmltag(name,atts) {
var tag = document.createElement(name);
for(var i in atts) tag.setAttribute(i, atts[i]);
return tag;
}
var img = htmltag("img", {
src: "https://kevcom.com/images/linux/linux.logo.2gp.jpg",
alt: "linux logo"
});
document.body.appendChild(img);
Note that img here is object (XML Node), not just plain text, so you can attach events on it etc. If you want to extract just the plain html code from it, use img.outerHTML. Test it on the fiddle.
Note: print is the equivalent of Ctrl+P in the browser :-) it is not the print equivalent in PHP.
In PHP you can use DOM::createElement and other methods from DOM which are quite similar to those from javascript. Personaly I prefer something more simple:
function tag($name,$atts="",$content="") {
$str_atts = "";
if(is_array($atts)) {
foreach($atts as $key=>$val) if(!($val===null || $val===false)) $str_atts.= " $key=\"$val\"";
} else $str_atts = " ".preg_replace("/=(?!\")(\S+)/m","=\"\\1\"",$atts);
if($name=="img" && !strpos($str_atts,"alt=")) $str_atts.= " alt=\"\"";
if(in_array($name,array("input","img","col","br","hr","meta"))) $name.= "/";
if(substr($name,-1)=="/") { $name = substr($name,0,-1); return "<{$name}{$str_atts}/>"; }
else return "<{$name}{$str_atts}>$content</$name>";
}
Examples
echo tag("p","class=foo id=bar1","hello");
echo tag("p",'class="foo" id="bar2"',"hey");
echo tag("p",array("class"=>"foo","id"=>"bar3"),"heya");
echo tag("img","src=https://kevcom.com/images/linux/linux.logo.2gp.jpg");
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.
I have a list of airport codes, names, and locations in an Excel Spreadsheet like the below:
+-------+----------------------------------------+-------------------+
| Code | Airport Name | Location |
+-------+----------------------------------------+-------------------+
| AUA | Queen Beatrix International Airport | Oranjestad, Aruba|
+-------+----------------------------------------+-------------------+
My Javascript is passed a 3 character string that should be an airline code. When that happens I need to find the code on the spreadsheet and return the Airport Name and Location.
Im thinking something like:
var code = "AUA";
console.log(getAirportInfo(code));
function getAirportInfo(code) {
// get information from spreadsheet
//format info (no help needed there)
return airportInfo;
}
Where the log would write out:
Oranjestad, Aruba (AUA): Queen Beatrix International Airport
What is the easiest method to get the data I need from the spreadsheet?
Extra Info:
The spreadsheet has over 17,000 entries
The function alluded to above may be called up to 8 times in row
I don't have to use an Excel Spreadsheet thats just what I have now
I will never need to edit the spreadsheet with my code
I did search around the web but everything I could find was much more complicated than what Im trying to do so it made it hard to understand what Im looking for.
Thank you for any help pointing me in the right direction.
I ended up using a tool at shancarter.com/data_converter to convert my flie to a JSON file and linked that to my page. Now I just loop through that JSON object to get what I need. This seemed like the simplest way for my particular needs.
I've used a plain text file(csv, or tsv both of which can be exported directly from Excel)
Loaded that into a string var via xmlhttprequest. Usually the browsers cache will stop having to download the file on each page load.
Then have a Regex parse out the values as needed.
All without using any third party....I can dig the code out if you wish.
Example:
you will need to have the data.txt file in the same web folder as this page, or update the paths...
<html>
<head>
<script>
var fileName = "data.txt";
var data = "";
req = new XMLHttpRequest();
req.open("GET", fileName, false);
req.addEventListener("readystatechange", function (e) {
data = req.responseText ;
});
req.send();
function getInfoByCode(c){
if( data == "" ){
return 'DataNotReady' ;
} else {
var rx = new RegExp( "^(" + c + ")\\s+\\|\\s+(.+)\\s+\\|\\s+\\s+(.+)\\|", 'm' ) ;
var values = data.match(rx,'m');
return { airport:values[2] , city:values[3] };
}
}
function clickButton(){
var e = document.getElementById("code");
var ret = getInfoByCode(e.value);
var res = document.getElementById("res");
res.innerText = "Airport:" + ret.airport + " in " + ret.city;
}
</script>
</head>
<body>
<input id="code" value="AUA">
<button onclick="clickButton();">Find</button>
<div id="res">
</div>
</body>
</html>