jQuery $.post callback function calling location.reload() without using an anonymous function - javascript

Consider the following:
wrap callback in anonymous function (works)
$('#updateView').change(function(e) {
$.post(URL + "actions/updateView.php",
{ view: $(this).val() },
function() {reloadPage();}
);
});
call function directly (cookie is set but doesn't seem to update before page reload)
$('#updateView').change(function(e) {
$.post(URL + "actions/updateView.php",
{ view: $(this).val() },
reloadPage()
);
});
For what i am doing the first works but the second doesn't. the function reloadPage (shown below) reloads the page after updateView.php updates a cookie. For some reason using the second version the cookie isn't getting set before the page is reloading. but if i refresh the page my self, it "finds" the new value for the cookie.
is there something in the jQuery docs about this? I couldn't find anything.
function reloadPage() {location.reload(true);}
I am using jQuery 1.4.1, Php 5.2.5, Apache 2.2.11

Try this:
$('#updateView').change(function(e) {
$.post(URL + "actions/updateView.php",
{ view: $(this).val() },
reloadPage
);
});
reloadPage() isn't a function name, but reloadPage is :)

Related

Run JS Function on Ajax Success & on Page Load

I have a function newCount that I run on Ajax success and it is working OK, however, I want to also run the same function every time the window is reloaded but for some reason I'm unable to call the function with newCount();
my code:
.ajax
$( document ).ajaxComplete(function() {
newCount();
});
.js
function newCount() {
var sum = 0;
$('.myclass').each(function() {
sum += parseFloat($(this).text());
});
// update count in html
$('#myid').html(sum);
}; // end count function
newCount(); // ajax not working when this in place
when I add newCount(); after the function, it will run correctly on page load, but the ajax will no longer work and vice versa.
What am I missing? How can I call the same function from the ajax success and every time the page is loaded?
Hey I've created this Plunker to show you how you should call the functions.
Here is the Javascript code.
<script>
(function(){
function newCount(msg) {
alert("message from: " + msg);
}; // end count function
debugger;
newCount("Page load");
$.get( "data.json", function( data ) {
alert( "Load was performed." );
});
$(document).ajaxComplete(function() {
newCount("ajax complete");
});
})();
EDIT 1
I've changed the Plunker so you can see that also works inside the $.ajax success property.
$.ajax({
url: "data.json",
data: "",
success: function() {
newCount("ajax complete");
}
});

Javascript with MVC not working in IE without browser debugger

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.

How to wait for a function to complete before executing another function

I'm using selecter jquery. I initialize it by typing the code
$("select").selecter();
I need to make sure that the formstone selecter jquery library has completed before i start appending elements. So what i did is to is use the $.when function
initialize: function(){
$.when($("select").selecter()).then(this.initOptions());
},
initOptions: function(){
this.$el.find('.selecter').addClass('something');
}
But this does not work. How can i wait while formstone selecter is doing its thing before i execute another function?
Thanks,
UPDATE
Here's the update of what i did but it does not work.
initialize: function(){
$("select").selecter({callback: this.initOptions });
},
initOptions: function(){
this.$el.find('.selecter').addClass('something');
}
There is a callback option.
The function passed as a callback will receive the newly selected value as the first parameter
Should be $("select").selecter(callback: function() { alert('callback fired.') });
or as shown
$("select").selecter({
callback: selectCallback
});
function selectCallback(value, index) {
alert("VALUE: " + value + ", INDEX: " + index);
}
The problem which I think regarding the callback edited code is that this can refer to anything. Try the following code
var selectorObj = {
initialize: function(){
$("select").selecter({callback: selectorObj.initOptions });
},
initOptions: function(){
this.$el.find('.selecter').addClass('something');
}
};
Created a working fiddler for you http://jsfiddle.net/6Bj6j/
The css is out of shape. Just select what is poping up when you click on the dropdown. You will get an alert which is written in the callback.
The problem with the provided snippet is the scope of the callback:
var selectorObj = {
initialize: function(){
$("select").selecter({ callback: selectorObj.initOptions });
},
initOptions: function(){
// 'this' refers to the "$('.selecter')" jQuery element
this.addClass('something');
}
};
However if you just need to add a class to the rendered element, you should use the 'customClass' option:
$("select").selecter({
customClass: "something"
});
If you need to do more, you can always access the Selecter element directly:
var $selecter = $("select").selecter().next(".selecter");
$selecter.addClass("something").find(".selecter-selected").trigger("click");
Sidenote: I'm the main developer of Formstone. If you have any suggestions for new features or better implementation, just open a new issue on GitHub.

Javascript works only once when function calls via button

I have a page with Javascript that calls a Django URL, but this call just work once.
The html code is here:
<script>
function myFunction(pk) {
if ($.data(this, 'submitted')){
return false;
}
$.data(this, 'submitted', true);
$.get("{%url 'myViewURL' %}",{req:pk}, function (data) {
$.data(this, 'submitted', false);//libero
});
}</script>
Button code
<button onclick="myFunction({{id}});">Click Me</button>
The view code:
def myFuncView(request):
p_id=request.GET['req']
do_stuff(p_id)
return redirect('anotherURL',p_id,permanent=True)
When is the first time I press the button, it fires, but after that it does not work anymore, even if I refresh the page or go to another page and come back!
this inside the get function refers to the ajax request, not the button which initiated it.
You need to store a reference to this, so you can then use it in a different context:
var self = this;
$.get("{%url 'myViewURL' %}", {
req: pk
}, function (data) {
$.data(self, 'submitted', false); //libero
});

jQuery $.get returns white error page when handling errors

The following code gives me an error like this when I request a page and it comes back 404. Instead it should bring up an alert. What is strange is it only does this on links that have been ajaxed in, on links that don't update/change it works fine.
('.page-wrap').append('<img src="img/graphics/ajax-loader.gif" class="ajax-loader" />');
var target = $('section.content'),
siteURL = 'http://' + top.location.host.toString(),
internalLinks = $("a[href^='"+siteURL+"'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#']"),
links = $('a'),
URL,
el,
mainContent,
headContent,
headClasses,
pageName,
ajaxSpinner = $('.ajax-loader');
internalLinks.click(function(e) {
el = $(this);
URL = el.attr('href');
$('.current_page_item').removeClass('current_page_item');
el.addClass("current_link").parent().addClass("current_page_item");
ajaxLoader(URL, false);
e.preventDefault();
});
function ajaxLoader(location, isHistory) {
$("html, body").animate({ scrollTop: "0px" });
ajaxSpinner.show();
$('.page-wrap').css('opacity', '0.5}');
// Load New Page
$.get(location, function(data) {
mainContent = $('section.content', data).html();
headContent = $('.feature-content', data).html();
pageName = $('.page-name', data).html();
headClasses = $('header', data).attr('class');
$('section.content').html(mainContent);
$('.page-name').html(pageName);
$('.feature-content').html(headContent);
if (headClasses) {
$('header').attr('class', headClasses);
} else {
$('header').removeClass();
}
if (!isHistory) {
history.pushState(location, '', location);
}
$(resizeHeader);
ajaxSpinner.fadeOut();
}).error(function() {
alert('woops'); // or whatever
});
}
w.bind('popstate', function(event) {
if (event.originalEvent.state !== null ) {
ajaxLoader(event.originalEvent.state, true);
}
});
First thoughts
Is it perhaps the case that something in your success handler code is causing an error of some kind? Like maybe the injection of whatever html that comes back the first successful time is causing the script to fail a second time?
What do you see playing out in your your Fiddler/Firebug/F12 developer tool of choice - you are using one of these, right? :) Keep an eye on any console errors...
Second thought
What jQuery version are you using?
I have tested this with jq 1.8.2 and the error handler works just fine for me, but if this is a JSONP request it won't trigger the error() function. I took the gist of your code:
$.get(
"404MeBaby.html", function (data) {
$(".result").html(data);
console.log(data);
}
).error(
function (x) {
console.log("well that didn't go so well...");
});
From the API:
As of jQuery 1.5, the success callback function is also passed a
"jqXHR" object (in jQuery 1.4, it was passed the XMLHttpRequest
object). However, since JSONP and cross-domain GET requests do not use
XHR, in those cases the jqXHR and textStatus parameters passed to the
success callback are undefined.
You could try using $.ajax instead as it gives a lot more control. Or, you can set the jQuery global ajax options as shown here that will affect all $.get calls, but remember the curse of JSONP, if relevant!

Categories

Resources