First check this site: check this first plz
hi , Im from mexico and Im auto learning html, css, js and php, for personal purposes.
IM trying to add that code to my testing page, the example is Example 3 — Random Fact Generator (form). When you click the random generaton button, it makes random text appear the problem is..WHERE IS IT COMMING FROM? and xml? php server?...I dont know..I checked in ALL the code and nothing :(, I can add random text with other methods like JS with a case and a random.math but I prefer like that page, any sugestions? thx a lotssss
It comes from : http://juicystudio.com/experiments/ajax/form/fact.php
Go see http://juicystudio.com/experiments/ajax/form/script.js
So it comes from a PHP file. The PHP could be reading a XML file, a CSV file, a database, etc.
Let me know if you still have questions.
Edit:
If you don't want to overwrite the last fact you have to change this from script.js:
if (objCurrent)
objCurrent.parentNode.replaceChild(objReplacement, objCurrent);
else
{
var objContent = document.getElementById('content');
objContent.appendChild(objReplacement);
}
To
var objContent = document.getElementById('content');
objContent.appendChild(objReplacement);
Edit 2:
CSV file (test.csv)
1,test1
2,test2
3,test3
4,test4
5,test5
Here is the PHP adapt from the site you have supplied
<?php
$handle = fopen("test.csv", "r");
$array= array();
while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
array_push($array,$data);
}
if(count($array) > 0){
$id = rand(0, count($array) -1);
echo $array[$id][1];
}
?>
It gets the text from http://juicystudio.com/experiments/ajax/form/fact.php
In this section, it opens a connection to that page:
if (objXMLRequest)
{
objXMLRequest.onreadystatechange = processResult;
objXMLRequest.open('GET', 'fact.php', true);
objXMLRequest.send(null);
}
When the connection's state change event fires, it calls the method processResult. That method checks that the readystate is 4 (completed) and the status is 200 (OK) and updates the text on the page.
You don't need a database or to read files to make that example page. The easiest way would be to create an array of facts and output one at random, like this:
<?php
$facts = array("fact 1", "fact 2", "fact 3", "fact 4", "fact 5", "fact 6");
$random_number = rand(0, count($facts)-1);
echo $facts[$random_number];
?>
Related
I have a li and inside that i have a div class="reload" that have some content that should be reloaded for every 10 sec.
<li class="b1">
<div class="reload">
</div>
</li><!--col-->
So therefore i have got a script that does just that.
<script type="text/javascript">
$('.b1').children('.reload').load('php/reload/reload.php'); // load the content at start
window.setInterval(function(e) {
$('.b1').children('.reload').load('php/reload/reload.php'); // reload the content every 10 sec
}, 10000);
In the reload.php i get some content from a database. It looks like this, sort of..
<?php
// login info
require("../../connection_to_database_login.php");
// My query
$result = mysqli_query($l,'SELECT * FROM abcd WHERE efg=1 LIMIT 1');
// include some stuff
$r = mysqli_fetch_row($result);for ($p = 0; $p < $r[4]; ++$p){include("../some/stuff_$p.php");};
// include a random picture script or just load a picture
if ($r[4] == 0){include ('getRandPic.php');}
else {echo ('<img src="images/picture.png" />');}
?>
So far so good.. everything works.
The getRandPic.php file.. select one random picture from a folder
<?php
$img_dir = "images/images";
$images = scandir($img_dir);
$html = array();
foreach($images as $img) {
if($img === '.' || $img === '..') {continue;}
if ( (preg_match('/.jpg/',$img)) || (preg_match('/.gif/',$img)) || (preg_match('/.tiff/',$img)) || (preg_match('/.png/',$img)) ) {
$html[] .= '<img class="img-responsive" src="'.$img_dir.$img.'" />';
}
else { continue; }
};
echo $html[rand(0,6)];
?>
So this works ok.
But the thing is, i want to check if it shall "include a random picture script or just load a picture" every 5sec.
Therefore i need to check "if ($r[4] == 0)" every 5 sec.
So my question is: Is there any other way to do that?
As you asked in the comment... This is a rough guide only. You will have to develop and write your own code based on this guide.
Step 1a: optional
Make an ajax call from your webpage to the server. to get image file names.
Step 1b:
On server side in php file perform DB operation.
Let assume you have a table imageTable and column name images so you would read from DB using query SELECT images FROM imageTable
You will have to change the query, add condition (e.g. all images with animal and cute tags) to it and if you want limit the number of files that you want to randomize then you will have to add that as well.
Step 2:
Once you read from DB, as you are already doing, read all image names and put it in json format (json_encode). I personally prefer json. If you prefer, you can also return all names in simple string where names are separated by comma.
Step 3:
Store your response in JS.
var imagesArray = new Array();
$.ajax({
type: 'post',
url: pathtophpfile,
success: function(htmll) {
// get object with all data
imagesArray= JSON.parse(htmll);
},
});
Step 4:
Once you have it in your js object named imagesArray, use setInetval to perform task every 5 seconds.
Read a random value from 0 to imagesArrays length, and change the source of your image tag, <img class="img-responsive" src="+ randomimage +" />
Periodic updater will do your task.
Use ajax framework, it will reduce your db connection burden at the server side.
Have a look at it. It is a simple and nice way to achieve your task.
http://prototypejs.org/doc/latest/ajax/Ajax/PeriodicalUpdater/
There was a great article posted by CSS-Tricks.com describing how to create a poll using PHP and a MySQL database. I've followed this and created a nice poll for myself. I noticed in the comments a mentioning of using AJAX to show the results on the same page instead of a completely separate page.
I am wondering what is the best way to display PHP Poll results on the same page?
UPDATE:
The answer is really simple. In fact, CSS-Tricks' poll without AJAX in my opinion is more difficult since it requires a database. This one does not!
The complete tutorial for creating a poll with PHP and AJAX is can be viewed here:
http://www.w3schools.com/php/php_ajax_poll.asp
I just wanted to clarify how to set the arrays up for more than two poll options. First you get the "database" (i.e. text file, not MySql).
//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);
Then you put the data in an array:
//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];
//if multiple options
$array = explode("||", $content[0]);
$option1array = $array[0]; //note: these values can be text values also. If text value, nothing changes with this part of the code.
$option2array = $array[1];
$option3array = $array[2];
$option4array = $array[3];
Store Data in "database"
if ($vote == 'option1')
{
$option1array = $option1array + 1;
}
if ($vote == 'option2')
{
$option2array = $option2array + 1;
}
if ($vote == 'option3')
{
$option3array = $option3array + 1;
}
if ($vote == 'option4')
{
$option4array = $option4array + 1;
}
Then, output your results. For file structure and AJAX script, see the complete tutorial.
You have two options:
1) Use ajax just as you suggested in your question, when you submit the vote via ajax, get the results back as the response.
2) Get the results before the vote is submitted, it will still need to be submitted via ajax if you want to stay on the same page. But instead of using ajax to get back the results, since you have the results prior to the vote you could just add one vote to the appropriate selection choice, then use Javascript / CSS to change the results from hidden to displayed.
okay here is my code :
var co = 0;
var comp = '';
<?php $i = 0;?>
while (co < <?php echo $db->count_rows(); ?>)
{
if ((parseInt(value) >= <?php echo $mfr[$i] ?>) && (parseInt(value) <= <?php echo $mto[$i] ?>))
{
comp = 'T';
break;
}
co++;
<?php $i++; ?>
}
i'm still learning about this whole php and javascript thing, and i know there are many things that i still had to work to to improve my understanding to this both language. that's why i really need your help in this
i'm trying to get the while iteration to work so i can compare the variable from javascript with variable from php which took the value from database. the php variable ('$mfr' and '$mto'), as you can see, is an array. now i want it to look at every element of both and if it meets the condition then it will update the variable 'comp' and stop the whole while iteration
but the problem is the '$i' variable doesn't do the iteration thing. it runs only once so my '$mfr' and '$mto' value doesn't go anywhere. how can i fix this so i can compare the javascript value with the php '$mfr' and '$mto' value?
your help would be much appreciated, thank you :)
EDIT
well, it is actually a function of custom validation for jqgrid.
and i do know that php is a server-side and javascript is a client-side language theoretically, though i don't really know it is practically
what i'm actually trying to do is when a user input a value and submit it, the system will check whether the value that was entered are between value of 'fromid' and 'toid' column of a table in database
here is my full code of the function
function checkid(value)
{
var co = 0;
var comp = '';
<?php $i = 0;?>
while (co < <?php echo $db->count_rows(); ?>)
{
if ((parseInt(value) >= <?php echo $mfr[$i] ?>) && (parseInt(value) <= <?php echo $mto[$i] ?>))
{
comp = 'T';
break;
}
co++;
<?php echo $i++; ?>
}
if (comp != 'T')
{
return [true, "", ""];
}
else
{
return [false, "Value entered is already between a range. Please try again!", ""];
}
}
while this is how i got the '$mfr' and '$mto' variable
<?php
$db=new database($dbtype, $dbhost, $database, $dbuser, $dbpassword, $port, $dsn);
$db->query("select fromid, toid from CORE_ID");
$i = 0;
while($row = $db->get_row())
{
$mfr[$i] = $row[fromid];
$mto[$i] = $row[toid];
$i++;
}
?>
if theres any better way to do this, then please do tell me
Typically, PHP is for server side logic and JS is for client side logic. If you want to send a value from JS to be processed in PHP, you'll probably need to use something like AJAX, which jQuery makes pretty easy with jQuery.ajax().
Getting the client value to be processed is the difficult part. Once you can do that, rewriting your code logic in full PHP should not be difficult.
EDIT: If I'm misunderstanding where variable value comes from, please say so!
EDIT 2: It looks like you want to have client input compared to server side data. JS will not have access to your PHP variables unless they are specifically sent there. Likewise, you can send your JS value to the server for validation in the PHP.
In your case, you could use JSON to send send the JS your validation dates. Assuming you don't have too many dates, it will probably be faster than sending a value to the server and waiting for a response.
I found a good example of using JSON at another post. You can send an array like:
<?php
$xdata = array(
'foo' => 'bar',
'baz' => array('green','blue')
);
?>
<script type="text/javascript">
var xdata = <?php echo json_encode($xdata); ?>;
alert(xdata['foo']);
alert(xdata['baz'][0]);
// Dot notation can be used if key/name is simple:
alert(xdata.foo);
alert(xdata.baz[0]);
</script>
For your code, you could put $mfr and $mto into a single 2D array. Here is how your new JS might look, assuming xdata contains $mfr and $mto:
function checkid(value) {
var co = 0, comp = '', i = 0, nrows = xdata.mfr.length;
while (co < nrows) {
if ((parseInt(value) >= xdata.mfr[i]) && (parseInt(value) <= xdata.mto[i])) {
comp = 'T';
break;
}
co++;
i++;
}
if (comp != 'T') {
return [true, "", ""];
} else {
return [false, "Value entered is already between a range. Please try again!", ""];
}
}
You have a loop in your Javascript, not your PHP. So the PHP is only going to get executed once. You need to rethink your approach. Without knowing what the script is supposed to actually achieve it's difficult to provide working code, but you at least need to put the loop into the PHP instead of the Javascript.
Before I can answer you should understand what's going on exactly:
PHP is being executed on the server, then sends back the result (HTML and Javascript) to the client (the browser).
Javascript is being executed on the client side. So this only starts after PHP is completely done. For this reason you can't mix Javascript and PHP.
Check the source of the page, then you'll see exactly what the server returns (what HTML/Javascript PHP generates) and you'll get a better insight of what happens.
Now, if you understand this, you may be able to solve your own problem. I don't exactly know what you want to do, but I can advice you that if you need Javascript to check values from the database, you should generate Javascript using PHP that defines these values in the Javascript like for example this:
var my_js_var = <?=$my_php_var?>
var another_var = <?=$another_one?>
Now they are defined in Javascript and you can use them (and check them).
When you have a large database it can become inefficient to do it like this and you might want to look into a technology called AJAX, which allows Javascript to do a request to the server and get back data from a PHP script.
You would also want to do this if there's data involved you don't want to be publicly viewable (because everyone can look into the source of your page.
An issue with a dropdown menu. The problem isn't the menu code itself ie ul..etc, but a php chat program im currently embedding. After inserting this code to embed the chat box which appears with no errors the ability to use the ul dropdown link is disabled. The embedded php is in an entirely seperate div from the menu which is located in the #zonebar div.
the embedded code <?php $chat->printChat(); ?> which is in a specific div.
The thing is when i remove this code the dropdown menu buttons work again..
To be more specific the only php code in my html file with appropriate htaccess which allows me to use php in an html document is..
the code below is located at the very top of my page above all tags
<?php
require_once dirname(__FILE__)."/src/phpfreechat.class.php";
$params = array();
$params["serverid"] = md5(__FILE__); // calculate a unique id for this chat
$params["title"] = "A simple chat with user's parameters";
$params["frozen_nick"] = true; // do not allow to change the nickname
$params["shownotice"] = 0; // 0 = nothing, 1 = just nickname changes, 2 = connect/quit, 3 = nick + connect/quit
$params["max_nick_len"] = 20; // nickname length could not be longer than 10 caracteres
$params["max_text_len"] = 300; // a message cannot be longer than 50 caracteres
$params["max_channels"] = 1; // limit the number of joined channels tab to 3
$params["refresh_delay"] = 2000; // chat refresh speed is 10 secondes (10000ms)
$params["max_msg"] = 15; // max message in the history is 15 (message seen when reloading the chat)
$params["height"] = "230px"; // height of chat area is 230px
$params['admins'] = array('daddo' => '1234', 'berthill' => '1234');
$params["debug"] = false; // activate debug console
$chat = new phpFreeChat( $params );
?>
and then the code in the specific div
<?php $chat->printChat(); ?>
link directly the html file without any php content
edited out address after fix
link with the php code embedded
I am going to wager a guess at this since looking through about a dozen javascript files is not something I really want to do.
Your dropdown menu uses jQuery... which is great.
Your chat uses Prototype... also great.
They are most likely not playing well together. You can try doing this:
var $j=jQuery.noConflict();
$j(document).ready(function(){
$j("#zone-bar li em").click(function() {
var hidden = $j(this).parents("li").children("ul").is(":hidden");
$j("#zone-bar>ul>li>ul").hide()
$j("#zone-bar>ul>li>a").removeClass();
if (hidden) {
$j(this)
.parents("li").children("ul").toggle()
.parents("li").children("a").addClass("zoneCur");
}
});
});
It may or may not work, but using $j instead of $ may fix the issue.
I am trying to auto generate pages.
What I am trying to do is make a upload form for an image upload that's displayed in a gallery.
I have this but I then want each image to have a page hyper-link auto made for each image where the image can be seen bigger with buying information that's also been uploaded to a MySQL table not 100% with codeigniter I am still luring please look at the site I am trying to build at http://www.fresherdesign.co.uk/PIFF/index.php/main/gallery
This is a direct link to the gallery that I would link to make the page's from, currently they just open a direct link to the image on its own
Any help would be awesome thanks to everyone in advance
Alan Morton
If you want the actual images to be uploaded (and not stored in the database - note that db storage is slightly more difficult to accomplish than your standard upload), you can create a field in the database for the image's location; that is how you are going to correspond your image data with your page content.
Now, if you want a hyperlink to automatically be made, I suggest querying the database of all "Active" entries (again, could be another field unless you simply delete old entries). Each entry should have a unique ID associated with it. This way, when you give the list, simply include a tag similar to
while($row = mysql_fetch_array($query_result)){
// Change this to whatever formatting you need
print '<!-- Whatever content for link -->';
}
Now that's just your loop to get the results. The actual page now should query the database based on the ID given. The query should grab the page content from the database. Something like this would work
<?php
if(!isset($_GET['id'])){
die("Please use a valid link!");
}
$q = mysql_query("SELECT * FROM YOUR_DB_TABLE WHERE ID='".mysql_real_escape_string($_GET['id'])."' LIMIT 1;");
if(!$q || mysql_num_rows($q) < 1){
die("A MySQL Error Occurred: ".mysql_error());
}
while($row = mysql_fetch_array($q)){
// Again, adjust this accordingly
print "Data column 1: ".$row['DataRow1']."<br />".
"Data Column 2: ".$row['DataRow2']."<br />".
"<img src='".$row['ImageLocation']."' />";
}
?>
Now, I haven't tested this exact code, however all of it should work as is. But you will need to adjust it appropriately to fit your requests; but this is one way to accomplish what you're looking for.
Precondition
You'll need to have the directory name in which things are stored, relative to where your php page is located. Obviously, you have this already to create the page. I will assume it is stored in the $dir variable.
Code
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
echo "<a href='http://www.mydomain.com/".$dir."/".$file."'>";
echo "<img src='http://www.mydomain.com/".$dir."/".$file."' />";
echo "</a>";
}
}
Output
This will provide you a list of images that link to the image file itself.
Possible Modifications
1) You may want to only show some of the files in the directory, or a certain amount: Use the if block added here to do that:
if ($handle = opendir($dir)) {
//set $strThatSpecifiesImages to whatever you want;
//for the example, I'm saying that we only want to show files with "gal_image" in the filename
$strThatSpecifiesImages = "gal_image";
$maxFilesToShow = 10; //set this to whatever you want; example max is 10
$count = 0;
while (($count < $maxFilesToShow) && (false !== ($file = readdir($handle))) {
if (strpos($file, $strThatSpecifiesImages) > -1) {
echo "<a href='http://www.mydomain.com/".$dir."/".$file."'>";
echo "<img src='http://www.mydomain.com/".$dir."/".$file."' />";
echo "</a>";
$count++;
}
}
}
2) You might also want to change how things are displayed, so that you don't just have the full image shown here every time. Do this by modifying things in the echo blocks that are outputting HTML. You can have the browser resize the images, or just change it completely so that the links use text instead, or something else.