Announcement

Collapse
No announcement yet.

Any simple examples of ajax use in module?

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    #31
    Re: Any simple examples of ajax use in module?

    Originally posted by wcw View Post
    Kyle,

    The problem I am having is trying to retrieve that response. No matter what I put in the javascript on the originating page, nothing comes through. I can hard code the array you saw at http://www.pinemporium.com/mm5/merch...E&Screen=AUTO3 in the origination page and I can access a specific member. But I have not been able to pull the data off the target page successfully. This page http://www.pinemporium.com/mm5/merch...E&Screen=JSON3 creates two variables, myJSONObject and myJSONObject2. The second is hard coded and works. The first is one of the attempts I tried to read the target page. It does not work. Do you see where I went wrong?
    Bill,

    http://resurrectionwebdesign.com/miva/test.html


    Have a look at that. I fixed the issues.

    First, you have to make an AJAX call in order to get the data from the script.

    Second, don't rely on document.write. This works as the DOM is being rendered, and this is NOT what you want. You'll end up running into issues because of it. Especially if you're on a server that might be a bit laggy sometimes. Use intervals, timeouts, or other events if need be.

    Third, the reason the hardcoded version worked was because it was present in the DOM. That's why the document.write was writing what you wanted.

    If you look at the JS I provided, you'll see the most basic AJAX call in the world. It parses the JSON string and shows it in the 'pre' element, and it puts the mydata[5] in a span.

    Hope that helps!
    PCINET, LLC

    Miva Merchant Design, Development, Integration & Support
    We built the most Miva Merchant stores!
    Miva shopping cart design & integration service and our Portfolio!

    e-mail: [email protected]
    web: www.pcinet.com

    "We who cut mere stones must always be envisioning cathedrals."
    Quarry Worker's Creed

    Comment


      #32
      Re: Any simple examples of ajax use in module?

      Tim,

      Thank you. This is exactly what I was looking for. So if I wanted a drop down select list choices of some data (states, shipping methods, suggested search key words, customer names) I would build the options in the head section and assign to a variable and then display that variable as an id in a div? Or is there some ready made javascript function that does that?
      Bill Weiland - Emporium Plus http://www.emporiumplus.com/store.mvc
      Online Documentation http://www.emporiumplus.com/tk3/v3/doc.htm
      Question http://www.emporiumplus.com/mivamodu...vc?Screen=SPTS
      Facebook http://www.facebook.com/EmporiumPlus
      Twitter http://twitter.com/emporiumplus

      Comment


        #33
        Re: Any simple examples of ajax use in module?

        On your myJSONObject try this instead. myJSONObject.data.mydata[5].name. If myJSONObject is a correct JSON response, it will be a structure. data holds the response data. Try this and let me know.

        -Kyle
        [I]Kyle Hansen

        Comment


          #34
          Re: Any simple examples of ajax use in module?

          Originally posted by wcw View Post
          Tim,

          Thank you. This is exactly what I was looking for. So if I wanted a drop down select list choices of some data (states, shipping methods, suggested search key words, customer names) I would build the options in the head section and assign to a variable and then display that variable as an id in a div? Or is there some ready made javascript function that does that?
          Glad it worked. (:

          If you want to build a drop down, you're going to want to do a couple of things.

          I wrote a module to do faceted searches based on custom product attributes. It's called "Faceted Search".

          Here's how I did it. I used jQuery, but it's pretty simple.

          http://mm55.hostasaurus.com/mm5/merc...ore_Code=titus

          If you don't want to use jQuery, I'd highly recommend using the AJAXQueue object that I posted earlier in the thread.

          It gives you a dynamic Ajax caller, is very reusable, and lets you set up a queue so you aren't abandoning current requests when a new one is added. It isn't dependent upon any external libraries either.

          You don't have to have your code in the head, either. It's valid HTML to have the script tags outside of the head especially with HTML5 (which I suggest you all switch to if you haven't; it makes browser compatibility much easier).

          If you put your JS at the bottom of the body, you won't have to worry about trying to access elements in the DOM which don't exist yet. That's a major problem which needs to be addressed, specifically when dealing with JS as the "interaction layer". You don't want to hardcode "onload", on an HTML element. That's equivalent of putting inline styles with CSS on an element. It makes our job much more difficult to manage. The separation of content, presentation, and interaction can be orthogonal, which is something as developers we want to strive for.

          It makes maintaining projects so much easier and more manageable.

          So, back to the heart of what you were asking: You're going to have to write a custom function to do what you're looking for. But it's not a lot of work, and isn't very low level.

          You'll be setting the attributes of the elements to modify their ID, and you'll be modifying the innerHTML, to display contents. If you're looking to populate a select box, you'll have to add the options to it, however you see fit.

          I encourage you to look at the source of the JS on the Faceted Search link I sent. That's actually pretty heavy with JS and Ajax on the admin side too. You can do faceted searches on categories, products, and from the admin, customers too.
          PCINET, LLC

          Miva Merchant Design, Development, Integration & Support
          We built the most Miva Merchant stores!
          Miva shopping cart design & integration service and our Portfolio!

          e-mail: [email protected]
          web: www.pcinet.com

          "We who cut mere stones must always be envisioning cathedrals."
          Quarry Worker's Creed

          Comment


            #35
            Re: Any simple examples of ajax use in module?

            Excellent. I'm studying now. Thank you.
            Bill Weiland - Emporium Plus http://www.emporiumplus.com/store.mvc
            Online Documentation http://www.emporiumplus.com/tk3/v3/doc.htm
            Question http://www.emporiumplus.com/mivamodu...vc?Screen=SPTS
            Facebook http://www.facebook.com/EmporiumPlus
            Twitter http://twitter.com/emporiumplus

            Comment


              #36
              Re: Any simple examples of ajax use in module?

              Tim,

              Your post was quite instructional. I played with some of the concepts and am getting close to a simple demo for the forum. There are still some issues. I listed them in order of importance at http://www.emporiumplus.com/mm5/merc...Screen=SUGGEST You can see what is and isn't working. I did end up using jquery since it is already in use by the mobile view of this store and hundreds of others.
              Bill Weiland - Emporium Plus http://www.emporiumplus.com/store.mvc
              Online Documentation http://www.emporiumplus.com/tk3/v3/doc.htm
              Question http://www.emporiumplus.com/mivamodu...vc?Screen=SPTS
              Facebook http://www.facebook.com/EmporiumPlus
              Twitter http://twitter.com/emporiumplus

              Comment


                #37
                Re: Any simple examples of ajax use in module?

                OK, I'm working on an AJAX hookup, and I've run into a snag. I used Larry's example JS to send a request; and I've got a module in the store with the json feature. The module is writing a log file, so I know that the requests are getting through. The problem is with handling the responses.

                For now, I've create a "send test message" setup on a store page, using this JavaScript on a page template:
                Code:
                var xmlhttp;
                
                function SendTestRequest() {
                	if (window.XMLHttpRequest) {			// for IE7+, Firefox, Chrome, Opera, Safari
                		xmlhttp = new XMLHttpRequest();
                	} else {								// for IE6, IE5
                		xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
                	}
                
                	xmlhttp.onreadystatechange = XResponse;
                
                	var url = 'http://MYSTORE.com/mm5/json.mvc?Session_ID=&mvt:global:Session_ID;'
                	 + '&Store_Code=&mvt:global:Store_Code;'
                	 + '&Function=Module&Module_Code=MYMODULE&Session_Type=runtime&Module_Function=TEST';
                
                	xmlhttp.open('GET', url, true);
                	xmlhttp.send();
                }
                
                function XResponse()  {
                	if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
                		document.getElementById('TestResponse').innerHTML = xmlhttp.responseText;
                		alert('Test request done, text: ' + xmlhttp.responseText);
                //	} else {
                //		alert('AJAX state=' + xmlhttp.readyState + ', status=' + xmlhttp.status);
                	}
                }
                Then I have a button on the page to trigger SendTestRequest(), and a <span> element with an id of "TestResponse" to accept the result.

                When I run this as-is, I get no response at all when I click the button, even though the module's log file shows that the requests are coming in. When I un-comment that extra alert in the callback function, I find that it's called a couple of times, and the readyState does get to 4, indicating completion; but the status is always zero. That's on Firefox; On IE, it just gets an "access denied" error.

                I've tried this on several different browsers on two different computers.

                Any thoughts?

                Thanks --
                Last edited by Kent Multer; 03-11-13, 12:38 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

                Comment


                  #38
                  Re: Any simple examples of ajax use in module?

                  Hi Kent:
                  What works for me is to have the onreadystatechange function within the AJAX function like this:

                  function AJAXGetCustomer(email,zipcode){
                  var xmlhttp;
                  if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
                  xmlhttp=new XMLHttpRequest();
                  } else { // code for IE6, IE5
                  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                  }
                  xmlhttp.onreadystatechange=function() {
                  if (xmlhttp.readyState == 4) {
                  if(xmlhttp.status == 200){
                  var cust = xmlhttp.responseText;
                  reply(cust);
                  } else {
                  var cust = " E^";
                  reply(cust);
                  }
                  }
                  }

                  var msg = "email=" + email + "&zipcode=" + zipcode + "&t=" + Math.random();
                  xmlhttp.open("POST","http://dev.rvparksupplies.com/mm5/Sh...omer.php",true);
                  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
                  xmlhttp.send(msg);
                  }
                  function reply(cust) {
                  // alert(cust);
                  var err_flag = trimString(cust.substr(1,2));
                  var cust_flds = cust.split("^"); // put customer fields into an array
                  var string_end = cust_flds[25];

                  etc.etc.
                  }
                  Larry
                  Larry
                  Luce Kanun Web Design
                  www.facebook.com/wajake41
                  www.plus.google.com/116415026668025242914/posts?hl=en


                  Comment


                    #39
                    Re: Any simple examples of ajax use in module?

                    Hi Kent: Looking closer at your reply, I don't think my previous post is pertinent to your problem. You are receiving responses so I think the problem is with the server program.
                    I'm trying to remember but I think i may have gotten the same status access denied because my server program wasn't using a GET when it received a AJAX GET message. With PHP, I have been receiving the URL's parms with either a $_GET or $_REQUEST. Does Miva have some way to receive the parms in the URL as a GET?
                    Larry
                    Last edited by wajake41; 03-11-13, 07:21 AM.
                    Larry
                    Luce Kanun Web Design
                    www.facebook.com/wajake41
                    www.plus.google.com/116415026668025242914/posts?hl=en


                    Comment


                      #40
                      Re: Any simple examples of ajax use in module?

                      Right, giving the callback function a name and separating it out from the main code doesn't affect the behavior. I just rearranged it for clarity; those functions-within-functions can get confusing sometimes.

                      Miva receives GETs the same as POSTs, by turning all the passed parameters into global variables. I know that all the data is being passed to Miva, because Module_JSON is being called correctly, and the module is writing into its log file for every incoming request. The problem is on the other side of the transaction.

                      I wonder if there's some special HTTP header that my module needs to send before it starts outputting other text? Content-Type, maybe? I saw a few of those in the LSK, but I'm not sure if the apply in this case.

                      Thanks --
                      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

                      Comment


                        #41
                        Re: Any simple examples of ajax use in module?

                        Hi Kent: I should have knocked on wood after I saw your post about the 500 response. I started getting the same this evening, found it was a program error, my program was aborting.

                        Did you find a solution for your 500?
                        Larry
                        Larry
                        Luce Kanun Web Design
                        www.facebook.com/wajake41
                        www.plus.google.com/116415026668025242914/posts?hl=en


                        Comment


                          #42
                          Re: Any simple examples of ajax use in module?

                          Here is another simple javascript routine demonstrating JSON in Miva Merchant. This one differs from the previous one I posted in that it uses an onclick event rather than a keyup. My onclick script was full of errors and Brennan Heyde from Miva cleaned it up and got me on the right track. I haven't completely studied the shipping estimator yet so I don't know if the address data is saved or if you have to enter it every time. So I used the old shipcalc example where the address (zip, state, country) is saved in the basket database for re-use.

                          Head tag tab of the store
                          Code:
                          <script type="text/javascript" src="../mobile/js/jquery-1.6.1.js"></script>
                          Head section of the BASK page or other page you have the estimator on. This retrieves the JSON data and formats it into
                          the display you want it for.
                          Code:
                          <script type="text/javascript" charset="utf-8">
                          	var reseturl = '<a href="http://www.emporiumplus.com/mm5/merchant.mvc?Screen=BASK&Store_Code=wcw&tkship=2">';
                          	var shipzip = '&mvte:global:basket:ship_zip;';
                          	var shipstate = '&mvte:global:basket:ship_state;';
                          	var shipcountry = '&mvte:global:basket:ship_cntry;';
                          	jQuery(document).ready(function() {
                          	    $('#getdata-button').click(function() {		
                          		$.getJSON('http://www.emporiumplus.com/mm5/merchant.mvc?Screen=SHIPCALCJSON&Store_Code=wcw&tkship=1',function(j){
                          			if (!j)
                          			{
                          			document.getElementById("getdata-button").hidden = false;
                          			}
                          			else
                          			{
                          			document.getElementById("getdata-button").hidden = true;
                          			}
                          	        	$('#content').empty();
                          		            var stuff = '<table cellpadding="1" cellspacing="0"><tr><td colspan="2" bgcolor="#d3d3d3"><b>Shipping to:</b> ' + reseturl + shipstate + ' ' + shipzip + ' ' + shipcountry + '</a></td></tr>';
                          				stuff += '<tr><td bgcolor="#d3d3d3">Shipping Method</td><td bgcolor="#d3d3d3" align="right">Cost</td></tr>';
                          				for (var i = 0; i < j.length; i++) {
                          					stuff += '<tr><td>' + j[i].name + '</td><td align="right">' + j[i].amount + '</td></tr>';
                          				}
                          			stuff += '</table>';
                          	            	$('#content').append(stuff);    
                          			});	 //close getJSON request
                          	    }); // Close click function
                          	}); // Close document.ready
                          </script>
                          Body of the page. This shows the regular button and page for a calculator if not all of the data is known. If it is known when the
                          page loads, it displays a button which runs the javascript function.
                          Code:
                          <mvt:if expr="NOT l.settings:basket:empty">
                          <mvt:if expr="g.basket:ship_zip AND g.basket:ship_state AND g.basket:ship_cntry AND (g.TKShip NE 2) AND (NOT g.shipform)">
                          <a href="#" id="getdata-button" onClick="return false;">
                          <input type="submit" value="Calculate Shipping" class="button" /></a>
                          <div id="content">
                          </div>
                          <mvt:else>
                          <mvt:item name="toolkit" param="render|SHIPCALC" /> 
                          </mvt:if>
                          </mvt:if>
                          Last edited by wcw; 03-11-13, 07:50 PM.
                          Bill Weiland - Emporium Plus http://www.emporiumplus.com/store.mvc
                          Online Documentation http://www.emporiumplus.com/tk3/v3/doc.htm
                          Question http://www.emporiumplus.com/mivamodu...vc?Screen=SPTS
                          Facebook http://www.facebook.com/EmporiumPlus
                          Twitter http://twitter.com/emporiumplus

                          Comment


                            #43
                            Re: Any simple examples of ajax use in module?

                            Originally posted by wajake41 View Post
                            Hi Kent: I should have knocked on wood after I saw your post about the 500 response. I started getting the same this evening, found it was a program error, my program was aborting.
                            Did you find a solution for your 500?
                            Larry
                            I'm not getting 500's. I'm getting a zeroes in the "xmlhttp.status" property, which isn't a valid HTTP status code at all. It looks as if the browser is sending the request to the server properly, but something is going wrong with the reply. Again, that's Firefox. IE just gives me an "access denied" error -- not in the JS, but in its usual error display.

                            No one answered my earlier question about HTTP headers. Larry, in your PHP scripts that send AJAX replies, do you have to do anything special to make sure that the output of your script will be accepted by the browser?

                            Thanks --
                            Last edited by Kent Multer; 03-11-13, 08:39 PM.
                            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

                            Comment


                              #44
                              Re: Any simple examples of ajax use in module?

                              Hi Kent: Nothing special in the PHP program. I just do a PHP "echo" to return the response. I do include the "setRequestHeader" when I send the AJAX message as you can see here:.
                              xmlhttp.open("POST","http://dev.myprogram.com/mm5/myPHPprogram.php",true);
                              xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
                              xmlhttp.send(msg);

                              Larry
                              Larry
                              Luce Kanun Web Design
                              www.facebook.com/wajake41
                              www.plus.google.com/116415026668025242914/posts?hl=en


                              Comment


                                #45
                                Re: Any simple examples of ajax use in module?

                                Hi Kent: I did the Google on xmlhttp.status = 0 and some people were attributing it to a firewall problem. If you solved the problem, please post what you found.
                                Regards, Larry
                                Larry
                                Luce Kanun Web Design
                                www.facebook.com/wajake41
                                www.plus.google.com/116415026668025242914/posts?hl=en


                                Comment

                                Working...
                                X