Why isn't this function triggered upon .click? - javascript

We need to load a given function on page load. Then, we should repeat that function execution, each time a given button is clicked. How can we do that?
Here's the code:
$(function showMember() {
$.ajax({ //Perform an asynchronous HTTP (Ajax) request.
success: function(html){
$('#members').append(html);
},
type: 'get',
url: '<?php echo $this->createUrl('member'); ?>', //A string containing the URL to which the request is sent.
data: {index:$('#members div>h3').size()},
cache: false, //if false, it will force requested pages not to be cached by the browser.
dataType: 'html' //The type of data that you're expecting back from the server.
});
});
$('.addMember').click(showMember);
showMember doesn't trigger uppon click.
Can anyone please explain with detail, why is that ?

that is because your created function is in limited scope $(function ..)....
you can simply do
$(function(){ //document.ready function
showMember(); //call showmember when document is ready
$('.addMember').click(showMember); //call same function when clicked
});
function showMember() {
$.ajax({ //Perform an asynchronous HTTP (Ajax) request.
success: function(html){
$('#members').append(html);
},
type: 'get',
url: '<?php echo $this->createUrl('member'); ?>', //A string containing the URL to which the request is sent.
data: {index:$('#members div>h3').size()},
cache: false, //if false, it will force requested pages not to be cached by the browser.
dataType: 'html' //The type of data that you're expecting back from the server.
});
}

As an addendum to bipen's answer: the reason your code does not work is because you don't seem to get what $ is.
Since you have tagged your question with jQuery, I assume that you are using it. When you include the jQuery library in your code it gives you a function called jQuery. This function is aliased as $. That is, $ is the same as jQuery.
When you call a function in javascript you can pass in arguments:
parseInt('1234');
At the top of your code you are calling $, and passing a function definition as an argument. So
$(function showMember()...
is the same as
jQuery(function showMember()...
That is syntactically correct, but limits the scope of the function to the list of arguments you have passed to the $ function. Once that call is complete the function showMember will no longer exist.
This is why you code does not work.

Here are few points:-
You don't need to call $(function showMember() like this.
You need to call it like function showMember() simply.
Also, you need to call the click function inside the DOM ready method.
Just to make sure that your click event is fired when the DOM is fully loaded, as follows:
$(document).ready(function () {
$('.addMember').click(showMember);
});
OR
$(function () {
$('.addMember').click(showMember);
});

When you pass custom function inside event handler (i.e click, change etc ) then you need to create function as normal, You do not need wrap function within $();
And also do not forget to wrap code inside $(document).ready();
function showMember()
{
$.ajax(
{
success: function(html)
{
$('#members').append(html);
},
type: 'get',
url: '<?php echo $this->createUrl('member'); ?>',
data: {index:$('#members div>h3').size()},
cache: false,
dataType: 'html'
});
}
$(document).ready(function(){
$('.addMember').click(showMember);
});

You need to use ready function when using jQuery
$(document).ready(function(){
$('.addMember').click({});
});

Try this:
$('.addMember').click(function(){
showMember();
});
function showMember(){
$.ajax({ //Perform an asynchronous HTTP (Ajax) request.
success: function(html){
$('#members').append(html);
},
type: 'get',
url: '<?php echo $this->createUrl('member'); ?>', //A string containing the URL to which the request is sent.
data: {index:$('#members div>h3').size()},
cache: false, //if false, it will force requested pages not to be cached by the browser.
dataType: 'html' //The type of data that you're expecting back from the server.
});
}

you may have this lement bind dynamically,
so I think you need to bind it after all binding is complete :
$('.addMember').live('click', function(){
showMember(); return false;
});

Related

Using jQuery event on ajax html response

I'm want to use jcarousel on an ajax html response. Here is how i use jcarousel on elements loaded with the DOM.
jQuery(document).ready(function() {
jQuery('#mycarousel-2').jcarousel({ wrap: 'circular' });
});
Now when i use ajax, the above code doesn't work on the returned html. What do i have to do to refire the jcarousel script?
var data = {
action: 'get_thumbnails',
id: id
};
jQuery.post(ajaxurl, data, function(response) {
});
call it inside ajax success callback to initate jcarousel again for dynamically loaded element
jQuery.post(ajaxurl, data, function(response) {
//success callback
jQuery('#mycarousel-2').jcarousel({wrap:'circular'});
});
Might not be the proper approach, but you may use jQuery's event delegation, I think it can be useful, if not in a straight way, then a tricky way :)
Hey buddy i believe that the right code for ajax is this
$.ajax(
{
type: "POST", /// your URL
url: pageurl + "/testajaxfunc1", /// backend function
data: '{"testval":"' + $('#testField').val() + '"}', /// data fields
contentType: "application/json;charset=utf-8", // content type
dataType: "json", // datatype
success: OnSuccessReturnValues, // function that it would initiate on success
error: OnError // function that it would initiate on Error
}
);
hope this help

Accessing DOM object after AJAX call?

I have a typical AJAX call that appends some HTML to the current page. I want to be able to access the newly inserted HTML with typical jQuery selectors.
Here's what I'd like to be able to do...
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
}
});
$('#new_div').show();
#new_div would be some HTML element from the data I retrieved. I don't necessarily want to attach events to the new elements (like click), so using something like .load() or .on() doesn't work here (as far as I know).
I tried setting the $.ajax() call to a variable: var new_div = $.ajax(...) but that didn't get me anywhere.
If you would like to manipulate the new content immediately after (or even before) inserting it to the DOM, you can put that in the AJAX success callback too:
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
$('#new_div').show();
}
});
On the other hand, if you want to bind handlers to content that will be added to the page via ajax, jQuery does that like this:
$(document).on('click', '#new_div', function(){
alert("This function is bound to all #new_div's click events, even if they are added to the DOM via ajax later!")
});
If you want to decouple your code from the callback:
functionWithALotOfStuffToDo = function(data){
// do stuff here
}
$.ajax({
url: url,
success: functionWithALotOfStuffToDo
});
how about:
$.ajax({
url: url,
success: function(data) {
$('body').append(data).find('#new_div').show();
}
});
Assuming the data being returned is something like <div id='new_div' /> then try something such as
var newDiv = null;
$.ajax({
url: url,
success: function(data) {
newDiv = $(data).appendTo($('body'));
}
});
This will add the <div /> to the body of your page, and assign the jQuery element to the variable newDiv which can then be accessed again at a later stage.
However, if you access newDiv before success has been returned, it will be null or the previous value, if it was assigned previously.
Actually this sort of things can be solved by following way:
(I know it is similar to others, but a little bit more clear)
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
afterHtmlAppendCallback();
}
});
function afterHtmlAppendCallback()
{
$('#new_div').show();
}
I think it's ajax async cause the problem you mention.
In jQuery ajax funciton API says:
Perform an asynchronous HTTP (Ajax) request.
If you want to access the data from ajax right after request
you should put you code in the ajax.success function like:
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
$('#new_div').show();
}
});
Or turn the async setting into false
$.ajax({
url: url,
async:false,
success: function(data) {
$('body').append(data);
}
});
$('#new_div').show();
that will make sure the $('#new_div') selector gets the object
I have the same issue and find a method that was great.
If you have the jQuery functions in a file for example library_jquery.js, just load that file again in the success.
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
//LOAD THE SCRIPT FILE AGAIN
var path_script_file="libray_jquery.js";
$.getScript(path_script_file);
}
});

