Hi I have a button group which when the selected button changes an ajax call should be triggered.
<div class="btn-group" id="graphSelection">
<button type="button" class="btn disabled btn-info" id="post" onclick="graphSelection(this.id)">Posts</button>
<button type="button" class="btn" id="comment" onclick="graphSelection(this.id)">Comments</button>
<button type="button" class="btn" id="interaction" onclick="graphSelection(this.id)">All Interaction</button>
</div>
and then the javascript/jquery and ajax
var postData;
var commentData;
var interactionData;
function graphSelection(clickedID) {
if(!$('#' + clickedID).hasClass('disabled')) {
$('#graphSelection').find('button.disabled').removeClass('disabled btn-info');
$('#' + clickedID).addClass('disabled btn-info');
loadGraphs(clickedID);
}
}
This first javascript just changes the css of the individual buttons and then calls load graph on the next javascript function which contains the ajax.
function loadGraphs(type) {
if ((type == "post" && !postData) || (type == "comment" && !commentData) || (type == "interaction" && !interactionData)) {
$.ajax({
url : 'parts/' + type + '_graph.php',
cache: false,
type : 'POST',
data : data,
dataType : 'json',
beforeSend: function() {
$("#report-loading").fadeIn(500);
},
success : function (jsonData) {
alert(type);
if (type == "post")
postData = jsonData;
else if (type == "comment")
commentData = jsonData;
else if (type == "interaction")
interactionData = jsonData;
drawChart(jsonData);
$("#report-loading").fadeOut(500);
},
error : function () {
$("#report-loading").fadeOut(500);
alert("error");
}
})
}
else if (type == "post") {
drawChart(postData);
}
else if (type == "comment") {
drawChart(commentData);
}
else if (type == "interaction") {
drawChart(interactionData);
}
}
In this one I check the type of the graph I am suppose to load and then check if I have loaded the data before. If not then the ajax is triggered and retrieves the required data. When the page is done loading the ajax is automatically called once with a type of post, however if I use the buttons in the button group it gets to the loadGraphs function but the ajax seems to be “skipped”
any help would be greatful thanks.
Update 1
var postData;
var commentData;
var interactionData;
are defined at the top inside the same script tags as the other javascript functions.
it is because of the variables used. Change the data variables
post,commentandinterationtopostData,commentDataandinteractionDatarespectively.Then change the
ifcondition toAnd change the ajax callback also.
The variable
postis referring to thebutton id="post"element, other variables also the same, I think it is because of theidof the elements are exposed globaly but do not know why.You also need to define the global variables as
Problem Demo : Fiddle
Solution Demo: Fiddle.