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);
Related
I have comment system using live ajax php, and also include for vote system on that comment
Logic: when i post new comment, system will call ajax function with method post, and display response in above of textarea for comment, that response is include vote system (a class="with_unique_id"), but when i click that vote, it wont calling ajax function (nothing happend in browser console), whereas in current comment that displaying in above of new comment, it working fine.
This is my ajax code for vote
jQuery(document).ready(function($){
$(".voteMe").click(function() {
var voteId = this.id;
var upOrDown = voteId.split('_');
$.ajax({
type: "post",
url: "<?php echo base_url('blog/likepost');?>/"+upOrDown[0],
cache: false,
data:'voteId='+upOrDown[0] + '&upOrDown=' +upOrDown[1],
success: function(response){
try{
if(response=='true'){
var newValue = parseInt($("#"+voteId+'_result').text()) + 1;
$("#"+voteId+'_result').html(newValue);
document.getElementById('likeStatus_'+upOrDown[0]).innerHTML = 'Success';
$("#likeStatus_"+upOrDown[0]).show();
setTimeout(function() { $("#likeStatus_"+upOrDown[0]).hide(); }, 5000);
}else{
$("#likeStatus_"+upOrDown[0]).show();
document.getElementById('likeStatus_'+upOrDown[0]).innerHTML = 'Liked';
setTimeout(function() { $("#likeStatus_"+upOrDown[0]).hide(); }, 5000);
}
}catch(err) {
alert(err.message);
}
},
error: function(){
alert('Error while request..');
}
});
});
});
It took me a while to read your code, but I guess this is the root cause:
if(response=='true'){
var newValue = parseInt($("#"+voteId+'_result').text()) + 1;
$("#"+voteId+'_result').html(newValue);
document.getElementById('likeStatus_'+upOrDown[0]).innerHTML = 'Success';
$("#likeStatus_"+upOrDown[0]).show();
setTimeout(function() { $("#likeStatus_"+upOrDown[0]).hide(); }, 5000);
}
This line here:
$("#"+voteId+'_result').html(newValue);
That become the link you want to click again. Right?
If that is so, then you need to re-assign the event handler.
By replacing the DOM element, you have also removed the assigned event handler
PS: You code is very hard to read. It will be nightmare for you to maintain it.
i have fixed my code with adding same ajax code function in response of current ajax with different id.
thankyou
I have a following javascript function mixed with MVC controller actions calls:
var loadPartialChapterAfterAnswer = function () {
$.ajax({
url: '#Url.Action("IsAuthenticated", "Story")',
type: "POST",
success: function(data) {
var isAuthenticated = data;
if (isAuthenticated) {
if ('#Model.IsPersonality' == 'True') {
loadPartialChapter();
} else {
$("#chapterContainer").load('#Url.Action("GetNextQuestion", "Story")' + '?storyId=' + '#Model.Id', function () {
selectedCounter = 0;
showOnlyOneQuestion();
});
}
} else {
window.location.href = '#Url.Action("RedirectToHomeRoute", "Home")';
}
},
error: function() {
alert("Error");
}
});
};
Every time I select one checkbox on my page(view) this function is called. Code works great in all browsers except in IE. In IE the ajax url #Url.Action("IsAuthenticated", "Story") is called OK every time, but the other controller action '#Url.Action("GetNextQuestion", "Story")' + '?storyId=' + '#Model.Id' is called only when the IE's browser debugger is turned on. When IE's debugger window is off this second MVC action is never called.
Any help is highly appreciated!
SOLUTION
I added at the beginning of my page this code:
<script>
$.ajaxSetup({
cache: false
});
</script>
and now it works! Thanks all for your effort.
I read something about IE having issues with JQuery load function
Try to replace it with regular $.ajax with cache: false option hopefully it will resolve the issue.
Check this topic
Add controller to this: #Url.Action("GetNextQuestion")'
Without controller specified it place controller which return view last.
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 want to set timeout after 2 seconds loading data. I am new in ajax so please clarify through my code...because i have already see many (set time out on ajax) answer but every one do through $.ajax().
how I can do through .load() ? It is possible or not ?
My AJAX code 1:
// Start of our new ajax code
if (!url) {
url = jQuery('#product_addtocart_form').attr('action');
}
url = url.replace("checkout/cart","ajax/index"); // New Code
var data = jQuery('#product_addtocart_form').serialize();
data += '&isAjax=1';
jQuery('#ajax_loader').show();
try {
jQuery.ajax( {
url : url,
dataType : 'json',
type : 'post',
data : data,
success : function(data) {
jQuery('#ajax_loader').hide();
parent.setAjaxData(data,true);
}
});
jQuery("#productOptions").modal('hide');
} catch (e) {
//alert(e);
}
// End of our new ajax code
2:
// AJAX product options modal
$('.optionsTrigger').on('click', function() {
var target, url;
target = $(this).attr('data-target');
url = $(this).attr('href');
$(target).load(url, function(){
$(target).modal({
show: true
});
});
});
$('#productOptions').on('hidden', function() {
$('#productOptions').html('<img src="<?php echo $this->getSkinUrl("img/loading.gif"); ?>" id="optionsLoading" />');
window.setTimeout("Tick()", 2000);
function Tick()
{
}
});
jQuery has the ajaxSetup() method available. You can set all options to the normal ajax() method there, including the timeout option. The settings set there should also be available when you call your AJAX request via load().
First, wrap your head around the fact that Ajax is asynchronous (like setTimeout) - the callbacks are called somewhen in the future.
How to timeout? You could use
var request = jQuery.ajax(…);
setTimeout(function() {
request.abort();
}, 2000);
request.done(function callback(){ … });
But it's much simpler than that, jQuery already has a timeout parameter for it's ajax() option object.
However, this is not possible using load - here not the jqXHR object is returned, but the current jQuery DOM-selection. Either, you have to globally configure ajax, or you don't use load and build the method yourself - it's not that hard, see source
I want a basic spinner or processing animation while my AJAX POST is processing. I'm using JQuery and Python. I looked at the documentation but can't figure out exactly where to put the ajaxStart and ajaxStop functions.
Here is my js:
<script type="text/javascript">
$(function() {
$('.error').hide();
$("#checkin-button").click(function() {
var mid = $("input#mid").val();
var message = $("textarea#message").val();
var facebook = $('input#facebook').is(':checked');
var name = $("input#name").val();
var bgg_id = $("input#bgg-id").val();
var thumbnail = $("input#thumbnail").val();
var dataString = 'mid='+mid+'&message='+message+'&facebook='+facebook+'&name='+name+'&bgg_id='+bgg_id+'&thumbnail='+thumbnail;
$.ajax({
type: "POST",
url: "/game-checkin",
data: dataString,
success: function(badges) {
$('#checkin-form').html("<div id='message'></div><div id='badges'></div>");
$('#message').html("<h2><img class=\"check-mark\" src=\"/static/images/check-mark.png\"/>You are checked in!</h2>");
$.each(badges, function(i,badge) {
$('#badges').append("<h2>New Badge!</h2><p><img class='badge' src='"+badge.image_url+"'><span class='badge-title'>"+badge.name+"</span></p>");
});
}
});
return false;
});
});
</script>
$.ajax({
type: "POST",
url: "/game-checkin",
data: dataString,
beforeSend: function () {
// ... your initialization code here (so show loader) ...
},
complete: function () {
// ... your finalization code here (hide loader) ...
},
success: function (badges) {
$('#checkin-form').html("<div id='message'></div><div id='badges'></div>");
$('#message').html("<h2><img class=\"check-mark\" src=\"/static/images/check-mark.png\"/>You are checked in!</h2>");
$.each(badges, function (i, badge) {
$('#badges').append("<h2>New Badge!</h2><p><img class='badge' src='" + badge.image_url + "'><span class='badge-title'>" + badge.name + "</span></p>");
})
}
});
http://api.jquery.com/jQuery.ajax/:
Here are the callback hooks provided by $.ajax():
beforeSend callback is invoked; it receives the jqXHR object and the settings map as parameters.
error callbacks are invoked, in the order they are registered, if the request fails. They receive the jqXHR, a string indicating the error type, and an exception object if applicable. Some built-in errors will provide a string as the exception object: "abort", "timeout", "No Transport".
dataFilter callback is invoked immediately upon successful receipt of response data. It receives the returned data and the value of dataType, and must return the (possibly altered) data to pass on to success.
success callbacks are then invoked, in the order they are registered, if the request succeeds. They receive the returned data, a string containing the success code, and the jqXHR object.
complete callbacks fire, in the order they are registered, when the request finishes, whether in failure or success. They receive the jqXHR object, as well as a string containing the success or error code.
Note the beforeSend and complete method additions to the code.
Hope that helps.
If you're using jQuery 1.5 you could do that nicely, unobtrusively and generically with a prefilter. Let's make a very simple plugin for this:
(function($) {
var animations = {};
$.ajaxPrefilter(function( options, _, jqXHR ) {
var animation = options.animation && animations[ options.animation ];
if ( animation ) {
animation.start();
jqXHR.then( animation.stop, animation.stop );
}
});
$.ajaxAnimation = function( name, object ) {
if ( object ) {
animations[ name ] = object;
}
return animations[ name ];
};
})( jQuery );
You install an animation as follows:
jQuery.ajaxAnimation( "spinner" , {
start: function() {
// code that starts the animation
}
stop: function() {
// code that stops the animation
}
} );
then, you specify the animation in your ajax options:
jQuery.ajax({
type: "POST",
url: "/game-checkin",
data: dataString,
animation: "spinner",
success: function() {
// your success code here
}
});
and the prefilter will ensure the "spinner" animation is started and stopped when needed.
Of course, that way, you can have alternative animations installed and select the one you need per request. You can even set a default animation for all requests using ajaxSetup:
jQuery.ajaxSetup({
animation: "spinner"
});
The best method I have found, assuming you are populating a present but empty field is to have a .loading class defined with background-image: url('images/loading.gif') in your CSS. You can then add and remove the loading class as necessary with jQuery.
you can set global ajax loading icon handler using here #ajxLoader takes your loading icon
$( document ).ajaxStart(function() {
$("#ajxLoader").fadeIn();
});
$( document ).ajaxComplete(function() {
$("#ajxLoader").fadeOut();
});
$(function() {
$('.error').hide();
$("#checkin-button").click(function() {
var mid = $("input#mid").val();
var message = $("textarea#message").val();
var facebook = $('input#facebook').is(':checked');
var name = $("input#name").val();
var bgg_id = $("input#bgg-id").val();
var thumbnail = $("input#thumbnail").val();
var dataString = 'mid=' + mid + '&message=' + message + '&facebook=' + facebook + '&name=' + name + '&bgg_id=' + bgg_id + '&thumbnail=' + thumbnail;
$.ajax({
type : "POST",
url : "/game-checkin",
data : dataString,
beforeSend : function() {
$('#preloader').addClass('active');
},
success : function(badges) {
$('#preloader').removeClass('active');
$('#checkin-form').html("<div id='message'></div><div id='badges'></div>");
$('#message').html("<h2><img class=\"check-mark\" src=\"/static/images/check-mark.png\"/>You are checked in!</h2>");
$.each(badges, function(i, badge) {
$('#badges').append("<h2>New Badge!</h2><p><img class='badge' src='" + badge.image_url + "'><span class='badge-title'>" + badge.name + "</span></p>");
});
},
complete : function() {
$('#preloader').removeClass('active');
}
});
return false;
});
});
#preloader{
background: url(staticpreloader.gif);
}
.active {
background: url(activepreloader.gif);
}
I wrote a blog post about how to do this on a generic document level.
// prepare the form when the DOM is ready
$(document).ready(function() {
// Setup the ajax indicator
$('body').append('<div id="ajaxBusy"><p><img src="images/loading.gif"></p></div>');
$('#ajaxBusy').css({
display:"none",
margin:"0px",
paddingLeft:"0px",
paddingRight:"0px",
paddingTop:"0px",
paddingBottom:"0px",
position:"absolute",
right:"3px",
top:"3px",
width:"auto"
});
});
// Ajax activity indicator bound to ajax start/stop document events
$(document).ajaxStart(function(){
$('#ajaxBusy').show();
}).ajaxStop(function(){
$('#ajaxBusy').hide();
});
The AJAX process starts when you run the $.ajax() method, and it stops when the 'complete' callback is run. So, start your processing imagery/notification right before the $.ajax() line, and end it in the 'complete' callback.
ajaxStart and ajaxStop handlers can be added to any elements, and will be called whenever ajax requests start or stop (if there are concurrent instances, start only gets called on the first one, stop on the last to go). So, it's just a different way of doing global notification if you had, for example, a status spinner somewhere on the page that represents any and all activity.