Ajax working on pageload but not on button click

I have an ajax query that's working if I call it from onpageload but not if I call it from a button click. Any reason why?
Edit: I've added the events as requested, please be aware I have debugged this and it is getting to the AJAX but just silently skipping it. It will call a failure function if I add one.
function detailsQuery(crn, semester, year, questionId, clickedButton)
{
$.ajax({
url: somebigurlwithnocallback (same domain),
type: "GET",
dataType: "json",
success: function (data) {alert(data)}});
}
-
$(function() {
$(document).delegate(".button", "click", function(){detailsQuery(CRN,Semester,Year,QuestionID, this);});
});
window.onload=(function() {detailsQuery(CRN,Semester,Year,QuestionID, this);});
Did you attempt to check if the click event was even working ? Try this code:
$(".button").live("click", function(){
function detailsQuery(crn, semester, year, questionId, clickedButton)
{
$.ajax({
url: somebigurlwithnocallback (same domain),
type: "GET",
dataType: "json",
success: function (data) {alert(data)}
});
});
});
This appears to be an issue with Google Chrome. If an HTML file is modified and only refreshed (even with ctrl+f5) Chrome does not always process the modified AJAX call properly. I don't have access to server side code so I can't see what's going on there, being a 'GET' not much can be going on. I can only see that it returns 'error'. Closing chrome and re-opening resolves the issue. Why it only happens when the AJAX occurs on a button click is beyond me.
Do this:
Change
$(function() {
$(document).delegate(".button", "click", function(){detailsQuery(CRN,Semester,Year,QuestionID, this);});
});
to
$(document).ready(function(){
$(".button").bind({"click": function(){
function(){detailsQuery(CRN,Semester,Year,QuestionID, this);}
}
});
});
That should resolve the issue.
Hope the explanation is clear and this helps.

Loading XML into JS variable with jQuery without JS alert

I know questions about loading XML into a JS variable have been posted here many times, but I didn't find a solution that would work. In my script I declare a variable before an ajax request, and then add the result to the variable. This works only if I add alert to the script:
var myDB;
$.ajax({
type: 'GET',
url: 'db.xml',
dataType: 'xml',
success: function (xml){
myDB = xml;
}
});
alert(myDB); //returns: undefined
$(myDB).find('item').each(function (){
var question = $(this).find('question').text();
alert(question);
});
The above code works only with the alert. When I delete the alert, the code doesn't work. How can I make this work without the alert?
You need to add your code to success handler for doing that:
var myDB;
$.ajax({
type: 'GET',
url: 'db.xml',
dataType: 'xml',
success: function (xml){
$(myDB).find('item').each(function (){
var question = $(this).find('question').text();
});
}
});
An ajax request is asynchronous. That means, the function you gave in the success option is excuted somwhen later.
After you've started the request, you're variable is still empty. Only if you wait long enough to confirm the blocking alert, the variable will have been loaded.
You will need to add the iteration to the success function, where the xml data is certainly available.

Call javascript function from jquery success

I'm having an issue in the success callback of my ajax function. On success of the ajax function I want to call a javascript function that is defined in an external file that is included in the header. However the javascript function never gets called. Is there something I am doing wrong here?
My JQuery looks like this:
$(document).ready(function() {
$.ajax({
type: 'get',
url: 'lib/ajaxDB.php',
data: 'ajax=1&action=locations&uid=<?php echo $uid; ?>&token=<?php echo $admin->getToken(); ?>',
success: function(data) {
addUserLocations(data); // call function in gmaps.js
}
});
...
...
Just make sure that your external file is loaded first.

Categories