I'm not too sure how to explain this, basically I want to make a array of images (hundreds of images) and then I would like a random 10 to be displayed on my website without any text. I'm not sure if it's possible to do this any other way.
function packOpen()
{
var card = new Array();
card[0] = "Messi";
card[1] = "Ribery";
card[2] = "Ronaldo";
card[3] = "Neymar";
card[4] = "Robben";
card[5] = "Casillas";
}
I have tried making a array, but it doesn't display a result.
If the number of images really is in the hundreds you could use a PHP script to generate the array. It will scan a directory and find the images then generate a JavaScript array.
Save this as images.php
<?php
header("Content-type:text/javascript");
//The directory of your images
$dir = "img";
echo "var images = [";
$arr = preg_grep("/[A-Za-z0-9].(jpg|gif|png|bmp|jpeg|svg)/",scandir($dir));
$index = 0;
foreach($arr as $value) {
$index++;
if($index < count($arr)) {
echo "\"" . $dir . "/" . $value . "\", ";
}
else {
echo "\"" . $dir . "/" . $value . "\"";
}
}
echo "];";
?>
Then if you include it in the HTML file you can use the array variable images to access the array.
The in the JavaScript file (script.js):
window.onload = function() {
var div = document.getElementById("images");
for(var i = 0; i < images.length; ++i) {
var img = document.createElement("img");
img.src = images[Math.floor(Math.rand() * 10)];
div.appendChild(img);
}
};
Finally the HTML file:
<script src="images.php"></script>
<script src="script.js"></script>
<div id="images"></div>
If you simply want a function to return the adress of an img you could try:
function packOpen()
{
var card = new Array();
card[0] = "Messi";
card[1] = "Ribery";
card[2] = "Ronaldo";
card[3] = "Neymar";
card[4] = "Robben";
card[5] = "Casillas";
return card[Math.floor(Math.rand() * card.length)];
}
Your array is certanly looking fine to me. One approach to your problem could be to use the javascript functions "slice", "splice" and "sort".
function packOpen(numResults)
{
var card = new Array();
card[0] = "Messi";
card[1] = "Ribery";
card[2] = "Ronaldo";
card[3] = "Neymar";
card[4] = "Robben";
card[5] = "Casillas";
card.slice(0);
card.sort( function() {
return .5-Math.random();
});
return card.splice(0,numResults);
}
var randomItems = packOpen(10);
Related
Hi I have a problem with this one. Instead of having a result of uniqueID = value I'm having a result like this uniqueID = undefinedvalue
JavaScript Code
function read(a){
var html;
if(a.indexOf("http://") === 0 || a.indexOf("https://") === 0)
html+="<a target='_blank' href='"+a+"'>"+a+"</a><br>";
html+=htmlEntities(a);
var audio = new Audio('lib/beep.ogg');
audio.play();
var uniqueID = document.getElementById("mapo").innerHTML= html;
window.location.href = "http://localhost/QR_JEFF/server.php?uniqueID=" + uniqueID;
}
PHP Code
$db = mysqli_connect('localhost', 'root','','suffrage');
$uniqueID = $_GET['uniqueID'];
$query = "SELECT * FROM applicant_table WHERE unique_id='$uniqueID'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$logged_in_user = mysqli_fetch_assoc($results);
if($logged_in_user['validation_status'] == 'Verified' && $logged_in_user['voting_status'] == 'No'){
$_SESSION['unique_id'] = $id;
$_SESSION['validation_status'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: wow.html');
}
}
This is the output in my URL. check this out to see the problem
Thank you in advance. :)
var uniqueID = document.getElementById("mapo").innerText;
console.log(uniqueID);
/*var uniqueID = document.getElementById("mapo").value;*/
<div id="mapo">123456789</div>
<!--<input id="mapo" type="hidden" value="123456789" />-->
I solved my own problem. This is the solution.
function read(a){
var html=htmlEntities(a);
var audio = new Audio('lib/beep.ogg');
audio.play();
var uniqueID = document.getElementById("mapo").innerHTML= html;
window.location.href = "http://localhost/QR_JEFF/server.php?uniqueID=" + uniqueID;
}
I realized that the var=html dont have any value and when I concatenate it to my htmlEntities it resulted into an undefined index. So I remove it and place the htmlEntities straight to the var html. :)
When i put
$link15 = $link15.$U;
$newpdf1 = $newpdf1.$_SESSION['arrayvalue']."\r\n\r\n".$link15."\r\n\r\n";
$link15 = "";
this line of code in foreach/for loop the the script is stop after displaying one result. and when i remove this line of code it runs.
Below is the complete script:
for ($i = 0, $count = count($arr1); $i < $count; $i++) {
print $arr1[$i]."\r\n\r\n";
$_SESSION['arrayvalue'] = "$arr1[$i]";
$in = $arr1[$i];
$in = str_replace(' ','+',$in); // space is a +
$result15 = httpGet("https://www.google.com/cse?cx=003255331468891741234:xxxxxxxxxx&client=google-csbe&output=xml_no_dtd&q='.$in.'&oq='.$in.'");
//echo $result15;
//this is to get perticular tag/node value
$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($result15);
$N = $dom->getElementsByTagName('U');
foreach ($N as $U) {
echo $U->nodeValue, PHP_EOL."<br/>";
$link15 = $link15.$U;
}
$newpdf1 = $newpdf1.$_SESSION['arrayvalue']."\r\n\r\n".$link15."\r\n\r\n";
$link15 = "";
}
Where i am doing error in concatenation or any other error.
Thank You!
Based on your code, $U is an object, yet you're trying to concatenate it to $link15.
Try changing this:
$link15 = $link15.$U;
To this:
$link15 = $link15.$U->nodeValue;
You cannot concatenate an object with a string
try the below code (what I have changed is I am accessing the particular key named as "nodeValue" in your $U object. If you want to add another change it accordingly, you need to access the particular key or bunch of keys depending on your requirement)
for ($i = 0, $count = count($arr1); $i < $count; $i++)
{
print $arr1[$i]."\r\n\r\n";
$_SESSION['arrayvalue'] = "$arr1[$i]";
$in = $arr1[$i];
$in = str_replace(' ','+',$in); // space is a +
$result15 = httpGet("https://www.google.com/cse?cx=0032553314688917412345:xxxxxxxxx&client=google-csbe&output=xml_no_dtd&q='.$in.'&oq='.$in.'");
//echo $result15;
//this is to get perticular tag/node value
$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($result15);
$N = $dom->getElementsByTagName('U');
foreach ($N as $U) {
echo $U->nodeValue, PHP_EOL."<br/>";
// here you need to access the particular key or bunch of keys depending on your requirement
$link15 = $link15.$U->nodeValue;
}
$newpdf1 = $newpdf1.$_SESSION['arrayvalue']."\r\n\r\n".$link15."\r\n\r\n";
$link15 = "";
}
Hope this helps.
There are plenty of examples of using database records to disable certain dates (unavailable) using JSON and AJAX however for some reason, these are done in PHP. Is there reason why it isn't done in JAVA and how can I replace the PHP file with Java for the exact same result?
checkDates.php
<? php
$sql = "SELECT start from gbh_rooster_afwijkend WHERE dlnmrID = '".$_GET['dld'].
"'";
$res = mysql_query($sql) or die(mysql_error());
$checkDates = array();
while ($row = mysql_fetch_assoc($res)) {
$checkDate['start'] = $row['start'];
$checkDates[] = $checkDate;
}
echo json_encode($checkDates);
?>
Javascript
$.getJSON('script/php/afwijkendrooster/checkDates.php?dld='+ id, function(json){dates=json;});
function checkAvailability(mydate){
var myBadDates = dates;
var $return=true;
var $returnclass ="available";
$checkdate = $.datepicker.formatDate('dd-mm-yy', mydate);
// start loop
for(var x in myBadDates)
{
$myBadDates = new Array( myBadDates[x]['start']);
for(var i = 0; i < $myBadDates.length; i++)
if($myBadDates[i] == $checkdate)
{
$return = false;
$returnclass= "unavailable";
}
}
//end loop
return [$return,$returnclass];
}
I have the following data in an SQL database
cname, ccode, colour
Great Britain, GB, 1
Italy, IT, 1
France, FR, 1
Spain, ES, 1
How can I create a JavaScript object like below?
var countries = {"GB":1, "IT":1, "FR":1, "ES":1}
So far, I have the following code;
PHP
$query2 = "SELECT ccode,colour FROM country_data WHERE 1";
$result2 = mysql_query($query2);
if (!$result2) {
die('Invalid query: ' . mysql_error());
}
$rows2 = array();
while($r2 = mysql_fetch_assoc($result2)) {
$rows2[] = $r2;
}
JS
var colours = '<?php print json_encode($rows2); ?>';
Which returns:
[{"ccode":"GB","colour":"1"},{"ccode":"IT","colour":"1"},{"ccode":"FR","colour":"1"},{"ccode":"ES","colour":"1"}]
change this code
while($r2 = mysql_fetch_assoc($result2)) {
$rows2[] = $r2;
}
to this one:
while($r2 = mysql_fetch_assoc($result2)) {
$rows2[$r2['ccode']] = $r2['colour'];
}
change php code as told in others answers too and it should be like
$rows2 = array();
while($r2 = mysql_fetch_assoc($result2)) {
$rows2[$r2['ccode']] = $r2['colour'];
}
if it does not work then try this:
$rows2 = array();
while($r2 = mysql_fetch_assoc($result2)) {
$rows2["'".$r2['ccode']."'"] = $r2['colour'];
}
if it also does not work then try this:
$rows2 = array();
while($r2 = mysql_fetch_assoc($result2)) {
$rows2[{$r2['ccode']}] = $r2['colour'];
}
I'm trying to transfer php variables, that I have pulled out of a database, into three different javascript arrays. I use a php function to dynamically create a css dropdown menu, and then use a php loop to transfer the php variables into the javascript arrays. I then try to use a javascript function to initialize the attributes of the css menu. The same function is called from each of the links of the menu to update the menu based on the javascript arrays.
Here is the php function:
function createMenu()
{
//create the proper drop down menu, based on the total number of games played and the max number of games
$totalVods = count($this->VodID);
$menuArray = array();
for($i = 0; $i < $totalVods; ++$i)
{
if ($this->currentVodID != $i)
{
$menuArray[] = ($i+1);
}
}
if ( $totalVods < $this->MaxGames )
{
for ($i = $totalVods; $i < $this->MaxGames; ++$i)
{
$menuArray[] = ($this->currentVodID+1);
}
}
$totalGames = count($menuArray);
printf("<p>$this->Name</p>");
printf("<div id='cssmenu2'>");
printf('<ul>');
if ($menuArray)
{
printf('<li id="vod1" class="has-sub last"><span></span><img class="arrow" src="/images/Arrow.png">');
printf('<ul>');
if ($totalGames > 1)
{
for ($j = 0; $j < ($totalGames - 1); ++$j)
{
$vodNum = 'vod'. ($j+2);
printf("<li id='$vodNum' onclick=''><span></span></li>");
}
}
$vodNum = 'vod'. ($totalGames + 1);
printf("<li id='$vodNum' class='last' onclick=''><span></span></li>");
printf('</ul>');
}
else
{
printf('<li id="vod1"><span>Game 1</span>');
}
printf('</li>');
printf('</ul>');
printf('</div>');
//---------------------------------------------------
// function works fine up till here
// ------------------------------------------------
printf('<script>');
printf('alert("Right after totalGames");'); /* If I take this part out, up till the next comment, the rest works, but none of this part, even the alerts, works */
for($i = 0; $i < $totalVods; ++$i)
{
printf("vodName[$i] = 'Game ". ($i + 1) ."';");
printf("alert('vodName[$i]= '+vodName[$i]);");
$this->VodObject->selectVod($this->VodID[$i]);
$address = $this->VodObject->returnVod();
printf("vodAddress[$i] = '$address';");
$date = $this->VodObject->returnDate();
printf("vodDate[$i] = '$date';");
}
if ($totalVods < $this->MaxGames )
{
for ($i = $totalVods; $i < $this->MaxGames; ++$i)
{
printf("vodName[$i] = 'Game ". ($i + 1) ."';");
$gameNum = $i +1;
$address = "<div class='matchNoVOD'>There is no Game $gameNum<br />Series ended before this game.</div>";
printf("vodAddress[$i] = '$address';");
printf("vodDate[$i] = '';");
}
}/* End of the section that is having problems- if I take this out, the rest of the alerts work */
printf('alert("Right before window.onload");');
printf('window.onload = function() { switchVod(0); };');
printf('</script>');
}
In the javascript part of the above function, I access a php class called vodObject- that just accesses the database and returns the strings I want to place in the javascript array.
The javascript function that updates the css menu is placed in the part of the html, and looks like this:
<script>
var vodName = Array();
var vodAddress = Array();
var vodDate = Array();
function createfunc(i)
{
return i;
}
function switchVod(vodID)
{
alert("switchVod ran");
alert('vodID= ' + vodID);
var x=document.getElementById("vod1");
var y = x.getElementsByTagName("span");
y[0].innerHTML = vodName[vodID];
for (var i=0; i < vodName.length; i++)
{
if ( i != vodID)
{
var id = createfunc(i);
var gameNum = i + 2;
var gameID = "vod" + gameNum;
var x = document.getElementByID(gameID);
var y = x.getElementsByTagName("span");
y[0].innerHTML = vodName[i]
x.onclick = function() { switchVod(id); }
}
}
alert("after for loop");
alert("1");
document.getElementById('vodObj').innerHTML = vodAddress[vodID];
alert("2");
document.getElementById("vodDate").innerHTML = vodDate[vodID];
alert("finished");
}
</script>
The createfunc(i) is meant to get around the closure issues I heard about.
Any ideas about what I can try to fix my code? Thank you for your help, in advance!
In the JS code, you can just use var city = '<?=$city;?>';, for example.
If I got you right, you can make it using AJAX. The PHP file while print this:
echo json_encode($your_php_array);
Then, using JQuery $.getJSON method
$.getJSON('json.php', function(response) {
/* do your stuff here */
console.log(response); // This var has the json object
});
Let me know if it's useful.