I have this link:
$('.popup-window').click(function (e) {
e.preventDefault();
$.ajax({
...
})
});
which is a .NET LinkButton (a link that call a javascript, not a real href). I want to prevent Default if ajax return some (let say, false). Else, if true, continue with that link handler.
How can I do it?
P.S. I need that e.preventDefault(); at the beginning, else .NET handler will act immediatly.
You can use the __doPostBack() js function to trigger the postback in your AJAX callback.
The only thing is that you need to pass in the id of the control causing the postback, e.g.
__doPostBack('btnPopup', null);
you can see more on this function in this question: How to use __doPostBack()
I think I understand what you're looking for.
Here's my idea on it: use a data attribute on the DOM element to decide weither default event should be prevented or not. Initially, the event is prevented but the ajax has the power to "unlock?" it, then fire it again. It's a little bit of custom work but it may do the trick:
var $popupWindow=$('popup-window');
// initially "tell" the LinkButton to prevent default
$popupWindow.data('prevent-default', 1);
// the click event (initially prevents default)
$popupWindow.click(function(e){
var $this=$(this);
if ($this.data('prevent-default')==0) { // if "unlocked"
// "lock" it again (default isn't prevented)
$this.data('prevent-default', 1);
} else { // if "locked"
// default is prevented
e.preventDefault();
// test if it should be unlocked
$.ajax({
// ...
}).done(function(data){
if (data.length>0 && data.response==false) {
// set the attribute so it shouldn't prevent default
$this.data('prevent-default', 0);
// trigger this click (should let the event fire completely)
$this.trigger('click');
}
});
}
});
UPDATE:
An alternative could be to add a Page Method.
(See: Using jQuery to directly call ASP.NET AJAX page methods)
This would reduce the mechanics to somethink like this:
$('popup-window').click(function(e){
e.preventDefault();
$.ajax({
// ...
}).done(function(data){
if (data.length>0 && data.response==false) {
$.ajax({
type: "POST",
url: "YourPage.aspx/YourMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
}
});
}
});
});
$('.popup-window').click(function (e) {
data = '?sample=1' //serialized data here
callback = function(json){
if(json.returnVar!=true){ //check if returnVar is not true
e.preventDefault(); //prevent redirect if not true
}
};
$.ajax({
type: 'POST',
url: "../ajaxcall.php", //the url to call for ajax here
data: data,
success: callback,
dataType: 'json'
});
});
Try this, let me know if you can't understand the code
Related
So, I have a jQuery AJAX call that gets data from the server (some text, some links).
Inside AJAX success callback function I got a .on that is bind to <a> that load for me next page and get me the text of the clicked link (let's say stackoverflow.com).
The problem starts here because in the newly loaded page I got anchors...
After every click on anchor links I got new .text() value.
$.ajax({
url: url,
type: type,
dataType: dataType,
success: function(data){
$('.container').append(data);
$('.container').on('click', 'a', function(e){
e.preventDefault();
var clickLinkName = $(this).text();
console.log(clickLinkName);
$('.container').load($(this).attr('href'));
});
}
});
I would like to know how to lock clickLinkName variable. OR any other way to save only first hit.
I think this would do the trick:
$.ajax({
url: url,
type: type,
dataType: dataType,
success: function(data) {
$(".container").append(data);
var clickLinkName; // Declared here.
$(".container").on("click", "a", function(e) {
e.preventDefault();
// If not initialized, initialize.
if(!clickLinkName) {
clickLinkName = $(this).text();
}
console.log(clickLinkName);
$(".container").load($(this).attr("href"));
});
}
});
That would save only the first value in the variable clickLinkName. This answers your question, but I'm sure there are better ways of doing this.
I have an ajax function that creates a link that triggers another ajax function. For some reason the second ajax function refuses to go through POST event if I've set type: "POST"
The two functionas are below:
function HandleActivateLink(source) {
var url = source.attr('href');
window.alert(url)
$.ajax({
type: "POST",
url: url,
success: function (server_response) {
window.alert("well done")
}
});
return false;
}
function HandleDeleteLink() {
$('a.delete-link').click(function () {
var url = $(this).attr('href');
var the_link = $(this)
$.ajax({
type: "POST", // GET or POST
url: url, // the file to call
success: function (server_response) {
if (server_response.object_deleted) {
FlashMessage('#form-success', 'Link Deleted <a class="activate-link" href="' + url.replace('delete', 'activate') + '">Undo</a>');
$('a.activate-link').click(function(){
HandleActivateLink($(this));
});
the_link.parent().hide();
} else {
var form_errors = server_response.errors;
alert(form_errors)
}
}
});
return false;
});
}
You'll notice HandleDeleteLink creates a new link on success, and generates a new click event for the created link. It all works butHandleActivateLink sends the request to the server as GET. I've tried using $.post instead with no luck.
Any pointers, much appreciated.
In the second event you do not inform the client to prevent the default behaviour.
One way to do this would be to change:
$('a.activate-link').click(function(){
HandleActivateLink($(this));
});
to:
$('a.activate-link').click(function(){
return HandleActivateLink($(this));
});
(This works because HandleActiveLink already returns false.)
A nicer way to do this is to pass in the event argument to the click function and tell it to preventDefault
$('a.activate-link').click(function(e){
e.preventDefault();
HandleActivateLink($(this));
});
what is your url?
btw You can't send a cross-domain post via javascript.
I have this simple code here, nothing too advanced.
$("input#send").submit(function(event){
event.preventDefault();
$.ajax({
type: 'POST',
url: add.php,
data: data,
success: success,
dataType: dataType
});
});
Whever I click on the "send" button, the event.preventDefault function doesn't work, and the page loads.
Any ideas why?
A form has the submit event, not a button. Plus, an ID should be unique so tag#id can just be #id.
$("#theform").submit(function(event) {
event.preventDefault();
// ...
});
You need to bind to the form's submit event or to the button's click event and call event.preventDefault() if you want to stop the form from submitting:
$('form').bind('submit', function (event) {
event.preventDefault();
});
$('form').find(':submit').bind('click', function (event) {
event.preventDefault();
});
I believe the submit event is for the form element. For an input[type='button'] you might want to use the click event.
Add quotes around 'add.php'
Change the selector in the first line to the id attribute of the form which contains input#send.
The advantage of handling the submit() handler on the form rather than the click handler on the input is that some forms can be submitted by pressing the enter key (when the user is focused on one of the form fields). If you don't have an id attribute, add one or use a different jQuery selector to target the form tag.
$("#myform").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'add.php',
data: data,
success: success,
dataType: dataType
});
return false;
});
Try using return false instead
$("input#send").submit(function(event) {
$.ajax({
type: 'POST',
url: add.php,
data: data,
success: success,
dataType: dataType
});
return false;
});
If you're using preventDefault I assume that means you do NOT want the default submit action. I would just use a different event instead of using .submit. To me, it's not the submit action that you want to intercept, but rather the click that would normally cause the submit.
$('#inputSend').on('click', function(event) {
event.preventDefault();
//the rest
});
If both return false and event.stopPropagation() don't work, try the following method. Using .on() will make the submit function accessible. Once you change the .submit() to .on("submit"..), you can either use return false or e.stopPropagation().
$(document).on("submit", "input#send", function(event) {
event.stopPropagation();
$.ajax({
type: 'POST',
url: add.php,
data: data,
success: success,
dataType: dataType
});
return false; });
I have some jquery that looks like this,
$('.career_select .selectitems').click(function(){
var selectedCareer = $(this).attr('title');
$.ajax({
type: 'POST',
url: '/roadmap/step_two',
data: 'career_choice='+selectedCareer+"&ajax=true&submit_career=Next",
success: function(html){
$('.hfeed').append(html);
$('#grade_choice').SelectCustomizer();
}
});
});
My problem is that if the user keeps clicking then the .hfeed keeps getting data appended to it. How can I limit it so that it can only be clicked once?
Use the one function:
Attach a handler to an event for the elements. The handler is executed at most once per element
If you wanted the element to only be clicked once and then be re-enabled once the request finishes, you could:
A) Keep a state variable that updates if a request is currently in progress and exits at the top of the event if it is.
B) Use one, put your code inside a function, and rebind upon completion of request.
The second option would look like this:
function myClickEvent() {
var selectedCareer = $(this).attr('title');
var that = this;
$.ajax({
type: 'POST',
url: '/roadmap/step_two',
data: 'career_choice='+selectedCareer+"&ajax=true&submit_career=Next",
success: function(html){
$('.hfeed').append(html);
$('#grade_choice').SelectCustomizer();
},
complete: function() {
$(that).one('click', myClickEvent);
}
});
}
$('.career_select .selectitems').one('click', myClickEvent);
You can either use a global variable like
var added = false;
$('.career_select .selectitems').click(function(){
if(!added) {
// previous code here
added = true;
}
});
or use .one("click", function () { ... }) instead of the previous click function to execute the handler at most once per element. See http://api.jquery.com/one/ for more details.
I have the following that fires off when a checkbox is changed.
$(document).ready(function() {
$("#reviewed").change(function(){
if ($('#reviewed:checked').val() !== null) {
$.ajax({
url: "cabinet_reviewed.php?reviewed=yes",
cache: false,
success: function(html){
$("#reviewDate").replaceWith(html);
}
});
} else {
$.ajax({
url: "cabinet_reviewed.php?reviewed=no",
cache: false,
success: function(html){
$("#reviewDate").replaceWith(html);
}
});
}
});
})
This only works once. I'm looking to see when the check box is changed and what the value of it is once changed.
UPDATE:
I've change the code around to the following (based on everyone's comments)
$(document).ready(function() {
$("#reviewed").click(
function() {
var rURL = 'cabinet_reviewed.php?reviewed=';
if ($("#reviewed").is(":checked"))
rURL = rURL + "yes";
else
rURL = rURL + "no";
alert (rURL);
$.ajax({
url: rURL,
cache: false,
success: function(html){
$("#reviewDate").replaceWith(html);
}
});
});
})
The file cabinet_reviewed.php simply echos the value of $_GET['reviewed']
With this updated code the alert shows the correct URL but the second click does not run the .ajax.
Do I need to do something so the .ajax is run again?
Try with != instead of !==
And also this as an alternative:
$('#reviewed').is(':checked')
The below code works consistently in FF 3.5 and IE8:
$("#reviewed").click(
function() {
if ($("#reviewed").is(":checked"))
alert('checked');
else
alert('not checked');
}
);
After your update:
This code...
success: function(html){
$("#reviewDate").replaceWith(html);
}
... is replacing the element with ID=reviewDate in the DOM with the HTML that is returned from the Ajax call, so it is no longer present the second time the Ajax call is made.
Will something simpler like this work for you?
success: function(html){
$("#reviewDate").html(html);
}
There are apparently some bugs with the change() event for checkboxes in IE. Try using the click() event instead and see if it works better.
You normally want to use click event to track changes in checkboxes/radiobuttons. The change event is only fired if the new value differs from the old value. In checkboxes/radiobuttons there's no means of an initial value, only the checked attribute which is often not predefinied, hence the need to click twice before the change event is fired.
In checkboxes/radiobuttons you also don't want to check the value by val(), it's always the same. You rather want to check the checked state using this.checked.
Thus, the following should work:
$(document).ready(function() {
$("#reviewed").click(function() {
if (this.checked) {
// ...
} else {
// ...
}
});
});