I'm trying to update multiple <div> without refreshing the whole page and figured that if I cycle through an array using the index I can achieve that, but it's not working at all.
However when I replace event[index]['fullName'] in the prevEvent function with index, the page gets updated.
How do I update the page contents without refreshing the whole page?
<script type="text/javascript" >
var index=0;
//pass php array to javascript
var event= <?php echo json_encode($event); ?>;
document.getElementById("fullName").innerHTML = event[index]['fullName'];
document.getElementById("emailAddress").innerHTML = event[index]['emailAddress'];
document.getElementById("phoneNumber").innerHTML = event[index]['phoneNumber'];
document.getElementById("childName").innerHTML = event[index]['childName'];
document.getElementById("theater").innerHTML = event[index]['theater'];
document.getElementById("movie").innerHTML = event[index]['movie'];
document.getElementById("eventDate").innerHTML = event[index]['eventDate'];
document.getElementById("eventTime").innerHTML = event[index]['eventTime'];
document.getElementById("eventType").innerHTML = event[index]['eventType'];
document.getElementById("numOfPeople").innerHTML = event[index]['numOfPeople'];
document.getElementById("partyRoomBook").innerHTML = event[index]['partyRoomBook'];
document.getElementById("partyRoomTime").innerHTML = event[index]['partyRoomTime'];
document.getElementById("description").innerHTML = event[index]['description'];
document.getElementById("specialAttention").innerHTML = event[index]['specialAttention'];
function prevEvent(){
index--;
document.getElementById("fullName").innerHTML = event[index]['fullName'];
}
</script>
Related
I am trying to make a PHP page that embeds a JavaScript into the page that makes some YouTube videos on the page and so on, that works fine, but I have another script on the page that should sort these YouTube videos based on the amount of views they have. That normally works, but since I started working on PHP for the page so I don't have to hardcode everything, it doesn't work.
Code:
<script src="jquery-3.2.1.min.js"></script>
<html>
<body>
<?php
$youtubeID = array("KxEhALUc_xo", "HHuOu8L5f58", "DANypN7iXsI");
$len = count($youtubeID);
for ($i = 0; $i < $len; $i++) {
$embedCode = "<script>
var id = ('" . $youtubeID[$i] . "')
$.getJSON('https://www.googleapis.com/youtube/v3/videos?part=statistics&id=" . $youtubeID[$i] . "&key=', function(data) {
$.getJSON('https://www.googleapis.com/youtube/v3/videos?part=snippet&id=" . $youtubeID[$i] . "&key=', function(data2) {
var tags = data2.items[0].snippet.tags;
var likes = data.items[0].statistics.likeCount;
var viewcount = data.items[0].statistics.viewCount;
var title = data2.items[0].snippet.title;
var channel = data2.items[0].snippet.channelTitle;
$('div#videocontainer').append('<div class = videoframe><iframe src = \"https:\\\\\\\\www.youtube.com\\\\embed\\\\" . $youtubeID[$i] . "\" width = 854 height = 510 frameborder= 0 allowfullscreen></iframe><div class = countercontainer><div class = counter>View count:'+viewcount+'</div></div><div class = titlecontainer><div class = title>'+title+'</div></div><div class = likescontainer><div class = likes>'+likes+'</div></div></div>');
});
});
</script>
";
echo $embedCode;
}
?>
<script>
$('button#viewsasc').click(function() {
var videos = $('div.videoframe').get();
videos.sort(function(a,b) {
return parseInt($(a).find('div.counter').text()) - parseInt($(b).find('div.counter').text());
});
$('div#sortedcontainer').html($(videos));
});
$('button#viewsdesc').click(function() {
var videos = $('div.videoframe').get();
videos.sort(function(a,b) {
return parseInt($(b).find('div.counter').text()) - parseInt($(a).find('div.counter').text());
});
$('div#sortedcontainer').html($(videos));
});
</script>
<button id = 'viewsasc'>desc</button>
<button id = 'viewsdesc'>asc</button>
<div id = 'videocontainer'></div>
<div id = 'sortedcontainer'></div>
</body>
</html>
I know it all looks like a mess, but its just a prototype ;).
So as you can see, I have a little array with 3 YouTube video IDs, I then try to embed a JavaScript code that will get som JSON data, make some divs, and show the video with youtubes "iframe".
That all works good, I have 3 YouTube videos showing on my page, and I have the external text with all the views, title, and likes showned.
WHAT's not working is this part:
<script>
$('button#viewsasc').click(function() {
var videos = $('div.videoframe').get();
videos.sort(function(a,b) {
return parseInt($(a).find('div.counter').text()) - parseInt($(b).find('div.counter').text());
});
$('div#sortedcontainer').html($(videos));
});
$('button#viewsdesc').click(function() {
var videos = $('div.videoframe').get();
videos.sort(function(a,b) {
return parseInt($(b).find('div.counter').text()) - parseInt($(a).find('div.counter').text());
});
$('div#sortedcontainer').html($(videos));
});
</script>
<button id = 'viewsasc'>desc</button>
<button id = 'viewsdesc'>asc</button>
<div id = 'videocontainer'></div>
<div id = 'sortedcontainer'></div>
So when i press these buttons:
<button id = 'viewsasc'>desc</button>
<button id = 'viewsdesc'>asc</button>
it will indeed move the "videoframe" div into the "sortedcontainer" div, but it is not sorted, it's just moved to another div, so that's pretty useless. Here is gyazo so you can see what i mean: https://gyazo.com/dc9baa1f1342ffc08c66b2db41d3a4d0
I am very confused by PHP and not very good at it as you can guess, there is probably some obvious rule I didn't know about, I only just started to study PHP.
I've been trying to fetch some values from a JSON file using the $.getJSON method. The first two loops are static so I wrote the below code to fetch the value of "layers.name". From the third loop, the data in the layers may or may not be available. How can I fetch the value of all "layers.name"presented in the JSON file
PS: The JSON file is an output generated from a software where the layer is presented
in this format
Here the code I've worked so far where I get the first two loop layers.
Html
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="test.js"></script>
</body>
Javscript
$.getJSON('https://api.myjson.com/bins/6atbz', function(data) {
var layer = data.layers.reverse()
for (i=0; i<layer.length; i ++){
name = data.layers[i].name
id= data.layers[i].do_objectID
var className = '.'+id
var main = "<div class=\""+id+"\" data-number=\""+i+"\">"+name+"<\/div>"
$('body').append(main);
var subLayer = data.layers[i].layers.reverse()
for(j=0; j<subLayer.length; j++){
newname = data.layers[i].layers[j].name
$().append(' '+newname);
var subsubLayer = data.layers[i].layers[j]
var sub = "<div class=\""+newname+"\" data-number=\""+j+"\">"+newname+"<\/div>"
$(className).append(sub);
}
}
})
Thanks
Link to Fiddle
I think it's a good idea use recursion. Here is example:
var container = document.getElementById("container");
$.getJSON('https://api.myjson.com/bins/6atbz', function(data) {
buildTree(data, container)
})
function buildTree (node, container) {
var layers = node.layers || [];
console.info(node);
layers.forEach(function(item) {
var newContainer = document.createElement('div');
var span = document.createElement('span');
span.innerHTML = item.name;
newContainer.appendChild(span);
container.appendChild(newContainer);
if(item.layers){
buildTree(item, newContainer)
}
});
}
Here is live demo
I am making a registration page that allows you to register an account to a mysql database for my uni project.
In this page you can also 'select' your avatar picture. Here is the code below:
<u>Select your avatar:</u><br>
<?php
// open this directory
$image_dir = opendir("images/avatars");
// get each entry
while( $image = readdir( $image_dir ) )
{
$dirArray[] = $image;
}
// close directory
closedir($image_dir);
// count elements in array
$indexCount = count($dirArray);
// loop through the array of files and print them all in a list
for($index=0; $index < $indexCount; $index++)
{
$extension = substr($dirArray[$index], -3);
if( $extension == "jpg" || $extension == "gif" )
{
//echo("<a href='#'>");
echo("<img id='$index' onClick='SetAvatar($index)' img src='images/avatars/$dirArray[$index]' class='o'> ");
//echo("</a>");
}
}
?>
<script>
function SetAvatar(id) {
var image = document.getElementById(id);
if( CurSelectedImage != null && id != CurSelectedImage )
{
var image_to_unselect = document.getElementById(CurSelectedImage);
image_to_unselect.Selected = false;
image_to_unselect.style.border = null;
}
if( image.Selected != true )
{
image.style.border = 'medium solid blue';
image.Selected = true;
SelectedImage = id;
}
else
{
image.style.border = null;
image.Selected = false;
SelectedImage = null;
}
}
</script>
This selects the avatar picture, makes the border blue and stores the selected image id in a variable but how would I pass the variable with the selected image id back to php so I can save it??
Thanks
can you show your CSS codes too ?
or you can find here jQuery select and unselect image
your answer
You have to think about your application design. Mixing PHP and Javascript isn't the best idea. Use a API instead of mixing code. You can call this API with Ajax. I think this is a good design choice:
Create a getImages API in PHP: You output the data in a json array.
You calling this api with javascript and generating the DOM with the json
You creating a click handler in javascript and calling again a API in PHP
You getting the json data in PHP and saving it in your db
:)
My suggestion would be to use a CSS class. Remove any existing instances of the class then add the class to the selected image.
function SetAvatar(id) {
//remove existing border(s) a while loop is used since elements is a live node list which causes issues with a traditional for loop
var elements = document.getElementsByClassName("selected-avatar");
while (elements.length > 0) {
var element = elements.item(0);
element.className = element.className.replace(/(?:^|\s)selected-avatar(?!\S)/g , '');
}
var image = document.getElementById(id);
image.className += " selected-avatar";
}
To pass the avatar value, I'd suggest using a form to pass all of your registration data to process_register (if you are not already). You can add an input of type hidden to your form and populate the value through javascript on submit.
html:
<form id="registration-form" action="process_register.php" method="put">
<input id="registration-avatar" type="hidden" />
<button id="registration-submit">Submit</button>
</form>
javascript:
document.getElementById("registration-submit").onclick = function(){
var avatarValue; //you'll need to write some code to populate the avatarValue based on the selected avatar image
document.getElementById("registration-avatar").value = avatarValue;
document.getElementById('registration-form').submit();
};
Then in php you can get the values using $_POST
http://php.net/manual/en/reserved.variables.post.php
I have created a page containing a text-area field and few check boxes, from where user can write many domain names in each line in text-area field, and then can choose different domain type through check-boxes. then user clicks on submit button which is redirected to bulk domain search page ?
Link to page where I'm trying to do this is --
http://www.ailogica.com/wp/packages/
I tried to create a simple submit button, but that does not work, then I wrote following code to submit the data by calling a function --
<script type="text/javascript">
function alerttlds() {
jQuery.noConflict();
var i = 0;
var j = 0;
var values = new Array();
var tld = new Array();
var bulkdomains = new Array;
jQuery.each(jQuery("input[name='tld[]']:checked"), function() {
tld[j++] = jQuery(this).val();
});
for(var k = 0; k < tld.length; k++) {
var lines = jQuery('textarea[name=sld]').val().split('\n');
jQuery.each(lines, function(){
bulkdomains[i++] = this+tld[k];
});
}
//alert(bulkdomains.join("\n"));
document.getElementById('bulkdomains').value = bulkdomains.join("\n");
document.forms["bulkchecks"].submit();
}
</script>
I'm trying to create a simple javascript game for college and am having trouble getting what i want to display on screen.
my script is as follows:
var qArray = new Array();
qArray[0] = {image:"Images/q1.png"};
qArray[1] = {image:"Images/q2.png"};
qArray[2] = {image:"Images/q3.png"};
qArray[3] = {image:"Images/q4.png"};
qArray[4] = {image:"Images/q5.png"};
var count = 0;
var question = qArray.splice(count,1);
when i use this i get "undefined":
document.getElementById("question").innerHTML = question.image;
and when i use this i get nothing:
document.getElementById("question").src = question.image;
my html is just a simple div like so:
<div id = "question" align = "center">
</div>
i need to have the "count" variable because it increments to show the next image for the next question
if anyone could help that would be great
Here is a working Fiddle. qArray.splice() doesn't work because it actually removes that element from the array and returns a new array while you were just looking for a specific index in the array (not to mention you just deleted the element you were looking for)
This works. I used a random imgur image to show that it does indeed load.
<html><head></head><body>
<img src="" id="question"></img>
<script type="text/javascript">
var qArray = new Array();
qArray[0] = {image:"http://i.imgur.com/pGpmq.jpg"};
qArray[1] = {image:"Images/q2.png"};
qArray[2] = {image:"Images/q3.png"};
qArray[3] = {image:"Images/q4.png"};
qArray[4] = {image:"Images/q5.png"};
var count = 0;
var question = qArray[count];
document.getElementById('question').src = question.image;
</script>
</body>
</html>