Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Huragok
Sep 14, 2011
Is there a JavaScript library that duplicates the functionality of jquery's .ajax function but without everything else?

Adbot
ADBOT LOVES YOU

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Well, I don't actually know anything about Zepto and it is not strictly just .ajax(), but it is a "minimalist JavaScript library for modern browsers with a largely jQuery-compatible API."

http://zeptojs.com/

Like I said, I don't know anything about it, just stumbled on it when reading backbone.js documentation.

Funking Giblet
Jun 28, 2004

Jiglightful!
code:
(function(a){var b=a.document,c=function(a,b){return!!(typeof a[b]=="object"&&a[b])},d=function(a,b){var c=typeof a[b];return c=="function"||c=="object"&&!!a[b]||c=="unknown"},e=c(b,"documentElement")&&b.documentElement,f=!!Function.prototype.call;var g=[function(){return new a.ActiveXObject("Microsoft.XMLHTTP")},function(){return new a.ActiveXObject("Msxml2.XMLHTTP.3.0")},function(){return new a.ActiveXObject("Msxml2.XMLHTTP.6.0")}],h,i;if(d(a,"XMLHttpRequest")){try{if(new a.XMLHttpRequest){i=function(){return new XMLHttpRequest}}}catch(j){}}else if(d(a,"ActiveXObject")){for(h=g.length;h--;){try{if(g[h]()){i=g[h]}}catch(j){}}}var k;if(i){k=function(a,b,c){function h(a){var b=false,c=a.status,d=c>=200&&c<300,e=c===304;if(d||e||c===0&&a.responseText){b=true}return b}function i(){if(a.readyState===4){if(h(a)){if(c.success){c.success(a)}}else if(c.fail){c.fail(a)}if(c.complete){c.complete(a)}}}c=c||{};var d,e=c.method||"get",f=c.headers||{},g=c.data||null;if(e==="post"&&typeof f["Content-Type"]==="undefined"){f["Content-Type"]="application/x-www-form-urlencoded"}a.open(e,b);for(d in f){a.setRequestHeader(d,f[d])}a.onreadystatechange=i;a.send(g)}}var l;if(i&&k){l=function(a,b){var c=i();k(c,a,b);return c}}a["API"]={isHostMethod:d,isHostObjectProperty:c,createXhr:i,xhrSend:k,ajax:l};b=e=null})(this)
Usage:
API.ajax(url, options);

* options.method - defaults to "get"
* options.timeout - defaults to 30 seconds
* options.complete
* options.success
* options.headers
* options.data
* options.fail

API.ajax('http://someUrl',{success:function(xhr){alert(xhr.responseText);}});

Kallikrates
Jul 7, 2002
Pro Lurker

Wheany posted:

Watch this video (java script: The Good Parts). It's a pesentation by Douglas Crockford at Google Tech Talks.

It's not about best practises for websites, but personally, it kinda blew my mind when I watched it:

https://www.youtube.com/watch?v=hQVTIJBZook

Also use JSlint/JShint with as few exceptions as possible. It will force you to write better Javascript.

Thanks, I use st2 and have been using the linting package, it gives me realtime lint warnings and errors.

Huragok
Sep 14, 2011

Wheany posted:

Well, I don't actually know anything about Zepto and it is not strictly just .ajax(), but it is a "minimalist JavaScript library for modern browsers with a largely jQuery-compatible API."

http://zeptojs.com/

Like I said, I don't know anything about it, just stumbled on it when reading backbone.js documentation.

Yeah I use zepto in my mobile apps, but I just don't need that darn selector doohickey! :v:

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
https://github.com/joehewitt/ajax

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Kallikrates posted:

Where is a good source for picking up best practices etc for writing javascript for websites?

Its not my first langauge, and so far I have solid grasp of the basics (async, callbacks etc).

From what I gather you just import the scripts you want in order (if dependance matter). But when I start writing my own 'site.js' I'm kinda making stuff up as I go, I understand you can't access DOM elements before they load, but when do you put the scripts in the <head> vs after <body> is it normal for your document ready function to be one big list of methods, and selectors, which document ready is the best, if using jquery should you tap into it's ready functions. When should you do stuff outside of or before document ready. etc..

