24/7 Support - 800.608.6482

Miva Merchant Community Forums

Page 2 of 6 FirstFirst 1 2 3 4 ... LastLast

Thread: Any simple examples of ajax use in module?

  1. #11
    Join Date
    Mar 2006
    Posts
    1,873

    Default Re: Any simple examples of ajax use in module?

    Yes, the MivaScript/JavaScript thing can be a bit of a head-scratcher. You have to remember that Miva Script gets executed first, on the server, and it writes the JS code out to the browser, which runs it later. If you need to get a Miva variable into the page so it's available for JavaScript, you write a mix of both, something like this:

    Code:
    var myVariable = <MvEVAL EXPR="{ g.myVariable }">;          -- for straight Miva Script
    var myVariable = &mvt:global:myVariable;;          -- for page template.  NOTE two semicolons
    HTH --
    Last edited by Kent Multer; 02-04-13 at 09:11 AM.
    Kent Multer
    Magic Metal Productions
    http://TheMagicM.com
    * Web developer/designer
    * E-commerce and Miva
    * Author, The Official Miva Web Scripting Book -- available on-line:
    http://www.amazon.com/exec/obidos/IS...icmetalproducA

  2. #12
    Join Date
    Mar 2006
    Posts
    11,187

    Default Re: Any simple examples of ajax use in module?

    There are a couple built in functions in the Miva lib. You can even study a working module, albeit quite complex, e.g. the templateorderemails.mv in the LSK. But, like Kent, most of these leave us trying to hold a snowflake. When MM5 was in beta we were give some really simple, commented examples on how render tokens worked. From those simple examples, a whole new world opened in rather short order. I have asked in another thread if Jon had a simple, commented example, like adding a product to the basket or showing the number of items in the basket, that we could study and build on. Perhaps he will chime in and this won't seem so convoluted. I spent hours chasing snowflakes one weekend and decided it would have to wait. Since Scot has brought it up, it appears I am not the only one scratching my head on this.

  3. #13
    Join Date
    May 2009
    Posts
    170

    Default Re: Any simple examples of ajax use in module?

    Quote Originally Posted by Scot - ScotsScripts.com View Post
    Thanks for all the information, appreciate your efforts.

    The flow of how things work is what is confusing me.

    Is this about right?

    1. The user selects a location from the dropdown. Upon selection, the onChange thing calls a javascript function called RegionLookup()
    2. The RegionLookup() function reads the vars (such as ajax_url) that you set up in the head of the same document the user is currently interacting with.
    3. The RegionLoookup() function calls your ajax controller function.
    4. Your ajax contoller function mysteriously calls a miva script that mysteriously sets data that mysteriously changes the form.

    Ok, I'm totally lost on how this can interact with mivascript. I can do ajax without using miva script variables.

    How is the ajax controller file called? And how does it link up with the miva script file that does the work in finding the region information for the user?

    Sorry, to be obtuse, it's like I'm trying to hold a snowflake here. Something basic I'm missing about how all this links up.
    Yeah, I've got books, looked through tons of online docs. It gets tricky.

    You've basically got the right flow. You'll mostly be working with JavaScript variables, up until you reach the "source" step.

    I'll put a mostly working example in the next post, but here is how things flow.

    1) Page is drawn with some links. The links include a javascript call to a function called Debug() and each link has a different parameter.

    2. Click on a link to call Debug().

    3. First Debug() creates an Object. This is what handles the flow of data from this page to the source of data. In this case it will be what I call the "ajax module".

    4. After a quick error check it creates the full URL of how to reach the file that is the ajax module. For example, http://localhost/test/ajax.mvc?security=MXxDeWJlcmZ1bmt8dXNlcnxkZWJ1Z3w3MjAzMWMwNjAyZjdlNm NmMjFjMmRmNDJ==&scope=s

    5. We then tell the Object that if there is a change in readystate, call GetDebugStatus. The readystate will change based on information going back and forth from this page and the ajax module.

    6. Then open a connection to the URL we made. The parameters sent are a little too out of scope for this example, but you can use "GET" or "POST", and based on that other parameters need to be set.

    7. At this point, things get turned over to the ajax module. The first step is to change the output level to "" to prevent any extra characters being sent and set the headers so the browser knows what to expect.

    8. Here you can go to town with calling functions, reading databases, etc. For this example, all I'm doing is using miva_getvarlist() and converting the output to JSON format. I don't even need to do that as I'm just going to display everything raw, but I'm going through the motions.

    9. The ajax module then outputs it, just like you would output to the screen. But instead, this is outputting a JSON formed response to the call.

    10. We now go back to the calling script and since readystate has changed, we look at GetDebugStatus().

    11. I forget what the readyState==4 means, but the status=200 is just like http status where 200 is an ok, and 404 is page not found. All we care about is 4 and 200.

    12. I then assign what comes back as stringData. There are a few ways for the javascript to 'decode' the response: .responseText is good for straight text and JSON, .responseXML is good for XML replies.

    13. Finally, I look for div id="debug", and replace its contents with what I sent from the ajax module.

    This is a really basic example, but you can build from here. Instead of putting a variable list, you could display something useful. Instead of links, use a drop down to send different values.

    I hope this helps you understand a little about how it all goes together. Obviously I can't share the security string portion, but you can get by without it. Check out the next post for code.
    Last edited by Scott McCollough; 02-04-13 at 03:15 PM.

  4. #14
    Join Date
    May 2009
    Posts
    170

    Default Re: Any simple examples of ajax use in module?

    Here is the main file:
    Code:
    <MIVA STANDARDOUTPUTLEVEL=""><MvDO FILE = "./config.mvc">
    
    
    <MIVA STANDARDOUTPUTLEVEL="text, html, compresswhitespace">
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    
    
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    
    
        <title>AJAX Testing</title>
    
    
        <script type="text/javascript">
            // setup for all ajax calls
            var ajax_url = "<MvEVAL EXPR = "{ g.site_lib_ajax }">";
    
    
            // AJAX controllers
            // Tries different methods because different browsers create the Object differently
            function createRequest() {
                try {
                    request = new XMLHttpRequest();
                } catch ( tryMS ) {
                    try {
                        request = new ActiveXObject("Msxml2.XMLHTTP");
                    } catch ( otherMS ) {
                        try {
                            request = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch ( failed ) {
                            request = null;
                        }
                    }
                }
    
    
                return request;
            }
    
    
            // Two functions for getting debug code on the screen
            function Debug(scope) {
                // Get the Object
                debugRequest = createRequest();
    
    
                // If it fails, alert us
                if (debugRequest == null)
                    alert("Unable to create request");
    
    
                else {
                    // Craft the url of where we are going to get the source of data
                    var url= ajax_url + '?security=' + debug_security_string + '&scope=' + scope;
    
    
                    // If something happens to the current state (like a drop down or a link press), call "GetDebugStatus()". Cannot included parameters
                    debugRequest.onreadystatechange = GetDebugStatus;
    
    
                    // Connect to the url we set up. Differences between "GET" and "POST", true and false, and using null are too much to explain here
                    debugRequest.open("GET", url, true);
                    debugRequest.send(null);
                }
            }
    
    
            // This is called because something happened. Trust me and check for readyState == 4 and status == 200.
            function GetDebugStatus() {
              if (debugRequest.readyState == 4) {
    
    
                if (debugRequest.status == 200) {
                    // we connected and got back informatoin, so process whatever has been sent back
                    // Assume was we got back is text. JSON or plain text uses .responseText, XML uses .responseXML
                    var stringData = debugRequest.responseText;
    
    
                    // Find <div id="debug"></div> on the page, and paste in what we got back
                    document.getElementById('debug').innerHTML = stringData;
                }
              }
            }
        </script>
        <link rel="stylesheet" href="css/default.css" />
    </head>
    
    
    <body>
        <form method="POST" action="" class="css_class" id="anyform" name="anyform">
        <h2>Test Debug</h2>
    
    
        <fieldset>
            <legend>Debug</legend>
            <p><MvEVAL EXPR = "{ Debug() }"></p>
        </fieldset>
        </form>
    </body>
    </html>
    <MvEXIT>
    
    
    <MvFUNCTION NAME = "Debug" STANDARDOUTPUTLEVEL = "text, html, compresswhitespace">
        <MvEVAL EXPR = "{ [ g.site_lib_utils ].Get_Parameters( l.parameters ) }">
    
    
        <MvASSIGN NAME = "l.parameters" MEMBER = "type" VALUE = "{ 'debug' }">
        <MvASSIGN NAME = "l.string" VALUE = "{ [ g.site_lib_utils ].Encode_Session( l.parameters ) }">
    
    
        <script type="text/javascript">
            var debug_security_string = "<MvEVAL EXPR = "{ l.string }">";
        </script>
    
    
        <p><a href="javascript:Debug('s');">Debug system variables</a></p>
        <p><a href="javascript:Debug('g');">Debug global variables</a></p>
        <p><a href="javascript:Debug('d');">Debug database variables</a></p>
        <p><a href="javascript:Debug('l');">Debug local variables</a></p>
        <p><a href="javascript:Debug('');">Clear</a></p>
    
    
        <p><div id="debug"></div></p>
    </MvFUNCTION>
    And here is the ajax module file:
    Code:
    <MIVA STANDARDOUTPUTLEVEL="">
    <MvDO FILE = "./config.mvc">
    
    
    <MvEVAL EXPR = "{ Send_Headers() }">
    <MvEVAL EXPR = "{ AJAX_Debug( g.scope ) }">
    
    
    <MvEXIT>
    
    
    <MvFUNCTION NAME = "Send_Headers" STANDARDOUTPUTLEVEL = "">
        <MvASSIGN NAME = "l.null" VALUE = "{ miva_output_header( 'Expires', 'Mon, 26 Jul 1997 05:00:00 GMT' ) }">
        <MvASSIGN NAME = "l.null" VALUE = "{ miva_output_header( 'Cache-Control', 'no-cache, must-revalidate' ) }">
        <MvASSIGN NAME = "l.null" VALUE = "{ miva_output_header( 'Pragma', 'no-cache' ) }">
        <MvASSIGN NAME = "l.null" VALUE = "{ miva_output_header( 'Content-Type', 'application/json' ) }">
    </MvFUNCTION>
    
    
    <MvFUNCTION NAME = "AJAX_Debug" PARAMETERS = "scope" STANDARDOUTPUTLEVEL = "">
        <MvASSIGN NAME = "l.scope" VALUE = "{ tolower( l.scope ) }">
    
    
        <MvIF EXPR = "{ NOT ( l.scope IN 'sgdl' ) }">
            <MvASSIGN NAME = "l.scope" VALUE = "s">
        </MvIF>
    
    
        <MvASSIGN NAME = "l.list" VALUE = "{ miva_getvarlist( l.scope ) }">
        <MvASSIGN NAME = "l.count" VALUE = "1">
        <MvASSIGN NAME = "l.debug" VALUE = "">
        <MvASSIGN NAME = "l.return" VALUE = "">
    
    
    
    
        <MvWHILE EXPR = "{ gettoken( l.list, ',', l.count ) }">
            <MvASSIGN NAME = "l.token" VALUE = "{ gettoken( l.list, ',', l.count ) }">
    
    
            <MvASSIGN NAME = "l.return" VALUE = "{ l.return $ '{' }">
            <MvASSIGN NAME = "l.return" VALUE = "{ l.return $ '"token":"' $ l.token $ '"' }">
            <MvASSIGN NAME = "l.return" VALUE = "{ l.return $ ', ' }">
            <MvASSIGN NAME = "l.return" VALUE = "{ l.return $ '"value":"' $ encodeattribute( miva_variable_value( l.scope $ '.' $ l.token ) ) $ '"' }">
            <MvASSIGN NAME = "l.return" VALUE = "{ l.return $ '}' }">
    
    
            <MvASSIGN NAME = "l.count" VALUE = "{ l.count + 1 }">
    
    
            <MvIF EXPR = "{ gettoken( l.list, ',', l.count ) }">
                <MvASSIGN NAME = "l.return" VALUE = "{ l.return $ ', ' }">
            </MvIF>
        </MvWHILE>
    
    
        <MvIF EXPR = "{ len( l.return ) }">
            <MvASSIGN NAME = "l.return" VALUE = "{ '[' $ l.return $ ']' }">
        </MvIF>
    
    
        <MvFUNCTIONRETURN VALUE = "{ l.return }">
    </MvFUNCTION>
    Last edited by Scott McCollough; 02-04-13 at 12:07 PM.

  5. #15
    Join Date
    Apr 2006
    Location
    Bellingham, WA
    Posts
    192

    Default Re: Any simple examples of ajax use in module?

    Hey Scott, that is above and beyond right there. A huge thank you for putting that together. I'll grab that code tomorrow and pour over it and see what I can come up with. But man, this is EXACTLY the kind of thing I need to learn how to do this. My personal learning method is all about taking something apart and putting it back together again... which would explain why I got in so much trouble as a little kid. Anyway, very much appreciated.

    Is that config.mvc file arbitrary? Just making sure.
    M.A.D.* since 1997

    http://www.scotsscripts.com

    *miva application developers

  6. #16
    Join Date
    May 2009
    Posts
    170

    Default Re: Any simple examples of ajax use in module?

    It's the config for setting up my work space. Works just like config in MM; sets paths, global variables, etc.

    In this case, it's what defined where the ajax.mvc file is. But you can just hardcode it to make life easy.

  7. #17
    Join Date
    May 2009
    Posts
    170

    Default Re: Any simple examples of ajax use in module?

    How goes the playing about? Make any cool advancements?

  8. #18
    Join Date
    Dec 2009
    Posts
    1,626

    Default Re: Any simple examples of ajax use in module?

    Hello forum: Looking for help.
    I am using the following POST in my AJAX routine:
    xmlhttp.open("POST","http://..............php",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("basket_id=307496&carrier=Roadrunner" );.

    It works OK with the coded constants for basket_id & carrier but I need to use my javascript variables instead.
    How should the send("....") be coded to use variables instead of constants?
    Thanks, Larry
    Last edited by wajake41; 02-19-13 at 06:25 AM.

  9. #19
    Join Date
    Mar 2006
    Posts
    1,873

    Default Re: Any simple examples of ajax use in module?

    I would think:

    xmlhttp.send("basket_id=" + b + "&carrier=" + c);

    -- where b and c are the variables. JS uses the plus sign for string concatenation (equivalent to the $ operator in Miva Script).
    Kent Multer
    Magic Metal Productions
    http://TheMagicM.com
    * Web developer/designer
    * E-commerce and Miva
    * Author, The Official Miva Web Scripting Book -- available on-line:
    http://www.amazon.com/exec/obidos/IS...icmetalproducA

  10. #20
    Join Date
    Dec 2009
    Posts
    1,626

    Default Re: Any simple examples of ajax use in module?

    Hi Kent: Thanks for the reply. I decided to go with a GET instead of a POST and after looking at an example at http://www.w3schools.com/ajax/ajax_x...quest_send.asp came up with this:
    xmlhttp.open("GET","http://www.xxx.com/mm5/UpdateCarrier.php?basket_id=" + basket + "&carrier=" +carrier + "&t=" + Math.random(),true);

    Cheers, Larry
    Last edited by wajake41; 02-19-13 at 09:12 AM.

Posting Rules

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •