I ahave some ajax that is fired when a checkbox is clicked, it essentially sends a query string to a PHP script and then returns the relevant HTML, however, if I select a select it works fine if I then slect another checkbox as well as the previous I get no activity what so ever, not even any errors in firebug, it is very curious, does anyone have any ideas?
//Location AJAX
//var dataObject = new Object();
var selected = new Array();
//alert(selected);
$('#areas input.radio').change(function(){ // will trigger when the checked status changes
var checked = $(this).attr("checked"); // will return "checked" or false I think.
// Do whatever request you like with the checked status
if(checked == true) {
//selected.join('&');
selected = $('input:checked').map(function() {
return $(this).attr('name')+"="+$(this).val();
}).get();
getQuery = selected.join('&')+"&location_submit=Next";
alert(getQuery);
$.ajax({
type:"POST",
url:"/search/location",
data: getQuery,
success:function(data){
//alert(getQuery);
//console.log(data);
$('body.secEmp').html(data);
}
});
} else {
//do something to remove the content here
alert($(this).attr('name'));
}
});
I see you are using the variable checked = $(this).attr("checked"); I think this might be a problem because checked is a standard JS attribute native to JS. You can compare checked normally on an element and see if it is true or false. I would start by changing the name of your variable and move on from there.
The other thing that could be happening is you might be losing your listener which might be caused by your variable selected. You do not need to declare selected outside your listener. Just declare it inside when you set it.
And if THAT doesn't help, providing some markup would help debug this issue because it seems like there is a lot going on here.
Good luck.
I turned out that because my ajax loads in a new page on success the actions were not being put on the elements as they were only being loaded once on DOM ready, I moved the all the script into a function and call that on DOM Ready now and it works great.
Related
If I am here asking it is because we are stuck on something that we do not know how to solve. I must admit, we already searched in StackOverflow and search engines about a solution.. but we didn't manage to implement it / solve the problem.
I am trying to create a JavaScript function that:
detects in my html page all the occurrences of an html tag: <alias>
replaces its content with the result of an Ajax call (sending the
content of the tag to the Ajax.php page) + localStorage management
at the end unwraps it from <alias> tag and leaves the content returned from ajax call
the only problem is that in both cases it skips some iterations.
We have made some researches and it seems that the "problem" is that Ajax is asynchronous, so it does not wait for the response before going on with the process. We even saw that "async: false" is not a good solution.
I leave the part of my script that is interested with some brief descriptions
// includes an icon in the page to display the correct change
function multilingual(msg,i) {
// code
}
// function to make an ajax call or a "cache call" if value is in localStorage for a variable
function sendRequest(o) {
console.log(o.variab+': running sendRequest function');
// check if value for that variable is stored and if stored for more than 1 hour
if(window.localStorage && window.localStorage.getItem(o.variab) && window.localStorage.getItem(o.variab+'_exp') > +new Date - 60*60*1000) {
console.log(o.variab+': value from localStorage');
// replace <alias> content with cached value
var cached = window.localStorage.getItem(o.variab);
elements[o.counter].innerHTML = cached;
// including icon for multilingual post
console.log(o.variab+': calling multilingual function');
multilingual(window.localStorage.getItem(o.variab),o.counter);
} else {
console.log(o.variab+': starting ajax call');
// not stored yet or older than a month
console.log('variable='+o.variab+'&api_key='+o.api_key+'&lang='+o.language);
$.ajax({
type: 'POST',
url: my_ajax_url,
data: 'variable='+o.variab+'&api_key='+o.api_key+'&lang='+o.language,
success: function(msg){
// ajax call, storing new value and expiration + replace <alias> inner html with new value
window.localStorage.setItem(o.variab, msg);
var content = window.localStorage.getItem(o.variab);
window.localStorage.setItem(o.variab+'_exp', +new Date);
console.log(o.variab+': replacement from ajax call');
elements[o.counter].innerHTML = content;
// including icon for multilingual post
console.log(o.variab+': calling multilingual function');
multilingual(msg,o.counter);
},
error: function(msg){
console.warn('an error occured during ajax call');
}
});
}
};
// loop for each <alias> element found
//initial settings
var elements = document.body.getElementsByTagName('alias'),
elem_n = elements.length,
counter = 0;
var i = 0;
for(; i < elem_n;i++) {
var flag = 0;
console.info('var i='+i+' - Now working on '+elements[i].innerHTML);
sendRequest({
variab : elements[i].innerHTML,
api_key : settings.api_key,
language : default_lang,
counter : i
});
$(elements[i]).contents().unwrap().parent();
console.log(elements[i].innerHTML+': wrap removed');
}
I hope that some of you may provide me some valid solutions and/or examples, because we are stuck on this problem :(
From our test, when the value is from cache, the 1st/3rd/5th ... values are replaced correctly
when the value is from ajax the 2nd/4th .. values are replaced
Thanks in advance for your help :)
Your elements array is a live NodeList. When you unwrap things in those <alias> tags, the element disappears from the list. So, you're looking at element 0, and you do the ajax call, and then you get rid of the <alias> tag around the contents. At that instant, element[0] becomes what used to be element[1]. However, your loop increments i, so you skip the new element[0].
There's no reason to use .getElementsByTagName() anyway; you're using jQuery, so use it consistently:
var elements = $("alias");
That'll give you a jQuery object that will (mostly) work like an array, so the rest of your code won't have to change much, if at all.
To solve issues like this in the past, I've done something like the code below, you actually send the target along with the function running the AJAX call, and don't use any global variables because those may change as the for loop runs. Try passing in everything you'll use in the parameters of the function, including the target like I've done:
function loadContent(target, info) {
//ajax call
//on success replace target with new data;
}
$('alias').each(function(){
loadContent($(this), info)
});
I'm struggling with figuring out how to call/execute a function in jQuery. I've done quite a bit of searching and find what looks like it should be the answer, but it doesn't seem to work. I assume it is a scope issue since everything else seems to match examples I've found here, but I'm relatively new to jQuery and can't quite figure it out.
Basically, when the "bookmark" button is clicked, it uses ajax to create an entry in the database, and changes the format of the clicked button. This acts as expected. The trick is this requires someone to be logged in. The actual click of the button adds a #bookmarkme anchor to the url - if they aren't logged in (this is where things start getting tricky for me), the log in window pops up and they are prompted to sign up/log in, and the page reloads to set all the log in variables properly. This also works as expected. Where it breaks down is once the user logs in and the page reloads, I can't get the "bookmarkFunction" to run.
<script type="text/javascript">
var loggedin = <?php echo $loggedin; ?>;
var headerButtonScript = function(){
var bookmarkFunction = $("#bookmark").click(function(){
var directoryName = "<?php echo $directoryName;?>";
if(loggedin == 1 && $("#bookmark").hasClass("headerButton")){
$.ajax({
type: "POST",
url: "../includes/bookmarkProcess.php",
data: {directory: directoryName},
success: function(data, status){
if(data == "success"){
$("#bookmark").switchClass("headerButton", "headerButtonDisabled", 1000, "easeInOutQuart");
$("#bookmark").text("Bookmarked");
}
}
});
}
else{
$("#signInContent").toggleClass('hidden');
$("#signInPopUp").toggleClass('hidden');
}
});
};
var headerButtonsAfterLoad = function(){
var currentAddress = window.location.href;
var hashPosition = currentAddress.indexOf("#");
var targetLocation = currentAddress.substring(hashPosition+1);
if(targetLocation == "bookmarkme"){
if(loggedin==1){
//CALL bookmarkFunction HERE;
//I know I get to this location when expected, because placing an alert("message") gives me the pop up
}
}
};
$(document).ready(headerButtonScript);
$(window).bind('load',"",headerButtonsAfterLoad);
</script>
Based on my research, I have tried the following lines (one line attempted each time rather than all at once, of course) in the excerpt to try to call the function, but no luck yet.
if(targetLocation == "bookmarkme"){
if(loggedin==1){
//CALL bookmarkFunction HERE;
bookmarkFunction();
bookmarkFunction.run();
bookmarkFunction.call();
bookmarkFunction.apply();
}
}
Any help on locating my issue - scope, methods, or otherwise - is greatly appreciated!
"I need the script to take the same action it would when I click on the bookmark button (ID = bookmark) when the page reloads and has the anchor #bookmarkme"
This will do what you want^
$('#bookmarkme').trigger('click');
$("#bookmark").click(). should work.
Remember, calling a jQuery method on a jQuery object returns the original jQuery object. So if you say:
var bookmark=$('#bookmark')
Then bookmark is set to the jQuery object (which contains the element of id=bookmark as a property).
If you attach methods to the object like this:
var bookmark=$('#bookmark').click(function(){console.log('You clicked!')})
Then, yes, the element with id bookmark will now call this event when you click it, but the click method on a jquery object returns the original jquery object. That means bookmark will still be equal to $("#bookmark"), not the function in the click method.
So in conclusion, when you attach an event to a jquery object, like click or hover, it goes into the dom and attaches the event, and then returns the original jquery object. That way you can do things like:
var bookmark=$("#bookmark").click(function(){console.log("you clicked")}).mouseover(function(){console.log("you moused over")})
And you can keep attaching events forever and ever, and bookmark will always be equal to $("#bookmark")
So i have a jQuery script that i should explain it line by line, i already do that and i want to make sure that is correct, so this is my script :
//Here we use the jQuery selector ($) to select the servers_id which is located into
//the delivers_id and we attaches a function to run when a change event occurs
$("#delivers #servers").change(function(){
//Here we look if the servers_id value was changed and the value is different of 0
if($(this).val() != '0') {
//Here we create a new variable sid and we stored the servers_id value in it
var sid = $("#delivers #servers").val();
//Here we use the Ajax $.get to get the sid value and send it by Ajax request then
//we set the data into the o_vmats_id html and empty the vmtas_id
$.get("/deliverability/get_vmtas/" + sid,
function(data) { $('#o_vmtas').html(data); $('#vmtas').html(''); });
}
//Here the else statement, we select the vmtas_id and set the html content like in the code (value=0)
//and empty the o_vmtas_id html content
else { $('#vmtas').html('<option value="0">All Classes</option>');
$('#o_vmtas').html(''); }
});
so please if someone has any remark i will be very appreciative
You're looking for the #servers element twice, no need for that. You can and should cache items that are going to be looked up more than once, so store that element in a var at the very beginning.
Other than that... there's not much to it, other than you wouldn't actually need much jQuery to do this :)
i have a list of dynamically created check boxes. when the state of the check box changes, a function is executed. the function runs perfectly in firefox 3.6 perfectly whether the user clicks the check box, or uses keyboard input to change the check box. in chrome or safari, the function executes fine using the keyboard, but errors out with a mouse click. i cannot seem to find why the code acts differently from a mouse click vs a keyboard entry.
here is what i believe is the pertinent code:
var q_id = $j('label:contains("SCORP Statewide Need ")').attr('for');
console.log(q_id); //writes out answer id a_721
an ajax post will create a list of check boxes:
if(found == true){
output+="<div name='"+q_id+"'><input type='checkbox' name='"+q_id+"' id='"+q_id+"."+i+"' class='check' checked='checked' onChange='saveStateNeed("+q_id+")' value='"+list[i]+"'/>";
}else{
output+="<div name='"+q_id+"'><input type='checkbox' name='"+q_id+"' id='"+q_id+"."+i+"' class='check' onChange='saveStateNeed("+q_id+")' value='"+list[i]+"'/>";
}
output+=" <label name='l_"+q_id+"' for='"+q_id+"."+i+"' id='l_"+q_id+"."+i+"'>"+ list[i] +"</label></div>";
output+="<div class='clearboth'></div><br/>";
$j('##div_'+q_id).append(output);
all this is generated perfectly in all browsers.
the error is in the callback saveStateNeed();
function saveStateNeed(list){
console.log('in saveStateNeed');
console.log(list);// prints out an array of the checkboxes [input#a_721.0.check Non-motorized trails, input#a_721.1.check Sports a...ayfields, input#a_721.2.check Land Acq...projects, input#a_721.3.check Picnicki...cilities, input#a_721.4.check Nature s...wildlife]
// **in safari i get function()** but it still works with keyboard, fails with click
// the next assignment $me fails.
var $me = $j('input [name="'+list+'"]');
var isChecked = $me.context.activeElement.checked;
var $value = $me.context.activeElement.attributes['value'].nodeValue;
console.log($me); out puts the object selected as an expandable firebug object []
console.log($value); outputs label for object: Picnicking/day use facilities
console.log(isChecked); outputs true false
if(isChecked){
}else{
}
$j.ajax({
type: "POST",
url: });
}
this is all kind of convoluted, im just hoping someone knows why i would get a different result from a click then a keyboard entry, when the same code is actually being executed.
i really hope this isnt all too convoluted.
thanks for taking a look at this, and i really appreciate any comments or suggestions you might have.
cheers.
You might have better luck if you attach the checkbox behavior as a delegated event instead of explicit assignment.
It looks like you're using jQuery, so you can do that like so:
$j('input.check').live('change', function(event) {
var jThis = $j(this);
// grab id from checkbox
var ID = jThis.attr('id').split('.')[0];
saveStateNeed(ID, jThis.attr('checked'));
return true;
});
Also: are you certain that the error is in the event handler, and not in the saveStateNeed function?
EDIT: Based on your updates, here's what I've got. First, note the minor change to the function above; now it passes two values. Second, if you want to act on a checkbox being toggled, modify saveStateNeed to accept two values: an ID and a boolean. Like so:
function saveStateNeed(ID, bChecked) {
console.log('checkbox ' + ID + ' is ' + (bChecked) ? 'checked' : 'not checked');
if(bChecked) {
// do something
} else {
// do something else
}
}
I'm trying to create a CMS system based on AJAX using Prototype's library. On a page load, I have HTML, page title and additional Javascript for the page returned via JSON, and I update the HTML on the main area. I also have an event listener that listens for certain ID's to be clicked on.
The listener is working,
var TabMenu = {
selectedTab: 'main',
showTab: function(pid) { alert(pid); alert($(pid));
$(pid).addClassName('selected'); this.selectedTab = pid;
$(this.defaultTab).removeClassName('selected');
}};
After loading, I click on one of the new tabs, and the first "test" alert successfully alerts the element's ID, but the second alert ($(pid)) returns null. I can only surmise that the HTML returned by the AJAX request is not being evaluated and added to the DOM, otherwise it would alert [HTMLDivElement] instead of "null".
Here is the relevant AJAX call:
new Ajax.Request(url, {
onSuccess: function(t) {
data = t.responseText.evalJSON();
Page.update(data.html, data.title, data.js);
Page.destroyLoader();
}
});
And here is the updating function:
update: function(data, title, js) {
document.title = Global.title + title;
if (title != "") { $('HEADING').update(title); }
$('MAIN').update(data);
if (js != "") {
var nuJS = new Element('script', { type: 'text/javascript' }).update(js);
$('MAIN').insert({ top: nuJS });
}
}
Any ideas on how I can get this working?
When is the ajax request triggered? Is it triggered when you click the tab? If so the showTab function is being triggered before data has been inserted into the DOM.
If you have firebug, try using the console to select the html data, after the ajax call has finished, to see what you get. You can also use firebug's html tab to see if the data has been inserted into the DOM.
Also, even though you get the pid parameter that is set to a value, does it refer to a real id that exists in the DOM?
From your code and the comment above.
I think your plan is to load all the tabs after the page loaded immediately.
And hide all of them using the css. Wait until the user click the tab,
Show only the one that is "selected", right?
That's mean you should change:
$('MAIN').update(data);
To something like
$('MAIN').update({after: data});
So it won't overwrite the existed one.
And don't forget to move the code for document.title and eval js into showTab function.
For javascript evaluation you can insert the js into data.html and use this instead:
$('MAIN').innerHTML.evalScripts();