I think I know the answers to these, but I would hate to be wrong and have to unlearn bad habits and rewrite code, and most of it I've gathered from reading other people's code, that might not be idiomatic.

Some things to be aware of / do:

Namespace your code. Always.
Learn about the 'module pattern', use it where it makes sense
Learn about custom events and writing event driven code, use it where it makes sense

As far as best practices, combine and minify your scripts when you hit production, and unless there is a reason not to, load your scripts at the end of the BODY.

Seconding reading / watching Crockford stuff. He definitely has a "my way is the only way!!" thing going on, but overall he is a great teacher of the JavaScript. John Resig of jQuery fame has a book coming out soon (not sure of the expected date) that I got a review copy of, and that is / will be an awesome resource.

dizzywhip
Dec 23, 2005

Funking Giblet posted:

It's been changed a few times in the last number of releases, and it's been broken a few times, so it's neither reliable nor tested. (Not to mention the confusion after they change how attr worked, how reliable was that either?)

If anything that's an argument for why you shouldn't try to do it yourself. If jQuery can't get it right without a few iterations then it's unlikely that a lone developer can.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Funking Giblet posted:

It's been changed a few times in the last number of releases, and it's been broken a few times, so it's neither reliable nor tested.

AJAX? How so?

Funking Giblet
Jun 28, 2004

Jiglightful!

Gordon Cole posted:

If anything that's an argument for why you shouldn't try to do it yourself. If jQuery can't get it right without a few iterations then it's unlikely that a lone developer can.

That's you putting jQuery on a pedestal. It's a case of understanding what you are doing. I know what attributes are vs properties, I gather most people don't, hence the usage of attr when direct properties would do the job instead of the crap that goes on in that method. ie: .attr("checked",ehwhatTheHellDoIset) vs. el.checked = true
I wonder how many people changed to prop, then to attr, without knowing what the hell was going on. (bear in mind, el.checked = true has worked since IE4)

quote:

AJAX? How so?

http://blog.jquery.com/2011/01/31/jquery-15-released/

Search "Ajax rewrite"

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
There was an internal rewrite, with no API break, but instead, provides more consistency for random browser bugs. How does that support your argument?

Funking Giblet
Jun 28, 2004

Jiglightful!

Suspicious Dish posted:

There was an internal rewrite, with no API break, but instead, provides more consistency for random browser bugs. How does that support your argument?

So they broke one part of their API doing a rewrite, but not another, and that's the what you are standing behind? And they changed the public interface as it returns something different. I've never ever had a break doing it my way. That's my argument. They committed a cardinal sin in rewriting public APIs. Have you much experience working with JavaScript or APIs in general? The JavaScript community seems quite bohemian in their ways, I guess it's because of the lower barrier to entry. Again, I'm not saying you should abandon JQuery, but god drat if people just stand behind everything they do even when they are quite cavalier when their poo poo breaks. THIS STUFF IS EASY TO LEARN, LEARN IT.

Funking Giblet fucked around with this message at 00:27 on Jun 28, 2012

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
What part of their public API did they break? They also changed it from returning a real XHR to returning a jqXHR - the latter is a dummy object that papers over the real XHR, and all the properties that jQuery said you were allowed to touch were still there. I do not understand how that's an API break.

I'm behind good software engineering practices. I'm not standing by them unilaterally - I said that you can also use MooTools or Dojo or something. I'm simply trying to understand how they broke API at all.

Funking Giblet
Jun 28, 2004

Jiglightful!

Suspicious Dish posted:

What part of their public API did they break? They also changed it from returning a real XHR to returning a jqXHR - the latter is a dummy object that papers over the real XHR, and all the properties that jQuery said you were allowed to touch were still there. I do not understand how that's an API break.

I'm behind good software engineering practices. I'm not standing by them unilaterally - I said that you can also use MooTools or Dojo or something. I'm simply trying to understand how they broke API at all.

