Monday, July 13, 2015

jQuery Mobile Architecture: data-ajax

Most online help I find only regurgitates other websites which is frustrating and time consuming. Then, many times they speak gobbly-gook language that even I, a programmer of over 30 years cannot interpret. There are so many languages to merge that I cannot be an expert at all of them. Here, I try to keep the explanations simple for a less-than-expert programmer can understand.

That said, this article is written for the mobile website developer who understands the basics of jQuery Mobile. If you need help understanding the issues herein, then please visit the jQuery Mobile website for the background.

I had to rush to get our 100% custom website mobile ready because the major search engines would demote us if our website wasn't abiding by THEIR standards. Many points are good however, if we were to follow them to a "T", all websites would lose their branding and look the same.

jQuery mobile was my chosen helper program (aka, "higher programming language") to accomplish this goal. It was easy to understand and had nice results. However, there are some nuances that are not explained in any "getting started" with jQuery mobile tutorial.

First was how it really behaves once programmed. For example, not using data-ajax="false" created problems that were not succinctly explained in any real tutorial. Let me explain.

The mobile site was started and the links were not working. It took hours to find the answer with an explanation. Even the jQuery Mobile page listing the Data Attributes doesn't explain
  1. jQuery Mobile treats links as if they were an ajax call to another "page container", or
    <div data-role="page" id="page1">
    .
  2. Each "page" is intended to have more than one page loaded as well in the data sent to the mobile device.
What? That is crazy when you want to keep the transit time down yet load more than one page at at time, especially if your "pages"  have rich content and good images.

jQuery Mobile expects the links to be from id="page1" to id="page2" (See page container for the fule html code.).

Thus, "external" pages means anything not going a data role page <div data-role="page" id="page1">, but a new html page.

So, manually use data-ajax="false" in your <a href> tag for links not going to a data-role="page" section of the current doc.

I advise to manually do this and not globally, otherwise other places that need the data-role="ajax" will not work properly, such as forms.




Saturday, December 25, 2010

Prototype Form.serialize

A short comment that took hours of debugging only to discover it wasn't me, it was the documentation. Who would have guessed that this works on the name of the element, not the id?

Prototype Form.serialize()
This serializes the name, not the id of the element(s).

In these examples from the prototype docs, the element name is "username", "age", "hobbies". 
The form id="person-example".
$('person-example').serialize()
// -> 'username=sulien&age=22&hobbies=coding&hobbies=hiking'
$('person-example').serialize(true)
// -> {username: 'sulien', age: '22', hobbies: ['coding', 'hiking']}

Tuesday, December 21, 2010

Prototype, Ajax, JSON, Form Submission, Array Return

I know this blog is jumping from one task to another. That's because the documentation for these libraries isn't straightforward. They all expect you to be an expert OO (object oriented) programmer. I learned non-OO or more logical programming and OO is an entire new playing field. I don't like it when I pick up a book that uses notation in their syntax/code explanations without defining what that notation means. I'm talking about that stupid arrow they use among other things. There are just too many "wannabees" who don't know how to present a clear tutorial.


To create an HTML form, submit it and return an array of values from the external program, I'm using JSON to help in this task. If you've been to the JSON website, it's pretty nebulous from the introduction.

