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.
Related
Ajax is not working I have to reload the page to make it work. Because of ajax was not reloading i used location.reload but I don't want this so please anyone can help me out how to make ajax function work. Its removing data but I need to refresh the page to see
$(document).ready(function() {
$('.headertrash').click(function(e){
e.preventDefault();
var trashcartid = this.id;
var splittrash = trashcartid.split('-');
var cartdelid = splittrash[1];
//Ajax Request
$.ajax({
url: 'delusing.php',
type: 'POST',
data: { id:cartdelid },
success: function(response){
// Remove row from HTML Table
$(this).closest('li').fadeOut(300,function(){
$(this).closest('li').remove();
});
//I uses location.reload as alternative
// location.reload();
}});
e.preventDefault();
});
I am going to assume that your request is working and returns success.
From your code and question I am deducing that the actual issue is not with ajax not working but with the li not fading and disappearing.
The issue you are experiencing is due to the this you are using, the way you are using this it means the ajax request, but your intent is to get the element associated with $('.headertrash') to fix your issue:
$(document).ready(function() {
$('.headertrash').click(function(e){
e.preventDefault();
var trashcartid = this.id;
var splittrash = trashcartid.split('-');
var cartdelid = splittrash[1];
var clickedElement = $(this);
//Ajax Request
$.ajax({
url: 'delusing.php',
type: 'POST',
data: { id:cartdelid },
success: function(response) {
// Remove row from HTML Table
clickedElement.closest('li').fadeOut(300,function() {
clickedElement.closest('li').remove();
});
}
});
});
});
See: Ajax (this) not working for more details
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 am trying to make a ajax call back to a Drupal 7. The problem I am encountering is that the url I want to use to make the callback is appended to the current page the user is viewing. I am not sure why this is happening and am wondering if some can point out my error for me. Here is the javascript code I am using to make the call:
(function($) {
function todaysHours(context) {
var callbackFunction = window.location.host +'/' + Drupal.settings.library_hours.callbackFunction,
content = $("#todays-hours").find(".block");
nIntervId = setInterval(checkTime, 300000);
function checkTime() {
request = $.ajax({
url: callbackFunction,
dataType: "json",
type: "GET"
});
request.done(function( result ) {
content.text(result[0].data);
})
}
}
Drupal.behaviors.library_hours = {
attach: function(context) {
todaysHours(context);
}
}
})(jQuery);
The url I expect to use is http://mydomain.com/ajax/get-time but what is actually being used in the ajax call is http://mydomain.com/current-page/mydomain.com/ajax/get-time even though the callbackfunction variable is set to mydomain.com/ajax/get-time.
Why is this happening and how do I fix it? Thanks.
Problem:
Protocol is not defined in the url
Solution:
update the following part in the code
(function($) {
function todaysHours(context) {
var callbackFunction = '//'+window.location.host +'/' + Drupal.settings.library_hours.callbackFunction,
// rest code
})(jQuery);
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
I have a link 'hrefs="javascript:callFunc()">' that invokes the function 'callFunc()';
function callFunc(){
$.ajax({
type: "POST",
url: "call.php",
data: "i="+i+add,
success: function(msg){
$('#content').html(msg);
}
});
}
The issue: When the user click's that link 4 times, the callFunc is going to invoke 4 times, sending 4* the post via ajax.
Anyway to lock this down?
*Beaware that the link could be through out the page too; And there could be similar functions.
What about:
window.funcRunning = false;
function callFunc(){
if(window.funcRunning == false) {
window.funcRunning = true;
$.ajax({
type: "POST",
url: "call.php",
data: "i="+i+add,
success: function(msg){
$('#content').html(msg);
window.funcRunning = false;
}
});
}
}
Have the event handler disable the link, or ever better replace it with "Please wait…" or other appropriate feedback message.