Stephen's dev blog

Posts Tagged ‘jquery

  • In: Tutorials
  • Comments Off on jQuery retrieving the data from an AJAX call into the global scope

Another quick one. Reading around it seems to be an issue. You make an AJAX call within a function and you want the call to be synchronous so that you can use the data from the call in the function scope.

AJAX calls are obviously asynchronous. jQuery has a ‘async: false’ option in AJAX calls but it is ignored by most (maybe all?) browsers. Using this method you can force a synchronous request and retrieve that data.

function myFunction()
{
    var myVariable = $.ajax(
    {
        url: 'someScript.php',
        async: false
    }).responseText;
    alert(myVariable);
}

So .responseText retrieves the text value of the response from the AJAX call. And because we’re assigning to a variable we are forcing a synchronous request. You can now use that variable as you see fit.

This causes an issue when you are trying to retrieve a JSON object from an AJAX call into the function scope. The best way I’ve found so far is to retrieve the JSON as a string and use a jquery JSON plugin to convert it into an accessible object. Or you could just use the ‘eval’ method.

Stephen.

Advertisements
  • In: Tutorials
  • Comments Off on jQuery wildcard selectors – update

Hello all,

On my first post on this blog I posted a small snippet to use a small regex pattern in jQuery selectors.

You can find the post here: https://colourgray.wordpress.com/2008/08/05/jquery-wildcard-selectors/

I was reading through some comments and posts on some incoming links and it seems it wasn’t working for anyone anymore. I just tested it myself and unfortunately it’s true (at least with with jQuery v1.3.1). However! All is not lost, there is another method which I’ve tested from one of the incoming links to that post which you can find here:

http://ropox.net/archives/1081

Cheers ropox!

Stephen.

I’ve been working over the weekend on a site and I got to the part of writing the client side MVC using jQuery (because I love the idea now!).

I found out that jQuery has a nice little method for loading external scripts into the page at run time called getScript(). It basically gets the contents of the external file using an AJAX request and then eval()s the code at runtime, which seems like a perfect way of doing it. I reckon it’s much better than appending new <script> tags to the <head> tag as well.

The only issue is that it can take some time to load an external file so you can’t always run functions from within that file straight away. Thankfully there is a workaround for this using another jQuery method. You basically set all AJAX request to be synchronous before you run getScript() and then set AJAX requests to be asynchronous again after the script is loaded. If you end up loading like 20 files at the beginning of a page load this could take a while but hopefully you won’t be doing that 😛

$.ajaxSetup({async: false});
$.getScript(MVCRoot+fileName+'.js');
$.ajaxSetup({async: true});

And here’s some more info on this lovely little function 🙂

A while ago a colleague suggested to me the idea of having a client-side MVC (Model View Controller) framework. At first I didn’t like the idea. I have always thought that all client-side code should be seen as one layer, one collection of files that all act as one set of functionality. Whether that be AJAX calls or general functions etc etc.

Then I began to think about it. We already know that a client-side MVC is possible, but I can now see why it would be useful. But it wouldn’t be the traditional MVC architecture, it would really only be VC, the view and controller layers. And that’s all it can ever really be. Javascript can never directly access the model in a web application environment.

I decided that a VC client-side system would still be useful and I’m probably going to develop one for future use. I haven’t got round to doing this yet but these are my ideas.

Firstly, looking at a few of our sites, I could quickly see that there were many javascript files being loaded per page as they were needed. The number of files could range from 5 to 10 or even more. So we need a way of dynamically loading javascript files onto the page as and when they are needed, on the fly. I initially thought that it wasn’t possible to dynamically load javascript files from within a javascript page but I Googled around a bit and when I found the solution it was painfully obvious: you simply load more tags in the section of the HTML.

So with that in mind, lets create a simple front controller. What does it need to do? It needs to have some basic configuration for the MVC; where the root of the files are etc. It needs to have the aforementioned function to load external javascript files into the current page. It needs to have an initialisation function which kicks the MVC off:

mvc.init.js
/**
* client MVC initialiser
*/

/**
* wheres are the MVC files?
*
* @access public
* @var string
*/
var MVCRoot = '/js/';

/**
* initialise the controller
*/
$(document).ready(function()
{
loadJS('mvc.controller');
Controller.init();
});

/**
* load an external js file by appending
* script tag as child to <head> section
*
* @var fileName name of file to load
* @return bool true on success, false on no fileName given
*/
function loadJS(fileName = null)
{
if (fileName != null)
{
$('<script type="text/javascript" src="'+MVCRoot+fileName+'.js"></script>').appendTo('head');
return true;
}
else
{
return false;
}
}

Ok most of that should make sense. The loadJS() function is fairly straight forward, it simply builds a HTML <script> tag for the new javascript file and appends it to the <head> tag of the HTML. The $(document).ready function then uses this function to ‘include’ the main controller file (which will be /js/mvc.controller.js according to the current config). Now that the init function can call methods of the Controller class it calls the main controller’s initialisation method.

As an initial idea, the main controller could start off looking like this:

mvc.controller.js
/**
* client main controller
*/

var Controller =
{
/**
* holds the current page's type
* used for loading required js files etc
*
* @var string
* @access protected
*/
var _pageType : null,

/**
* main controller init function
* gets current page type
* includes required js files
*/
var init : function()
{
loadJS('mvc.controller.ajax');
Controller._getPageType();

/**
* logic to include required files dependent on page
* type etc etc
*/
...
}

/**
* returns the page type for current URI
*
* @return void
*/
var _getPageType : function()
{
var currentURI = window.location;
Controller._pageType = ControllerAjax.getPageType(currentURI);
}
}

Again this is mostly basic stuff and it definitely hasn’t been tested but I think the general idea is in the right direction. I think now that I can visualise how to seperate out javascript objects more clearly I can see how this would benefit a javascript heavy web site/application.

Even though web frameworks have been gaining more and more popularity over recent years I hadn’t thought of applying the same methodical approach to client side coding until my colleague suggested this idea. I think if you think about it and you’re thinking like I was, you can quickly warm to the idea as I have. Almost every day you can read a new article about how in development, we need to be separating out our different types of logic and our layers. Javascript is of course just another language, so why should it not get the same treatment? 🙂

  • In: Tutorials
  • Comments Off on jQuery create a simple plugin

This is just a quick tutorial (more of a code snippet) for creating a very simple plugin for jQuery.

Of course, there are lots of tutorials around for this, this is mainly for reference 🙂

$.fn.myFunction = function()
{
    // use the following loop to iterate through all objects
    // returned by the jQuery selector which was used
    return this.each(function()
    {
        // here we can access any properties using
        // the normal jQuery selectors
        alert($(this).html());
        $(this).addClass('red');
    });
};

So this function alerts the HTML of the selected element(s) and adds a new class ‘red’. You can then call the new function using:

$('#myElement').myFunction();

Another example of how easy and powerful jQuery is 🙂 Look here for more information.

Tags: ,

UPDATE: The below method no longer works! Go here to see a tested, working method: http://ropox.net/archives/1081

This is the first tutorial on my blog. We’re going to start with something simple and it’s only useful if you use jQuery.

When I started using jQuery I found it hard to find information on using wildcards when selecting DOM elements.

After a while you get to understand that jQuery allows the use of regular expressions in a lot of places, I.E. when selecting like this:

$('#myElement').html();

So with this in mind, you can use \\S* to make wildcard selections, I.E.:

$('#myEle\\S*').each();

Stephen.



  • Patrick: I changed my code, but now I have another problem: Fatal error: Call to a member function isAvailable() on a non-object in /var/www/vhost/web/shopA
  • Stephen Gray: Hi Patrick, That first error is my fault. I had the method name for the refund() method as void() as I had copied the code from the other method!
  • Patrick: Hi Stephen, thanks for sharing your knowledge about creating a custom payment module. I need an extension for magento to handle a credit card payme

Categories