I just want to know the structure of the data JSON creates and how to decipher it.

  1. In Prototype, collect the form elements to send to the external program using Form.serialize('myform') where 'myform' is the form's id= value. You can use that as the parameter value in the options field for the Ajax.Updater.
  2. Send that to the external program with a post method so you don't send it in the url parameters (more secure for login programs).
  3. The external program can refer to the form elements from a post command using the form element id= value as the parameter. E.g., in PHP, you'd use $thefield = $_POST['theformfield'];
  4. To send the data back to the Prototype Javascript, create a hash array. E.g., in PHP, you can do something like this.

    <?
    $thefield = $_POST['theformfield'];
    // ... Some code here to select from a database or other stuff...
    $data[] = array(
    'access' => 'y',
    'firstname' => $results['db_firstname']
    );
    header('Content-type: application/x-json');
    echo json_encode($data);
    ?>


    The header tells the receiving program that the output is JSON formatted.
    Yes, the json_encode() is a PHP command to format the return data.
    The echo sends the data back to whatever script called this routine.
  5. Back at the Prototype script, you need to decipher the incoming data from the external PHP file. I did this with the following line:

            onSuccess: function(returndata) {
        var reply = returndata.responseText.evalJSON(true);

    Where evalJSON parses the incoming array and true will render the input safe.
    Okay, so now we have something back at the Prototype Javascript. What now?
  6. To use the parsed array in the Prototype Javascript, your parameter will look something like this.

           myname = reply[0].firstname;

    Now, you can use the returned array elements in the Prototype Javascript.
Why [0]?  The returned array is an associative array and we want the first value for "firstname". You might have a multidimensional array where you'd want subsequent values.

That's it for now.

    Saturday, December 18, 2010

    Ajax.Request, Ajax.Updater, Callbacks

    Ajax.Request sends data to an external program.
    Ajax.Updater just like Ajax.Request but will update id tags on your page.

    method:get - retrieve data from the external program.
    method:post - to only send data to the program.

    CALLBACK
    You'll see "callback" used in tutorials. We have 3 pieces: the html form, the Javascript, and the external program. So, who is calling back what?

    Per the jQuery folks, "a callback is a plain JavaScript function passed to some method as an argument or option."

    In proper time, the method is calling back data or event from the function within the method. Think of a mother (method) calling the kids back home (function=callback) so that they can eat dinner (data or event).

    In the following example,
    • The argument or option passed is the function in purple. 
    • This is passed onto the method, someMethod (made up - "someMethod" doesn't exist unless I program it to exist.).
    • Thus, the "callback" is the function(event) in purple.

    $("body").someMethod(
     function(someFunction) {
       console.log("clicked: " + event.target);
     }
    

    Events can be called back to give the user a chance to react when a certain state is triggered. jQuery's event system uses such callbacks everywhere:

    $("body").click(
     function(event) {
       console.log("clicked: " + event.target);
     }
    );
    

    Arguments and a context can be within a callback.
    Above, the callback is called with one argument, an event.
    The context is set to the handling element, in the above example, document.body.

    Callbacks can return data, either required or optional.

    E.g., to prevent a form submission, a submit event handler can return false:

    $("#myform").submit(
    function() {
       return false;
     }
    );

    Instead of always returning false, the callback could check fields of the form for validity, and return false only when the form is invalid.
    Thank you to the folks at jQuery for the above.

    Where am I? 
    I can return data and update one element on a page with the Ajax.Request method. How about passing several data from the external program to the page to update several different elements.

    To do that, JSON will help me parse the data without learning the syntax of XML.

    Tuesday, December 14, 2010

    Program Conflicts

    My project is complex. I'm teasing through snippets from a large program that I have. It uses Javascript libraries/higher level programs (Prototype, script.aculo.us, and a couple other "plugins" from resources such as DynamicDrive.com.).

    After intense learning and work with the program, many times debugging the wrong part, I realized that there are conflicts between jQuery and Prototype and maybe other plugins, although all are Javascript. I should have been debugging the libraries, not my programs. Where's standardization?

    CURRENT PROBLEM
    I'm trying to include a call to an external program to read a database and return the results back to the script with jQuery and Ajax. Something like "Autocomplete". This doesn't work when I simply install a working script into a page using the other higher-level Javascript programs.

    I tried the jQuery $.noConflict(); command (instead of using the dollar sign, use jQuery.whatever); however, when I use that in this haystack of program libraries, functions on the page breaks.

    I'm now attempting to use Ajax with script.aculo.us instead of the jQuery. Will this work?

    THE DIRECTION of This Blog
    I've decided to include in this blog not only syntax of these higher-level languages, but also the parameters that you can use (e.g., for the accordion, I saw "slide" and "bounce" but are there more? Can you control the speed, and if so, what exactly do you enter, a number or word?) as well as how to logically modify code snippets that you find on the Net.

    I have a few books and they all boast that they are a "comprehensive guide" (those 2 words combined don't make sense) or appear to have the dictionary of syntax for the languages. But, they don't. They all teach by example and don't really provide the nuts and bolts of the syntax. Sure, I can print what's on the Net but I don't want to waste my toner and paper on something that I should have been able to purchase.

    I want to document the syntax and parameters so that I can modify existing code. I want to be able to look at some code and quickly determine if it's jQuery, Prototype or something else. This will make modifying programs written by someone else much easier.

    Meanwhile, stay looney tuned!

    Friday, December 10, 2010

    The first lines in jQuery

    As noted before, jQuery and jQuery UI command lie within the <script> tags.
    They work in concert with html tags and css of a document.

    The first jQuery line starts with $()

    That prepares the script to be executed. Inside the parentheses, you can put whatever you need to apply the functions. It can be a tag such as $('div') where all div tags are affected by what you write there.
    Or, it can be $(document) to apply to the entire document.
    Or, $('.myclass') to apply to elements with class="myclass".
    Or, $('#myid') to apply to elements with id="myid".

    Most of the time you want to execute the jQuery/UI after the DOM is loaded so all the relevant elements are found. In that case, use ready().

    $(document).ready()

    Back to the accordion. Especially for large pages, you might include a ready command so that it can find the element to apply the accordion.

    <script type="text/javascript">
    $(document).ready(function() {
         $("#myAccordion").accordion();
    });
    </script>

    Wednesday, December 8, 2010

    The minimum jQuery Accordion.

    I'm concentrating on the jQuery UI Accordion feature for now. This needs the jQuery core library (aka, file). At this writing, the file is "jquery-1.4.4.min.js". The numbers indicate the version and I believe the accordion will work with 1.3.3+.

    It also needs the "extension, "module", "widget" or "plugin". Call it what you want but an Accordion by any other name is still an accordion. I downloaded everything in one file, or you can download just what you need here.

    When it's unzipped, you get a boatload of files. You'll just need the file,

    "jquery-ui-1.8.6.custom.min.js"

    Again, the numbers indicate the version.

    What's with the "min" in the file name?
    That compresses the file size to minimize the size for downloading, thus reducing load time. All it does is remove the extra spaces and new lines. Yes, that will reduce the size enough to make a difference. Think about that next time you create just HTML code.

    In the old Internet days, I used to remove all extraneous spaces and new lines and that did make a significant difference in load time for the users.

    The "development" copies have the new lines for readability and don't have the "min" in the file name. This allows the advanced programmers to modify the main code for their needs or to fix bugs.

    So, if you're using files with similar names with and without the "min" or different versions, then remove the older version or uncompressed files from your html document. Do this one at a time and test test test.

    In the html document <head>, I have this - IN PROPER ORDER with the core file first.

    <script type="text/javascript" src="/jqueryui/jquery-1.4.2.min.js"></script>
    <script type="text/javascript" src="/jqueryui/jquery-ui-1.8.6.custom.min.js"></script>

    You'll see the jQuery UI has "ui" in the file name whereas the "core" file doesn't.

    MINIMUM CODE for JQUERY
    The minimum code for jQuery +/- UI is (1) The

    Now, in the <head>, following the <script> links, you can insert the JQuery [UI] code for your page. Because it's really Javascript, you need to have the jQuery within the <script> tags.

    I'm installing the Accordion so the simplest code is

    <script type="text/javascript">
    $(function() {
         $("#myAccordion").accordion();
    });
    </script>

    SYNTAX or the "grammar" of the program.

    The jQuery is within the $().
    The second part is just like a Javascript function(). Yes, jQuery has functions that you program.

    $(
    function() { 

    [PUT YOUR JQUERY STUFF HERE]

    }
    );

    Of course, you can have several function()'s within this.

    It's best to keep good formatting so that you can count the open and end parentheses and braces. Sometimes, I have to count the open ones that should be the same number as the closed ones. Other times I copy the cope into a word processing doc and color the blocks of code different colors so that I have everything nested correctly.

    THE HTML PART

    Okay, now to create the html code that will function like an accordion. Here is what your document will need.
    1. An outer tag, usually a <div> tag to enclose ("wrap") the accordion.
    2. A tag that when clicked will tell jQuery to open/close (show/hide) the content. This is defaulted to <a href="#"> tag. The navigation within your outer div tag will be disabled (there are ways to enable navigation but let's deal with that later). This tag will always show.
    3. Consistent layout of the elements, usually <li> tags to define the pieces to hide and show. What's between the <li> and </li> will show/hide.
    I'm using the following and funny, the <h2> tag will act like the <a href> tag without adding anything to the jQuery function.

    <ol class="blue" id="myAccordion">
    <li id="fold1" class="section">
        <h2>My Content 1</h2>
    </li>
    <li id="fold2" class="section">
        <h2>My Content 2</h2>
    </li>
    </ul>

    That's it.
    Now, look back at the jQuery function():

    $("#myAccordion").accordion();

    The "selector" is "myAccordion" which is defined as the "id" for the <ol> tag.
    If you want 2 different accordions, just add another line to the jQuery within parentheses of $()

    $("#myAccordionTwo").accordion();

    AND don't forget to include another set of html tags with the outer element ("wrapper") with 

    id="myAccordionTwo" 

    Some of my content for each <li> tag is large and I'm trying to figure out if that causes a jerky accordion movement. I changed the <!DOCTYPE that seemed to help, but it's still jerky. I think it may be the CSS that I'm using from the original web page that I'm modifying. If I remove the CSS altogether, it's a smooth open/close. Maybe I should just start from scratch and not modify that page.