So if you're behind good software engineering practices, how do you explain the attr debacle? I said Ajax was changed, not broken, the attr() is what broke recently. (1.6.1 I believe).

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Funking Giblet posted:

So if you're behind good software engineering practices, how do you explain the attr debacle? I said Ajax was changed, not broken, the attr() is what broke recently. (1.6.1 I believe).

Did jQuery steal your girl or something?

Crazy idea: if you coded to jQuery 1.5.2 (or 1.3.6, or 1.6.1, or.... ) and don't want those evil jQuery guys breaking your poo poo *ever*, just include jQuery 1.5.2 (or 1.3.6, or 1.6.1, or....) on your page instead of 1.7 (or 1.8, or...) on your page.

Are they flawless golden gods? No. But jQuery by and large has been rock solid, it's public face has been incredibly consistent for a project with it's scope, and they do a very good job about communicating upcoming changes.

If you are only using a single function or method, yeah, 33k is a big download, but 33k off a CDN verus your code that hasn't been reviewed, tested, or vetted anywhere near as much as jQuery might be worth it.

dizzywhip
Dec 23, 2005

Funking Giblet posted:

So they broke one part of their API doing a rewrite, but not another, and that's the what you are standing behind? And they changed the public interface as it returns something different. I've never ever had a break doing it my way. That's my argument. They committed a cardinal sin in rewriting public APIs. Have you much experience working with JavaScript or APIs in general? The JavaScript community seems quite bohemian in their ways, I guess it's because of the lower barrier to entry. Again, I'm not saying you should abandon JQuery, but god drat if people just stand behind everything they do even when they are quite cavalier when their poo poo breaks. THIS STUFF IS EASY TO LEARN, LEARN IT.

Not using a library because they might change their API at some point is just silly. If you're really too lazy to update your code as the API changes, just don't update the library.

Here's my argument in more detail. If I decide to use jQuery to do my ajax call, I can google "jquery ajax", click the first link to get to the documentation and have everything I need to get up and running in less than five minutes. I think it's reasonable to assume that the majority of modern web apps are using jQuery in production, so I can be reasonably sure that it's reliable enough for my own uses.

If I decide to write my own implementation, I can google "javascript ajax" and learn how to use the browser's API. Fortunately I'll know to avoid w3schools (the first result), but others might not know to do that. I can do some research to learn about cross-browser compatibility issues and write my own little ajax library. In the end I've spent probably about an hour or two to create something that's almost certainly not as flexible as jQuery, and when a bug causes it to break a few months down the road I'll have to go in and fix it myself.

The tradeoffs just don't make sense. The time spent updating code to match new APIs is going to be significantly less than writing your own libraries, dealing with lovely browser APIs and debugging cross-browser compatibility issues.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Funking Giblet posted:

I said Ajax was changed, not broken


Funking Giblet posted:

It's been changed a few times in the last number of releases, and it's been broken a few times, so it's neither reliable nor tested.

Feel free to move the goalposts. The attr/prop split is a good cleanup.

Polio Vax Scene
Apr 5, 2009



I want to let the user save their game but I'm not sure of what would be the best way to do this.

I have three things which need to be saved: The current level name, a list of objects which persist between levels, and a list of objects which are permanently removed. Currently I'm saving this to a cookie but even with just a small amount of data I'm already over 1kb. I'm afraid that eventually I'll reach some cookie size limit and this will break it. I've done pretty much everything I can to make the save data as concise as possible. Is there some other method I can use for saving/loading? Saving a file on the server is out of the question.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Manslaughter posted:

I want to let the user save their game but I'm not sure of what would be the best way to do this.

I have three things which need to be saved: The current level name, a list of objects which persist between levels, and a list of objects which are permanently removed. Currently I'm saving this to a cookie but even with just a small amount of data I'm already over 1kb. I'm afraid that eventually I'll reach some cookie size limit and this will break it. I've done pretty much everything I can to make the save data as concise as possible. Is there some other method I can use for saving/loading? Saving a file on the server is out of the question.

