How to call a function in javascript? - javascript

I want to call a function every time my update was successful. The update is working my only concern is the alert pop-up every successful update.
$.post(
{
url: 'update_question.php',
data:
{
id: id,
new_question: newText,
},
success: function()
{
that.replaceWith("<section>"+newText+"</section>");
if(text != newText)
{
popup();
}
}
});
var popup = function () {
$(document).ready (function(){
$("#myWish").click(function showAlert() {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
});
});
};

var popup = function () {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
};
On the first update, pop-up showed but it doesn't show on the 2nd update

I think it'll solve your issue
$.post(
{
url: 'update_question.php',
data:
{
id: id,
new_question: newText,
},
success: function()
{
that.replaceWith("<section>"+newText+"</section>");
if(text != newText){
popup();
}
}
});
function popup() {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
};

The $(document).ready jquery function waits until the DOM is loaded into your browser before it executes the javascript code contained within it's function scope {}.
So remove $(document).ready from your code.
Also note that single page applications only need to list $(document).ready once and all the listener events you setup are defined within it's body.
So you should have it listed somewhere at least once and then you define all your initial event listeners within its body.

Related

Unbind jquery in document ready conflict when used in two functions

I have two pages with posts and reviews. The functions for the reply buttons are similar and both using unbind function in document ready event. Somehow, just one function will work even if they are accessing different classes. They both work when one is commented out. I appreciate any help and ideas. Thank you!
//Replies Posts
$(document).ready(function () {
$(document).unbind().on("click", ".btnReplySubmit", function() {
if (!$.trim($(this).closest(".myRepliesForm").find(".textareaReply").val())) {
alert("Empty Content");
}
else {
$.ajax({
url: "/Replies/Create/",
type: "post",
cache: false,
data: $(this).closest(".myRepliesForm").serialize(),
success: function() {
$(".reloadComments").load(location.href + " .reloadComments");
$(".reloadComments").show("slow");
}
});
$(this).closest(".myRepliesForm").find(".textareaReply").val("");
}
return false;
});
});
//Reply Review
$(document).ready(function () {
$(document).unbind().on("click", ".btnReplySubmitReview", function () {
if (!$.trim($(this).closest(".myRepliesFormReview").find(".textareaReplyReview").val())) {
alert("Empty Content");
}
else {
$.ajax({
url: "/ReviewReplies/Create/",
type: "post",
cache: false,
data: $(this).closest(".myRepliesFormReview").serialize(),
success: function () {
$(".reloadCommentsReview").load(location.href + " .reloadCommentsReview");
$(".reloadCommentsReview").show("slow");
}
});
$(this).closest(".myRepliesFormReview").find(".textareaReplyReview").val("");
}
return false;
});
});
Well if you use unbind on both event handlers, one of the functions is going to be inevitably unbound. You also do not need two ready calls as one is enough and finally, you can chain your event handler binding as follows :
$(document).ready(function () {
$(document).unbind()
.on("click", ".btnReplySubmit", function() {
if (!$.trim($(this).closest(".myRepliesForm").find(".textareaReply").val())) {
// ...
}
else {
// ...
}
return false;
})
.on("click", ".btnReplySubmitReview", function () {
if (!$.trim($(this).closest(".myRepliesFormReview").find(".textareaReplyReview").val())) {
// ...
}
else {
// ...
}
return false;
});
});
Because unbind will clear all previous bindings.
But.. why complicating things with bind/unbind on document, you could just do a click listener on both buttons :
$(document).ready(function () {
$('.btnReplySubmit').click(function(){
// alert(1);
});
$('.btnReplySubmitReview').click(function(){
// alert(2);
})
});
the main issue I see here is that you are unbinding events attached to $(document). also, according to jquery's api, you shouldn't be using unbind anymore as it is already deprecated.
instead, you should structure your code like so
$(document).ready(function() {
$('. btnReplySubmit').click(function() {
// your code here
})
$('. btnReplySubmitReview').click(function() {
// your code here
})
})
this makes your event declarations much clearer and much easier to read
All the answers are correct. I may just add that the selector in .on(events [, selector] [,data], handler) method is the event trigger, but event is bound to document in your case.

Losing scope in jQuery AJAX Lightbox

My lightbox opens and the new content is displayed within it.
But the script doesn't seem to add the event listener to the links in the generated content. Thus nothing happens but a new pageload.
var lightbox = (function() {
var init = function() {
$('footer').append("<div id='lightbox'><div id='close'>x</div></div>");
$('#close').click(function() {
$('#lightbox').hide();
$('#lightbox').children(':not(#close)').remove();
});
ajax();
};
var ajax = function() {
$('.ajax a').add('#lightbox a').click(function(e) {
e.preventDefault();
$('#lightbox').children(':not(#close)').remove();
$.ajax({
url: $(this).attr('href'),
success: function(result) {
$('#lightbox').fadeIn(300).append(result);
}});
});
};
return {
init:init
}
})();
You don't actually invoke init which is where your close handler is bound. init is a local variable which is never returned from your IIFE, so obviously it's not being invoked from outside this function.
The answer is to invoke init. As it stands, your lightbox function doesn't do anything except for declare (and then immediately discard) two variables named init and ajax.

reinit function after ajax

