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');
}
Related
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);
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.
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.
isn't it possible to execute multiple ajax calls using javascript only and without using Jquery. I tried the below javascript code with two ajax calls but the code is not working when I place the second ajax call
<script type="text/javascript">
var class1;
var class2;
var sec1;
var sec2;
function func()
{
class1 = document.getElementById('selcla');
class2 = class1.options[class1.selectedIndex].value;
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("secdiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getsec.php?q="+class2,true);
xmlhttp.send();
}
function funcsec()
{
sec1 = document.getElementById('selsec');
sec2 = sec1.options[sec1.selectedIndex].value;
alert("selecting class and section details " + class2 + " " + sec2 );
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)
{
alert("successfully received " );
document.getElementById("studiv").innerHTML=xmlhttp.responseText;
}
else
alert("unsuccessful ajax second call ");
}
xmlhttp.open("GET","getstu.php?x="+class2"&y="+sec2,true);
xmlhttp.send();
}
It is, but you need a different "xmlhttp" handler for each request you make.
Setup a new xmlhttp object and make a second request with the new object.
My suggestion is to break out the part with you initializing the xmlhttp object, into a standalone function, and use it to create a few instances of those objects.
However I must advise against such an approach. It is better to use a library for ajax requests.
How can JSON be used to parse xmlhttp.responseText? I can't seem to get textboxes populated using the parsed data. I tried using .value and .innerHTML with the dot notation with b.first and b.second used with json_encode from the loadTextBox.php file (see below), but the textboxes won't populate.
Main page code:
function loadDoc()
{
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
//code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var doc = window.document.createElement("doc");
var a = xmlhttp.responseText;
var b = JSON.parse(a);
document.getElementById("textbox").innerHTML=b.first;
document.getElementById("textbox2").innerHTML=b.second;
}
}
xmlhttp.open("GET","loadTextBox.php?id=4",true);
xmlhttp.send();
}
loadTextBox.php code:
<?php
---Placeholder for correct DB login info---
$result = $mysql->query("SELECT column_one FROM table_one");
while ($row = $result->fetch_object())
{
$queryResult[] = $row->present_tense;
}
$textboxValue = $queryResult[0];
$textboxValue2 = $queryResult[2];
echo json_encode(array('first'=>$textboxValue,'second'=>$textboxValue2));
?>
This is fully tested and works. Use as a starting point to accomplish what you are trying to do:
var url = "YOUR.php"
var ajax = new XMLHttpRequest();
ajax.open("GET", url, true);
ajax.send(null);
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && (ajax.status == 200)) {
console.log("ready")
var Data = JSON.parse(ajax.responseText);
console.log(Data);
console.log(Data.first);
} else {
console.log("not ready yet")
}
}
This assumes your JSON output is properly formatted as you stated:
{"first":"radim","second":"radi"}
I have figured out the underlying problem. Extra tags were being sent because I had unnecessary tags in my DB info file. Those tags were being sent in the responseText with {"first":"radim","second":"radi"}. So the code pertaining to ---Placeholder for correct DB login info--- was wrong. I also changed .innerHTML to .value and now it works as intended.
Main page code updated:
function loadDoc()
{
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var a = JSON.parse(xmlhttp.responseText);
document.getElementById("textbox").value=a.first;
document.getElementById("textbox2").value=a.second;
}
}
xmlhttp.open("GET","loadTextBox.php?id=4",true);
xmlhttp.send();
}