If you can't store to a server, you have few options. One is cookies... but the good news is, you can store 4k per cookie, and store ~30 cookies per domain. So in theory, you can do a bunch of storage that way. Until they clear their cache...

The other way is to use "Web Storage" (http://dev.w3.org/html5/webstorage/) but then you'll have to figure out your needs as far as browser support. IIRC, it's IE 8+ and pretty much all other browsers.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
I think localStorage is probably the most widely-supported option.

JavaScript code:
// Store value on the browser beyond the duration of the session
localStorage.setItem('key', 'value');
 
// Retrieve value (works even after closing and re-opening the browser)
alert(localStorage.getItem('key'));

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
There's a few shims for localStorage that use cookies or Flash LocalSharedObjects.

Polio Vax Scene
Apr 5, 2009



That works perfectly and is easier than cookies even. Thanks!

Funking Giblet
Jun 28, 2004

Jiglightful!

Lumpy posted:

Did jQuery steal your girl or something?

Crazy idea: if you coded to jQuery 1.5.2 (or 1.3.6, or 1.6.1, or.... ) and don't want those evil jQuery guys breaking your poo poo *ever*, just include jQuery 1.5.2 (or 1.3.6, or 1.6.1, or....) on your page instead of 1.7 (or 1.8, or...) on your page.

Are they flawless golden gods? No. But jQuery by and large has been rock solid, it's public face has been incredibly consistent for a project with it's scope, and they do a very good job about communicating upcoming changes.

If you are only using a single function or method, yeah, 33k is a big download, but 33k off a CDN verus your code that hasn't been reviewed, tested, or vetted anywhere near as much as jQuery might be worth it.


I guess most people will be stuck at 1.9 in the future for a long time anyway!

Huragok
Sep 14, 2011

Funking Giblet posted:

I guess most people will be stuck at 1.9 in the future for a long time anyway!

The price of progress! :eng101:

Black Noise
Jan 23, 2008

WHAT UP

I have a checkbox on this form setup so that when it is clicked it calls a function that checks to see if the relevant fields have been properly filled out right now it works but it only works once so if someone checks the box then unchecks it and presses submit they then have to fill out all of the fields instead of just the ones that apply to them.

So what I want to do is if the box is checked then all fields are required but if it isn't then only some of the fields are required

I'm seeing an error in the console on chrome involving a javascript from DreamWeavers Spry library (I'm using spry because the text validation fields are really quick to implement)

What im trying to do is when you click on this checkbox then it calls the function to check if the required fields have been filled out.

This is the error message
Uncaught TypeError: undefined is not a function :223 (anonymous function)


The Checkbox in question
code:
<span id="sprycheckbox1">
	  <input type="checkbox" name="jUpdate" value="YES" tabindex="15" onclick="requireJobberValidation ()"/>
	  </span>
The related scripts
code:
<script type="text/javascript">
var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1", "integer", {minChars:0, maxChars:8, useCharacterMasking:true});
var sprytextfield3 = new Spry.Widget.ValidationTextField("sprytextfield3");
var sprytextfield4 = new Spry.Widget.ValidationTextField("sprytextfield4");
var sprytextfield5 = new Spry.Widget.ValidationTextField("sprytextfield5");
var sprytextfield7 = new Spry.Widget.ValidationTextField("sprytextfield7");
var sprytextfield8 = new Spry.Widget.ValidationTextField("sprytextfield8");
var spryselect1 = new Spry.Widget.ValidationSelect("spryselect1");
var sprytextfield9 = new Spry.Widget.ValidationTextField("sprytextfield9");
var sprytextfield6 = new Spry.Widget.ValidationTextField("sprytextfield6");
// Line 223 is below;
var sprycheckbox1 = new Spry.Widget.ValidationCheckbox("sprycheckbox1", {isRequired:false});
</script>