I'm trying to rewrite some script. This script takes some data from data attributes and rebuild block with them. All was alright, but I need to do it via AJAX. Here my modified script:
(function($){
jQuery.fn.someItem = function()
{
var make = function() {
var _$this = $(this);
var $thumb = _$this.find('.thumb');
function init()
{
$thumb.on('click', function()
{
if (!$(this).hasClass('active')) setNewActiveItem($(this));
return false;
});
}
function setNewActiveItem($newItem)
{
$.ajax({
url: '/ajax-item?id=' + $newItem.data('id'),
type: 'GET',
success: function(response)
{
_$this.replaceWith(response);
**init();**
}
});
}
init();
};
return this.each(make);
};
})(jQuery);
All working fine, but after Ajax call and block replaced, I can't apply ajax-call in modified block again. I guess that I need to reinit "init()" function after "replaceWith()", but how to do it? Thank you for help.
You need to use a delegated event handler in the init() when attaching your click event to the .thumb elements. Try this:
var make = function() {
var _$this = $(this);
function init() {
_$this.on('click', '.thumb', function() {
if (!$(this).hasClass('active'))
setNewActiveItem($(this));
return false;
});
}
function setNewActiveItem($newItem) {
$.ajax({
url: '/ajax-item?id=' + $newItem.data('id'),
type: 'GET',
success: function(response) {
_$this.replaceWith(response);
}
});
}
init();
};
This works by assigning the click handler to the parent element and inspecting the click event as it bubbles up the DOM. It means that you can append any .thumb element at any time and not have to re-assign any new click handlers as the one defined on the parent will catch all.

Button click pass argument to callback

I have this code , very simple , not working :
$(function() {
$(document).on('click', '#NetworkSearch', NetworkMarketSearching("NETWORK"));
$(document).on('click', '#MarketSearch', NetworkMarketSearching("MARKET"));
$(document).on('click', '#CableSearch', NetworkMarketSearching("CABLE"));
});
you can see - I am very simply using .on() to make NetworkMarketSearching() fire from a click, here is the function. This function works just fine on its own if called from the console.
function NetworkMarketSearching(types) {
var name, searchType;
if (types == 'NETWORK') { name = $('#NetworkName').val(); searchType = 0; }
else if (types == 'MARKET') { name = $('#MarketName').val(); searchType = 1; }
else if (types == 'CABLE') {name = $('#CableName').val();searchType = 2;}
$.ajax({
type: 'POST',
url: '/Talent_/Common/NetworkMarketSearch',
dataType: 'json',
data: { 'name': name, 'searchType': searchType },
success: function(data) {
}
});
}
The error is 'undefined is not a function' it repeatedly happens when putting NetworkMarketSearching('NETWORK') in the line of .on('click', ...
try this:
$(function() {
$(document).on('click', '#NetworkSearch', function() { NetworkMarketSearching("NETWORK"); });
$(document).on('click', '#MarketSearch', function() { NetworkMarketSearching("MARKET"); });
$(document).on('click', '#CableSearch', function() { NetworkMarketSearching("CABLE"); });
});
The click method doessnt support the string parameter, it expects the event object parameter.
This NetworkMarketSearching("NETWORK") calls the function immediately and attempts to assign its return result (which is undefined) as the callback.
You can use the data argument to pass information to your function calls:
$(function() {
$(document).on('click', '#NetworkSearch', { types: 'NETWORK' }, NetworkMarketSearching);
$(document).on('click', '#MarketSearch', { types: 'MARKET' }, NetworkMarketSearching);
$(document).on('click', '#CableSearch', { types: 'CABLE' }, NetworkMarketSearching);
});
Then the function definition would be:
function NetworkMarketSearching(event) {
and, within the function, the types would be referenced as
event.data.types
This is the way the jQuery docs specify passing arguments to the callback, but it can be done also with an inline anonymous function. That is to say, like this:
$(function() {
$(document).on('click', '#NetworkSearch', function () {
NetworkMarketSearching('NETWORK');
});
$(document).on('click', '#MarketSearch', function () {
NetworkMarketSearching('MARKET');
});
$(document).on('click', '#CableSearch', function () {
NetworkMarketSearching('CABLE');
});
});
Are you sure the function exists at the moment you call it?
Try go simple, use this sample of jquery site (http://api.jquery.com/on/):
function notify() {
alert( "clicked" );
}
$( "button" ).on( "click", notify );
then you pass a parameter, if it works you move to your code.

Binding two JQuery and ajax functions

I have the follwoing JQuery/AJAX code:
<script>
$('.warning-dialog').click(function () {
alert($(this).data("id"));
});
$(function () {
//twitter bootstrap script
$("button#delete").click(function () {
$.ajax({
type: "GET",
url: "deleteArticleType.php",
data: { 'typeID': $('.warning-dialog').data("id") },
success: function (msg) {
$("#thanks").html(msg)
$("#form-content").modal('hide');
},
error: function () {
alert("failure");
}
});
});
});
</script>
The first function gets the data-id of a button . The second function calls a PHP page and with the method GET should get the value from the first function.
I tried the code above but it didn't work.
My question is why and how can I fix it?
If these are two separate events, disconnected in time and you want to store the value from the first click and then use it in the second click, then you will have to store it somewhere. There are several options, the simplest being a variable.
$(function () {
var lastClickId;
$('.warning-dialog').click(function () {
lastClickId = $(this).data("id");
});
//twitter bootstrap script
// FIXME: you need to add logic here for what to do if lastClickId isn't set yet
// or create a default behavior in that case
$("button#delete").click(function () {
$.ajax({
type: "GET",
url: "deleteArticleType.php",
data: { 'typeID': lastClickId },
success: function (msg) {
$("#thanks").html(msg)
$("#form-content").modal('hide');
},
error: function () {
alert("failure");
}
});
});
});
Since it looks like you are requiring the first click to happen before the second click can have something to operate on, then you should probably either modify the UI to use different types of controls or you will need to add some error handling if the user doesn't click in the right order.
Actually it should have worked using $('.warning-dialog').data("id")
If your page contains only a single class warning-dialog, you approach will be worked. It seems you're referring this class to many elements.

Categories

Resources