echo variable to document via button click - javascript

First time here so apologies if I'm doing something wrong.
I have the following php code:
<?php
$quoteFile = "quotes.txt"; //File holding qoutes
$fp = fopen($quoteFile, "r"); //Opens file for read
$content = fread($fp, filesize($quoteFile));
$quotes = explode("\n",$content); //Put quotes into array
fclose($fp); //Close the file
srand((double)microtime()*1000000); // randomize
$index = (rand(1, sizeof($quotes)) - 1); //Pick random qoute
?>
The code fetches a random quote from a text file by randomly choosing one of the lines of the .txt file.
I then echo out the result using:
echo $quotes[$index];
However what I want to achieve and don't seem to be able to is to have a button (html) that when clicked executes the echo $quotes[$index]; to the current page. So that each time the button is clicked it prints/echo's out a random quote from the .text file.
I did mess about with just setting a button up to refresh the page which by default made a new random quote display but it sometimes just reloaded a blank so I'm hoping someone can help me achieve this better or prompt me in the right direction. Thank tou.

You can try saving that variable into a session variable like this:
$_SESSION['quote'] = $quote['index'];
Then create an anchor element that redirects to current page:
Refresh
And print the result on the page:
<span><?php echo $_SESSION['quote']; ?></span>
To do all of this, you need to set a session. At top of your php file write:
session_start();
Hope that helps. :)

Your TXT file might have an empty line in it at the end or anywhere else. A second explanation of this, is that the way you are generating randomness is quite questionable.
Check out this simple example by W3 Schools.
$a=array("red","green","blue","yellow","brown");
$random_keys=array_rand($a,1);
echo $a[$random_keys[0]]."<br>";
The array_rand() function returns a random key from an array, or it returns an array of random keys if you specify that the function should return more than one key.
Or, simply:
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
print_r(array_rand($a,1));
?>
Full Post: http://www.w3schools.com/php/func_array_rand.asp
Happy coding !

Related

php Load an Image from url with json and display

I want to get images from URL I am very very new to JavaScript. I appreciate your patience with me.
I'm trying to create a script that allows a user to input a name into a text-area, press submit and an image is displayedon web page based on imei no.enter image description here
{"status":1,"image_list":["011975002649_201020131619.jpeg","011975002649_201020134737.jpeg","011975002649_201027135940.jpeg"]}
Assuming the files are uploaded on your server, and you want to print images with PHP you can do :
$images = array("image1.jpg", "image2.jpg");
foreach ($images as $image) {
echo "<img src='/path/to/images/$image' />";
}
Edit after discussion:
You must perform an XHR to getinfo.php. See: https://developer.mozilla.org/fr/docs/Web/API/XMLHttpRequest
On server's answer then test for success or fail
if success parse JSON, and loop through the table to create an img element each time you want to display an image. See https://developer.mozilla.org/fr/docs/Web/API/Document/createElement
otherwise, handle error
Please try this code, To PHP Load an Image from URL and display
<?php
$image = 'http://www.google.com/doodle4google/images/d4g_logo_global.jpg';
$imageData = base64_encode(file_get_contents($image));
echo '<img src="data:image/jpeg;base64,'.$imageData.'">';
?>
I hope this code will be useful to you.
Thank you.

SimpleHtmlDom take elements from pagination built with javascript

So i already have used SimpleHtmlDom with success. The difference is that i iterated through the pagination based on the url.
For example the domain would be:
www.example.com/articles
and the pagination would be
www.example.com/articles/page/1.html
Now i have a pagination that is based on javascript and i get only the results from the first page. Now, when i tell the page to get to the next page, i assume that it reloads the page, so it goes from the start again because the url does not change.
One extra problem is that the link that belongs to the "next page", if you copy it and paste it on the URL bar then it redirects you to another section of the website. (So much for developers -_- )
I will actually paste the original code so you can see by yourself what is going on with the links.
Anyways my question is the following:
How can i iterate through the whole pagination?
<?php
require "simple_html_dom.php";
$url = "http://es.4story.gameforge.com/ranking/browse?type=world";
$baseUrl = "http://es.4story.gameforge.com/ranking/browse?type=world";
//Create a DOM object
$html = new simple_html_dom();
// Load HTML from a URL
$html->load_file($url);
// Get all links
foreach ($html->find('.enc_controls .enc_pager a.enc_next') as $anchor) {
$tempUrl = $baseUrl . $anchor->href;
$linkHtml = file_get_html($tempUrl);
foreach ($linkHtml->find('#results td .item_classWrap a span') as $item ) {
echo $item;
echo "<hr/>";
}
}

PHP altering HTML on first connection

Currently I have a php-page using include to show an html-page.
What I want to do is use a variable the php-page received when being called and project data into a field of the html-page depending on this variable. The problem is that I can't seem to pass the variable from php to html without using html to call php.
I know that I can simply echo the php-part, but because I can't echo straight into one of the html-page's divs it ends up putting the echo at the beginning or end of the page.
What I want to accomplish is for the html-page to load the php-part into one of the div's the first time the php includes the html-page. Is there any way to do such a thing?
If this isn't possible, then how do I get the javascript in the html-page to use the variable from the php-file? Is the best option really the href?
As requested some of the code:
php:
if (filter_input(INPUT_GET, "event", FILTER_SANITIZE_STRING))
{
include "../Html/EventPage.html"; //target page
$temp = filter_input(INPUT_GET, "event", FILTER_SANITIZE_STRING); //get the variable
include "../PHP/Connector.php"; //include the connection page
$value = callFunction(Connect(), $temp); //call connection page and return value
echo "<div class = 'cant select div in html'>" . $value . "</div>"; //echo value in location
}
html:
<div id = "dynamic">
this should have the php
</div>
I assume you use some code like this to display the page:
include('page.html');
A safer way would be to prevent evaluation in page.html:
echo file_get_contents('page.html', true);
You can then do any string modification you want for the content:
$replacement = 'MY REPLACEMENT';
echo str_replace('<div id="my-div">', '<div id="my-div">' . $replacement, file_get_contents('page.html', true));

String value accumulating empty spaces in MySQL database

I have a webpage where admin users can edit the text on the page. But when they insert the text into the mysql database, it sometimes adds more and more white spaces before the acual content.
If you place your cursur before the first word on the page and spam backspace for a while, the whitespace in the database dissappears. But over time, the more you keep editing the page, more and more whitespaces are added again.
I did a lot of trouble shooting, but I just can't figure out what causes the whitespaces to be added. It does not always happen making it really difficult to troubleshoot.
Here's my code:
As my code is pretty long, I tried to translate most of the content to english.
If you want to translate something that in't already translated, the original language is Dutch.
over_ons.php - Shows edit button and page content from the database.
//Active page:
$pagina = 'over_ons'; ?>
<input type='hidden' id='pagina' value='<?php echo $pagina; ?>'> <!--Show active page to javascript--><?php
//Active user:
if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin'){
$editor = $_SESSION['gebruikersnaam']; ?>
<input type='hidden' id='editor' value='<?php echo $editor; ?>'> <!--Show active user to javascript--><?php
} ?>
<!--Editable DIV: -->
<div class='big_wrapper'><?php
//Get eddited page content from the database
$query=mysql_query("SELECT inhoud FROM paginas WHERE naam_pagina='" .$pagina. "'");
while($inhoud_test=mysql_fetch_array($query)){
$inhoud=$inhoud_test[0];
}
//Show Content
?><div id='editedText'><?php echo $inhoud; ?></p></div>
<!--Show edit button-->
<?php
if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin')
{?>
<div id='sidenote'>
<input type='button' value='Bewerken' id='sent_data' class='button' />
<div id="feedback" />
</div>
<?php }
javascript.js - Sents page content to the php file sent_data.php:
//If the system is in edit mode and the user tries to leave the page,
//let the user know it is not so smart to leave yet.
$(window).bind('beforeunload', function(){
var value = $('#sent_data').attr('value'); //change the name of the edit button
if(value == 'Verstuur bewerkingen'){
return 'Are you sure you want to leave the page? All unsaved edits will be lost!';
}
});
//Make content editable and send page content
$('#sent_data').click(function(){
var value = $('#sent_data').attr('value'); //change the name of the edit button
if(value == 'Bewerken'){
$('#sent_data').attr('value', 'Verstuur bewerkingen'); //change the name of the edit button
var $div=$('#editedText'), isEditable=$div.is('.editable'); //Make div editable
$div.prop('contenteditable',!isEditable).toggleClass('editable')
$('#feedback').html('<p class="opvallend">The content from<BR>this page is now<BR>editable.</p>');
}else if(value == 'Verstuur bewerkingen'){
var pagina = $('#pagina').val();
var editor = $('#editor').val();
var div_inhoud = $("#editedText").html();
$.ajax({
type: 'POST',
url: 'sent_data.php',
data: 'tekst=' +div_inhoud+ '&pagina=' +pagina+ '&editor=' +editor,
success: function(data){
Change the div back tot not editable, and change the button's name
$('#sent_data').attr('value', 'Bewerken'); //change the name of the edit button
var $div=$('#editedText'), isEditable=$div.is('.editable'); //Make div not editable
$div.prop('contenteditable',!isEditable).toggleClass('editable')
//Tell the user if the edditing was succesfully
$('#feedback').html(data);
setTimeout(function(){
var value = $('#sent_data').attr('value'); //look up the name of the edit button
if(value == 'Bewerken'){ //Only if the button's name is 'bewerken', take away the help text
$('#feedback').text('');
}
}, 5000);
}
}).fail(function() {
//If there was an error, let the user know
$('#feedback').html('<p class="opvallend">There was an error.<BR>Your changes have<BR>not been saved.<BR>Please try again.</p>');
});
}
});
And finally,
sent_data.php - Get page content from javascript,js and insert into database:
<?php
session_start();
include_once('./main.php');
include($main .'connectie.php');
//Look up which page has to be edited
$pagina=$_POST['pagina'];
//Get the name of the person who eddited the page
$editor=$_POST['editor'];
//Get content:
$tekst=$_POST['tekst'];
$tekst = mysql_real_escape_string($tekst);
$tekst = trim($tekst);
$query="UPDATE paginas SET naam_editer='" .$editor. "', inhoud='" .$tekst. "' WHERE naam_pagina='" .$pagina. "'";
}
if(mysql_query($query)){
echo "<p class='opvallend'>Successfully saves changes.</p>";
}else{
echo "<p class='opvallend'>Saving of changes failed.<BR>
Please try again.</p>";
}
?>
Extra information:
PHP version: 5.5.15
jQuery version: 1.11.1
Testing in browser: Chrome
Database: phpMyAdmin 5.5.39
The content is inserted in a VARCHAR type with space for 10000 caracters
Thanks in advance for you help!
SOLUTION
Thanks to the great help of a lot of people, and especially #avnishkgaur, it is working perfectly now. Here is what I ajusted (also changed it in my code above, so that's working code now).
1. Removed all the white spaces I had in my code between <div id='editable'> and <?php
2. Added $tekst = trim($tekst); to my PHP file to remove white spaces (didn't work)
3. Placed the editable text into another div as the code for getting the data from the database (was in the same div before)
4. Renamed the ID from the editable div to editedText. Also changed the name in the javascript file. This solution made it work perfectly (it was 'editable' before).
This was kind of an unexpected solution, so I think this could help others too.
As to why it is adding extra whitespace, I think it is because you are inserting the text from database into div directly (which contains some white space in html code, which is removed when page is rendered).
One efficient solution would be to insert your content in tag, probably like this:
<div class='big_wrapper'>
<p id='editable'></p>
</div>
Another solution is to trim the text before inserting into db. You can do that either at javascript post stage, or right before inserting in mysql db.
In jQuery, (which you are using) you can implement this :
data: 'tekst=' +$.trim(div_inhoud)+ '&pagina=' +pagina+ '&editor=' +$.trim(editor),
or in sent_data.php, you can use TRIM mysql function in your update query.
First of all, I would strongly suggest to use mysqli or PDO instead of the mysql functions in PHP, as these are deprecated. Please look into this on PHP.net.
As for your problem, I have no tried to reproduce the issue. I suggest you log and check what happens step by step, for example logging the div_inhoud var, are the spaces included at this stage already? And so on.
If you are in a hurry, you could also use the PHP function ltrim on the $tekst var in your sent_data.php, which would trim all spaces on the left side (Or any characters you would want to be trimmed from the string)
Try to add a trim() function in your send_data.php, this will help you to strip white spaces.
$tekst = trim($_POST['tekst']);
My guess is that the newlines after the <div id='editable'> and ?> and the indentation of <?php in over_ons.php is adding the extra whitespace. Specifically, a couple of extra /n's and also spaces from the indentation within the file.
You could trim the whitespace before saving it to your database, or alternatively, before the ajax call, or both.
In php, trim():
sent_data.php
$tekst = trim($tekst);
Or javascript, str.trim():
javascript.js
var div_inhoud = $("#editable").html().trim();
Also, you may want to consider using PHP Data Objects, instead of inserting variables directly into your SQL statements. It's actually really easy to use and in my opinion makes code easier to read and more reusable. There is a fantastic tutorial by Tuts+ that makes it easy to learn and get started. This will ensure you don't accidentally allow SQL injection issues into your application.

JQuery seems to be blocked by something else

JQuery seems to be blocked
Hello there, I've been confronting this problem for several days, I just can't find a way to get this fixed, or around it.
What I want to do is simple, I want to read out every sub-folder of a big Project folder. Then assign a thumbnail image and a figcapture to this folder. With a simple for loop, php builds this for me. Everything works perfect and quick. The only thing is that the jquery won't respond. Even though I have created various menus with this technique. As you can see in my code, in the "script" tags, I have the jquery code which doesn't seem to work.
I don't know wheter php puts in a space somewhere or I just looked too long at this code for seing the error.
I appreciate any help.
<?php
/*Because of the "ease of use" aspect of this site, I prefered to write it completely in PHP,
advantage of that:
Images are loaded directly out of the folder, so I can just drag and drop something onto the server without having to write aditional code.
As you see, it can save a lot of time.*/
echo "<h1>Referenzen</h1><br>";
$projects = scandir('../src/sub/credentials'); //The credentials directory is being scanned and converted into an array.
$projectsSize = count($projects); //$size is being created. It counts the number of objects in the array which has been created above.
$projectsCaptions = file('../src/sub/captionsOfCredentials.txt'); //Edit the name of the figcaption in the "captionsOfCredentials.txt".
for($i = 2; $i < $projectsSize; $i++){ /*Simple "for" loop, that creates $i with the size of two, because PHP is 0-index based and has the "dot" and the "dotdot" folder. The loop stops at the end of the array($size).*/
echo '<a href="index.php#PRJ'.trim($projectsCaptions[$i]).'" class="ID'.trim($projectsCaptions[$i]).'">
<div class="projectFolder">
<img src="src/sub/credentialsThumb/project_00'.$i.'.jpg" width="100%" />
<figcaption>'
.$projectsCaptions[$i].
'</figcaption>
</div>
</a>';
/*Project folder level starts here.*/
$images = scandir('../src/sub/credentials/project_00'.$i);
$imagesSize = count($images);
for($k = 3; $k < $imagesSize; $k++){
$tempID = ('ID'.trim($projectsCaptions[$i]).'.php'); //$tempID is the entire file name including the .php part.
$handle = fopen($tempID, "a") or die ('Unable to open '.$tempID.' , please contact admin A.S.A.P..');
$imagesCode = 'test';
fwrite($handle, $imagesCode);
}
//end second for-loop
echo "
<script>
$(document).ready(function () {
$('#ID".$projectsCaptions[$i]."').click(function () {
$('#mainContent').load('de-DE/".$tempID."');
});
});
</script>";
}
//end first for-loop
?>
You're selecting an element by id when you need to use class. Change the JS block to this:
$(document).ready(function () {
// Note ".ID" not "#ID"
$('.ID".$projectsCaptions[$i]."').click(function () {
$('#mainContent').load('de-DE/".$tempID."');
});
});
UPDATE
It seems like you've also got an illegal character in $projectsCaptions[$i]. It's most likely a newline character. Try wrapping the above reference above in trim():
$('.ID" . trim($projectsCaptions[$i]) . "').click(function () {

Categories

Resources