Javascript "getElementsByClassName" not working - javascript

I have a website with a picture of a tree, I have then used Ajax to remove that tree and insert a number using javascript. What I used for that was;
document.getElementById("cut_oak_tree");
I have now added another tree on the page, which should have the exact same function as the first tree, except that only the tree that you clicked on, shall be removed. To avoid duplicating code, I have tried adding following:
document.getElementsByClassName("cut_oak_tree");
and then changed my div from using id to class. However, nothing happens when I click any of the trees now. My current ajax code right now, looks like this:
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var getClass = document.getElementsByClassName("cut_oak_tree").innerHTML=xmlhttp.responseText;//ask for this.
for(i=0;i<getClass.length;i++)
{
getClass[i].innerHTML = "";
}
}
}
xmlhttp.open("POST","xxx",true);
xmlhttp.send();
}
I have been searching a lot and found that I might need to use a for loop together with the document.getElementsByClassName("cut_oak_tree");
but I can't really get that to work. If I have figured my problem correctly, everything should be good if I could just determine which of the tree images in the div should be removed when it's pressed. Thanks in advance.
EDIT:
Html sample:
<div id "thanks">
<img class="cut_oak_tree" src="http://www.pbpixels.com/x/images/oak.png" onclick="loadXMLDoc(), myFunction()">
<img class="cut_oak_tree" src="http://www.pbpixels.com/x/images/oak.png" onclick="loadXMLDoc(), myFunction()">
</div>

Try the following:
document.getElementsByClassName("cut_oak_tree")[0];
If you want to apply changes to more than one elements with classname cut_oak_tree then you will have to use for loop
var getClass = document.getElementsByClassName("cut_oak_tree");
for(i=0;i<getClass.length;i++)
{
getClass[i].innerHTML = "";
}
Using your earlier HTML with slight modifications you can do the following:
HTML
<div class="cut_oak_tree">
<img src="http://www.pbpixels.com/x/images/oak.png" onclick="loadXMLDoc(this.outerHTML), myFunction()" />
<img src="http://www.pbpixels.com/x/images/oak.png" onclick="loadXMLDoc(this.outerHTML), myFunction()" />
</div>
Hence change your JS function to :
function loadXMLDoc(h)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var getEle = document.getElementsByClassName('cut_oak_tree')[0];
getEle.innerHTML = getEle.innerHTML.replace(h,xmlhttp.responseText);
}
}
xmlhttp.open("POST","http://www.pbpixels.com/x/post.php",true);
xmlhttp.send();
}
Demo Fiddle
Response to comment:
Inorder to uniquely identify clicked <img>s with same images just make minor change to the one of the img srcs from the two.Example give space within src src="http://www.pbpixels.com/x/images/oak.png ".Note the space after .png which will make the difference between the two

I would think that the most straightforward way to do it would be to pass the clicked element into the loadXMLDoc() as a parameter, and then get the parent of that element. Something like this:
HTML
<div id="cut_oak_tree">
<img src="http://www.pbpixels.com/x/images/oak.png" onclick="loadXMLDoc(this), myFunction()">
<img src="http://www.pbpixels.com/x/images/oak.png" onclick="loadXMLDoc(this), myFunction()">
</div>
JS
function loadXMLDoc(clickedElement) {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
clickedElement.parentNode.innerHTML = xmlhttpinnerHTML = xmlhttp.responseText; //ask for this.
}
}
xmlhttp.open("POST","xxx",true); //the xxx's represent my website
xmlhttp.send();
}
NOTE: I'm not 100% sure that I have the logic right, since you changed your original post, while I was typing up my answer. :)
UPDATE #2: I found the original code in the edit history . . . my code should be correct now.

Related

Changing HTML group class with JavaScript variable

I'm using an AJAX function to grab some data from a database and run a simple if statement. I want to use the output variable "test" to change the class (and therefore styling) of an SVG group. I was originally using PHP on page load but now that I'm using AJAX I have to use JavaScript and it isn't working.
Here's the AJAX:
function loadfacebook1()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var obj = JSON.parse(xmlhttp.responseText);
document.getElementById("fbname").innerHTML=obj.name;
document.getElementById("fbtraffic").innerHTML=obj.traffic;
document.getElementById("fbrevenue").innerHTML=obj.revenue;
document.getElementById("fbprofit").innerHTML=obj.profit;
document.getElementById("fbrafrica").innerHTML=obj.rafrica;
var test = document.getElementById('fbrafrica').value;
if(test > 100)
{var africastyle = "b1";
}
}
}
xmlhttp.open("GET","getfacebook.php",true);
xmlhttp.send();
}
And here is the group that I'm trying to change the class of:
<g class="<?php echo $africastyle ;?>" transform="translate(0,239) scale(0.016963,-0.016963)">
As you can see it uses PHP at the moment but how to I replace this with the JavaScript variable "test" that I assigned in the AJAX function?
Thanks,
Will
Here's what I would do. Add an ID to your group element.
HTML:
<g id="myGroup">
JS:
if(test > 100){
var el = document.getElementById('myGroup');
el.setAttribute('class', 'b1');
}

Put HTML tabs using ajax

I want to put tabs created using JQueryUI in my existing HTML page. I have created to display HTML content received using Ajax. But tabs are not shown correctly. Below is my ajax function
function GetVendorProfile(Category,Business) {
var xmlhttp;
if ((Category== 0) || (Business == 0)) {
document.getElementById("ShowVendorProfile").innerHTML="Please select Category";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{ document.getElementById("ShowVendorProfile").innerHTML=
xmlhttp.responseText;
}
}
if ((Category == "Function Hall") && (Business != 0)){
xmlhttp.open("GET","vendorprofile.php?Business="+Business,true);
}
xmlhttp.send();
}
My vendorprofile.php contains simple tabs. Pls let me know if there is any other way to display HTML successfully using ajax.
Try Jquery load
You can easily load from server directly to html:
$("#ShowVendorProfile").load("vendorprofile.php?Business="+Business);

AJAX - PHP to Javascript Multi Array and Split

New to JSON/AJAX here but trying...
PHP page appears to be returning [{"id":"1"},{"id":2}] to my javascript.
How would I convert it to something useful like a dropdown in html?
Code:
<script>
function show(str) {
if (str=="") {
var ajaxDisplay=xmlhttp.responseText;
var res=ajaxDisplay.split("#");
document.getElementById("ajax1").innerHTML=res[1];
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var ajaxDisplay=xmlhttp.responseText;
var res=ajaxDisplay.split("#");
document.getElementById("ajax1").innerHTML=res[0];
}
}
xmlhttp.open("GET","get.php?q="+str,true);
xmlhttp.send();
}
</script>
<div id='ajax1'><b>ID dropdown will be listed here.</b></div>
I am not sure why you declared the variables twice, but I think this may help If you are asking what I think.
function showUser(fo,to)
{
if (fo=="")
{
document.getElementById("show").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var arr=xmlhttp.responseText.split(":||:");//I used this as the delimiter
document.getElementById('show').innerHTML=arr[0];
document.getElementById('show1').innerHTML=arr[1];
}
}
xmlhttp.open("GET","some.php?q="+ fo + "&w=" + to,true);
xmlhttp.send();
}
And the php side is different than normal, you;ll need something like this.
if (!$result=mysqli_query($con,$sql))
{
die('Could not get data: ' . mysqli_error($sql));
}
$test=mysqli_fetch_all($result,MYSQLI_ASSOC);//this was key to fetching the array properly for display
$length=count($test);
$half_length=$length/2;
//echo $half_length."<br />";/used for testing
$test12=array_chunk( $test,$half_length+.5,false);//here use true to preserve keys, worked both ways for me
$test5=$test12[0];
$test6=$test12[1];
while(list($key,$val)=each($test5))
{
echo "<p>".$val[$colunm_name]."<p/><br />";//Here you can put in the tags you want and will list your array in the format you want
}
echo ":||:";//Make sure the delimiter is out of the loop
while(list($key2,$val2)=each($test6) )
{
echo "<p>".$val[$colunm_name]."<p/><br />";//Here you can put in the tags you want
//echo "result_count_".count($test)."_-st<br/>";//used for testing
Took me a while to get this, I hope it helps.

Using javascript and ajax to fill an input field

I have the following javascript which is intended to be used to dynamically fill another input field with the data retrieved via ajax. If I set it to fill a div it works, but changing to an input, it stops working.
My javascript is:
function showCD(str)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('txtHint').value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","script.php?q="+str,true);
xmlhttp.send();
}
Html is:
<input type="text" name="cds" value="" onKeyUp="showCD(this.value)">
<input type="text" name="txtHint" id="txtHint" />
As I say, if i replace the latter input with a div with the id of "txtHint" and alter the javascript to:
document.getElementById('txtHint').innerHTML=xmlhttp.responseText;
it works.
Thanks.

2 functions onchange event at same time separately

So what i'm looking for is a way to trigger 2 function events onchange with my first option, i've looked up a few examples on other sites an neither of them works. But what i want is when this.value is selected, for the function to open 2 separate options via the selection.
So if category is Dogs it does showSub(Dogs) and showSize(Dogs) at the same time and sends to 2 different php page calls, IF thats possible.
//index.php
<select name="category" onChange="showSub(this.value);showSize(this.value)" style="width:200px;">
<option value="">Select Category</option>
Send to php to get actual options.
</select>
//foo.js
function showSub(str)
{
if (str=="") {
document.getElementById("txtSub").innerHTML="";
return;
}
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtSub").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getSub.php?q="+str,true);
xmlhttp.send();
}
function showSize(str)
{
if (str=="") {
document.getElementById("txtSize").innerHTML="";
return;
}
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtSize").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getSize.php?q="+str,true);
xmlhttp.send();
}
//rest of index.php
<div id="txtSub"></div>
<div id="txtSize"></div>
Use var to declare all variables. Your showSub() and showSize() functions both use a variable xmlhttp that is not declared with var, which makes it global - so when you call showSize() it overwrites the xmlhttp object from showSub() (which is why you get the effect mentioned in a comment where "with the current code, the showsize only shows").
So add this line to the start of each function:
var xmlhttp;
And better yet, move the if/else out into a separate function that returns an xmlhttp object rather than repeating that code in both functions:
function getXMLHttp() {
return window.XMLHttpRequest ? new XMLHttpRequest() // newer browsers
: new ActiveXObject("Microsoft.XMLHTTP"); // old IE
}
// and then within your other functions:
var xmlhttp = getXMLHttp();

Categories