Creating a new function in AJAX - ajax

I saw some sample code like this in Javascript. Is this AJAX?
(function() {
/*some code*/
})();
Thanks a lot!

Is this AJAX?
No. It's what's commonly referred to as an "immediately invoked function expression", or IIFE.
(function() {
/*some code*/
})();
//^^These parentheses cause the function to be executed
The wrapping pair of parentheses cause the construct to be an expression, rather than a declaration. That's necessary because you can't have an anonymous function declaration (you'd get a syntax error).
They are commonly used to introduce a new scope (producing what you may have heard referred to as a closure).

Related

Problems in throttle function in js

below 'throttle' code works good. But my question is that why we are using 'this' keyword in throttle function.
what is it actually?
please describe it.
thank you very much
$("document").ready(function(){
$("input").keypress(throttle(function(e){
$(".div1").html($("#ip").val());
},1000))
function throttle(fn,dly){
var timer=null;
return function(){
clearTimeout(timer);
timer=setTimeout(function(){
fn.apply(this,arguments);
},dly);
}
}
});
fn is a function. You can call the function in the standard way - fn() or you can call the call method or apply method on it.
When calling call or apply you have the option with the first argument to set the scope the function can be called in. The scope can also be set to null for no scope.

How to manipulate async scope in angularjs

I have this defined in controller
$scope.files = {};
Then I have a ajax call to get data and pass to $scope.files;
In the same controller. I have a ng-click function which I want to manipulate $scope.files
How to do that because it is async. I tried and the $scope.files always return blank {}
$scope.click = function() {
//Do something to $scope.files;
}
My fault. this is not related to async. I can actually get the data.
My problem is the return data is object and I tried to use .length to get the length of object so it always return 0 and {}. And I found .length for array.
and Object.keys(a) for object sizes
Looks like you need to use promise/deferred implementation. Promises allow you to execute code and once the promise is returned then continue.

getJSON success function out of scope

I just have started writing AJAX functions using jquery. Here i am calling myfunction(). where check.php is returning {"count":1} or {"count":0} for which myfunction is always returning retval=false . But for {"count":1} it should return true. I dont know where i am wrong. Below is the code i am using.
function myfunction(){
var retval=false;
if($('#tag').val() != ''){
var query=$( "#tag" ).val();
$.getJSON("check.php",{
q: query
},function(data){
if(data.count==0){
$('#formerrormsg').html('Error msg');
}
else{
retval=true;
}
});
}
return retval;
}
Please Help me to understand this.
That is because, $.getJSON(..) is asynchronous. The below is what jQuery doc says about the third parameter you are passing (function(data){...}):
success(data, textStatus, jqXHR): A callback function that is executed if the request succeeds.
The function which set retval to true is executed when the AJAX call succeeds; not when you call myfunction()
There are two way you could get around this:
Make your AJAX call synchronous; the function wont return until the response is received. (Not a great idea, UI might freeze)
Modify your code -- the asynchronous way. Typically, call the function (that would ideally be depending on the return value) from within the "success-function" defined as the 3rd parameter.
It is an AJAX (asynchronous) request so return retval; is returning before the AJAX success function executes, hence always returns false. You need to change your implementation to wait for that request before returning and using retval.

PlayFramework strict routes and ajax

Question could be obvious but I still cannot find appropriate solution for this.
Lets assume there is a controller with only one method:
class MyController extends Controller {
public static Result sum(int op1, int op2) {
return ok(op1 + op2);
}
}
Routes file is simple enough too:
GET /sum controllers.MyController.sum(op1: Integer, op2: Integer)
Well, now I can do call from templates:
#controllers.routes.MyController.sum(1, 2)
which will be translated to
localhost:9000/sum?op1=1&op2=2
, or directly paste this url in browser. This works pretty ok.
But everything goes bad when I decide to use ajax for doing this.
I am not js-guru, so I write small (and bad I think:) object using jQuery which adds onClick handler to button. Here it is:
entityController.setSumURL = function(sumURL) {
this.sumURL = sumURL;
}
entityController.bindSumButton = function(buttonId, op1, op2) {
$.get(entityController.sumURL, {op1: op1, op2, op2}, function(){
alert("Done!");
});
}
where entityController.sumURL should be url to /sum method.
Usually when I render page view I write something like this:
#()
....
entityController.setSumURL("#controllers.routes.MyController.sum()")
....
But I cannot do this because sum method has mandatory arguments and there is no way to get address only because binded url can rely on parametes passed to function defined in routes.
So the question is how to do get path only from url without arguments, or how to reorganize whole process to avoid such situations?
My solution is to remove arguments from function appearing in routes and query them directly from request, but my project is growing and sometimes it become too hard to understand which parameters are passed to method.
Check out the zen tasks sample application.
In particular:
the javascriptRoutes method in the controller
the references to jsRoutes in the coffeescript
the routes config
You may want to compile this app and look at the output javascript rather than the coffeescript if you're not familiar with coffeescript.
Also, if you're reloading parts of the page using ajax, you may want to bind your jQuery using
$('.somePermanentContainer').on('click', 'selectorForClickable', function()...)
otherwise you'll find it's no longer bound when that part of the DOM is reloaded.

in jQuery what is the difference between $.myFunction and $.fn.myFunction?

I'm delving into writing plugins for jQuery and I'm trying to understand the distinction between $.f and $.fn.f
I've seen pluggin authors use both, or sometimes assign $.f = $.fn.f
Can someone explain this to me, reasoning, benefits, etc?
Looking at the jQuery source code will clear things up. By the way, jQuery and $ refer to the same object, and this is how the jQuery object is defined:
var jQuery = function( selector, context ) {
return new jQuery.fn.init( selector, context );
}
jQuery is a function and in Javascript, a function is also an object of the type Function. So jQuery.f or $.f attaches f to the jQuery Function object, or call it the jQuery class if you will.
if you look at jQuery's source, you'll see that jQuery.prototype has been assigned to jQuery.fn
jQuery.fn = jQuery.prototype
So, whenever you attach a method (or property) to jQuery.fn, as in jQuery.fn.f = .., or $.fn.f = .., or jQuery.prototype.f = .., or $.prototype.f = .., that method will be available to all instances of this jQuery class (again, there are no classes in Javascript, but it may help in understanding).
Whenever you invoke the jQuery() function, as in jQuery("#someID"), a new jQuery instance is created on this line:
return new jQuery.fn.init( selector, context );
and this instance has all the methods we attached to the prototype, but not the methods that were attached directly to the Function object.
You will get an exception if you try calling a function that wasn't defined at the right place.
$.doNothing = function() {
// oh noez, i do nuttin
}
// does exactly as advertised, nothing
$.doNothing();
var jQueryEnhancedObjectOnSteroids = $("body");
// Uncaught TypeError: Object #<an Object> has no method 'doNothing'
jQueryEnhancedObjectOnSteroids.doNothing();
Oh, and finally to cut a long thread short and to answer your question - doing $.f = $.fn.f allows you to use the function as a plugin or a utility method (in jquery lingo).
The $.f is a utility function whereas $.fn.f is a jQuery plugin / method.
A utility function is basically a function within the jQuery namespace that is useful for performing some operation, for example, $.isArray(obj) checks if an object obj is an array. It is useful to put functions in the jQuery namespace if you'll use them often and also to avoid global namespace pollution.
jQuery methods on the other hand operate on jQuery objects/wrapped sets. For example, $(document.body).append('<p>Hello</p>'); will append a paragraph containing Hello to the body element of the document. $.fn is a shorthand for $.prototype in later versions of jQuery (it wasn't always in earlier versions of the library). You would use this when writing your own plugins.
The $.fn.f is simply a shortcut to jQuery.prototype
By using the fn, you can add plugin methods without using the extend method:
jQuery.fn.myPlugin = function(opts) { ... }

Resources