<script type="text/javascript">
function requireJobberValidation ()
{
if (document.getElementsByName("jUpdate").item(0).checked == true)
  {
	var spryselect2 = new Spry.Widget.ValidationSelect("spryselect2");
	var sprytextfield11 = new Spry.Widget.ValidationTextField("sprytextfield11");
	var sprytextfield12 = new Spry.Widget.ValidationTextField("sprytextfield12");
	var sprytextfield13 = new Spry.Widget.ValidationTextField("sprytextfield13");
	var sprytextfield14 = new Spry.Widget.ValidationTextField("sprytextfield14");
	var sprytextfield15 = new Spry.Widget.ValidationTextField("sprytextfield15");
	var sprytextfield16 = new Spry.Widget.ValidationTextField("sprytextfield16", "none");
  }
};
</script>

Black Noise fucked around with this message at 15:06 on Jul 5, 2012

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
From the error message it sounds like ValidationCheckbox is undefined.

If you put a breakpoint on that line, what does it say is the value of Spry.Widget.ValidationCheckbox?

Black Noise
Jan 23, 2008

WHAT UP

I fixed the function undefined issue, now I'm trying to make the checkbox that calls the function work more like a light switch for the field validation

Black Noise fucked around with this message at 16:06 on Jul 5, 2012

Mindisgone
May 18, 2011

Yeah, well you know...
That's just like, your opinion man.
Is anyone familiar with google maps api using javascript? I am specifically trying to use the geocoder api and my code is as follows:
code:

var geocoder;

function codeAddress() {
    var address = document.getElementById("zip").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
		  var latlong = results[0].geometry.location;
		  params = "latlng=latlong"
		  request = new ajaxrequest()
		  request.open("POST","cwerksignup.php",true);
          request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		  request.send(params);
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }
All I am really trying to achieve here is take the value of 'latlong' (which should be the lat and long of my query) and pass it into a php variable (or right into the html form being posted to the php script). I am not sure of the format of this variable so any info on that would be much appreciated. If I am all hosed up here please let me know.

Jam2
Jan 15, 2008

With Energy For Mayhem
I'm using Ruby on Rails and Backbone, and I'm writing the js in Coffeescript.

I'm having a problem in my view, where I get the following error:
code:
Uncaught TypeError: Property 'template' of object #<ListingsNewMajorCategorySelect> is not a function 
Here is the problem view:
code:
class Appname.Views.ListingsNewMajorCategorySelect extends Backbone.View
  template: JST['listings/major_category_selet']

  render: ->
    $(@el).html(@template({categories: 'these'}))
    this
Here's where that view gets called:
code:
class Appname.Routers.Listings extends Backbone.Router
  routes:
    'new': 'new'

  initialize: ->
    @collection = new Appname.Collections.Categories()
    @collection.fetch()

  new: ->
    view = new Appname.Views.ListingsNewMajorCategorySelect(collection: @collection)
    $('#js-container').html(view.render().el)

And where the router is initiated:
code:
window.Appname =
  Models: {}
  Collections: {}
  Views: {}
  Routers: {}
  init: ->
    new Appname.Routers.Listings()
    Backbone.history.start({pushState: true})


$(document).ready ->
  Appname.init()
Any idea why the console is spitting out this error? Writing template: -> JST[...] quiets the error, but does not render the template.

I'm just starting out with Coffesscript and Backbone, so I don't really know what I'm doing.

Strong Sauce
Jul 2, 2003

You know I am not really your father.





Is the template actually "listings/major_category_selet" or is it suppose to be "listings/major_category_select" ?

dizzywhip
Dec 23, 2005

The problem is what it says, that the template property is being used as a function but it isn't one. It looks like the most likely cause is a typo: "listings/major_category_selet" is probably supposed to be "listings/major_category_select". That typo would cause the template property to be undefined, which is not a function.

The reason it doesn't complain when you put the arrow in is that you're making the property into a function, so it can be called, but it doesn't render because the function doesn't do what's expected (return some HTML, I assume).

biochemist
Jun 2, 2005

Who says we don't have backbone?

Wheany posted:

Watch this video (java script: The Good Parts). It's a presentation by Douglas Crockford at Google Tech Talks.

It's not about best practises for websites, but personally, it kinda blew my mind when I watched it:

https://www.youtube.com/watch?v=hQVTIJBZook

Also use JSlint/JShint with as few exceptions as possible. It will force you to write better Javascript.

I'm watching this right now and I'm interested in how he explained Javascript's semi-colon insertion. That's how it works? I mean, I doubt he's lying but drat.

Do I need to worry about that? My js rarely gets huge, but it does kind of worry me in the long run. Is there much of a performance hit between writing semis and leaving them out in huge projects?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

biochemist posted:

I'm watching this right now and I'm interested in how he explained Javascript's semi-colon insertion. That's how it works? I mean, I doubt he's lying but drat.

Do I need to worry about that? My js rarely gets huge, but it does kind of worry me in the long run. Is there much of a performance hit between writing semis and leaving them out in huge projects?

You should put your own semicolons in, but not for any real concern about performance. Putting semicolons in explicitly makes it clear "what you meant" to others (and to yourself in 3 months when you revisit your code) and also avoids some functional "gotchas" where letting the interpreter put them in for you might not give you what you expect / want.

Strong Sauce
Jul 2, 2003

You know I am not really your father.





I've never run into any problems with javascript's rules about automatic semicolon insertion. However the coding style I use never puts the return statement on a different line so I don't run into weird semicolon gotchas.

Here's the thing, unless you like putting every single thing on its own line you will never run into problems with javascript regarding semi-colons. Use semi-colons if you prefer it, or don't use them if you hate them. The only time I will ever space out code by adding a new line is when I'm chaining statements together, and that is not affected by the rules of ASI.

If you want to read the rules for semi-colon insertion it's here:
http://bclary.com/2004/11/07/#a-7.9.1

If you read the next section about examples, you have to be a pretty bad developer to write in some of the ways that will create these gotchas. I don't bother with semicolons but that's more of a preference than anything else.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
That's third edition. Please read the ES5 spec: http://es5.github.com/#x7.9

Strong Sauce
Jul 2, 2003

You know I am not really your father.





Bookmark updated. But still, it's the same thing.

Jam2
Jan 15, 2008

With Energy For Mayhem

Strong Sauce posted:

Is the template actually "listings/major_category_selet" or is it suppose to be "listings/major_category_select" ?

FACK. Thanks, guys.

geeves
Sep 16, 2004

Lumpy posted:

You should put your own semicolons in, but not for any real concern about performance. Putting semicolons in explicitly makes it clear "what you meant" to others (and to yourself in 3 months when you revisit your code) and also avoids some functional "gotchas" where letting the interpreter put them in for you might not give you what you expect / want.

Non-use of semi-colons or not using braces is only of my coding pet peeves with c-style languages. I've tried to contribute to some opensource (mostly jQuery plugins that I use) when I can, especially ones with promise that fall victim to poor coding standards. Only to have the changes rejected and comments deleted when I raise concerns.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
If you're contributing to another project, follow the existing standards. If you don't like them? Too bad. You're not the maintainer. Go fork the project if you really want to.

No maintainer ever likes seeing a whitespace/code-style fix on its own, or a large amount of them compounded with some other fix.

Adbot
ADBOT LOVES YOU

Fruit Smoothies
Mar 28, 2004

The bat with a ZING
I'm building a class on top of JQuery's $.ajax class. My JSON has a response code that determines which function to call back.

code:

function Ajax() {

	var AJAX = this;

	var responseFunction = function(jQueryAjaxSuccessResponse) {
		
		switch(jQueryAjaxSuccessResponse.type) {

			case "OK": {
				// call the "OK" function
				// This is where AJAX is the window object.
				okFunction(jQueryAjaxSuccessResponse, AJAX]);
				break;
			}
			case "WARNING": {}
			...	

	}

}

How can I pass the AJAX object to the callback? I've stepped through the code, and "this" is always either the window or the jQuery javascript object!

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply