10 Replies Latest reply on Sep 19, 2016 12:04 AM by VectorP

    jQuery code won't run in phonegap

    micha889

      Someone provided me with a jsfiddle code https://jsfiddle.net/adeneo/2uod274d/

      It works well within jsfiddle, but when I put the code into my Xcode and modified it to integrate into my code and run it in the simulator, the code won't work at all (i.e no data is stored in local storage)

       

      I'm building an app for iOS using phonegap. JS:

           <script type="text/javascript" src="cordova.js"></script>
        
      <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
        
      <script type="text/javascript" src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>

        
      <script type="text/javascript">
        document.addEventListener("deviceready",onDeviceReady,false);

        function onDeviceReady() {

        document.getElementById("btnSave").addEventListener("click",saveData,false);
        document.getElementById("btnShow").addEventListener("click",showData,false);
      }

        function saveData(){
        var data = window.localStorage.getItem("date");

        var dates = data ? JSON.parse(data) : [];

        dates.push( new Date() );

        window.localStorage.setItem("date", JSON.stringify(dates));

        alert("Your data is stored");
        }

        function showData() {
        var data = JSON.parse(window.localStorage.getItem("date"));
        console.log(data);
        $('#res').html(JSON.stringify(data));
        $(this).html('Update result');
        }

      </script>

      html:

      <button id="btnSave"> Save Data </button>

        
      <button id="btnShow"> Show Data </button>

      I'm not sure what is going on because the code runs well in jsfiddle, but for some reason just won't run in my phonegap.

       

      My phonegap version 5.3.6, cordova version 5.3.3

       

      Message was edited by: Fang Kerry, I've added my full code so it's easier to see the problem (if any)

        • 1. Re: jQuery code won't run in phonegap
          VectorP Level 4

          - How do you whitelist the external sources?

          - You wrote: the code won't work at all (i.e no data is stored in local storage). Where exactly doesn't your code 'work'? Is your function onDeviceReady executed at all? If so, are the click eevents caught? If so, are the callback functions executed? If so, could it be that the data are handled correctly, and they are just not displayed? What does your console.log(data);  show?

          Storing data in localStorage is the very ultimate result...if you don't get that result, you should backtrack until you find the spot where the first error takes place.

          • 2. Re: jQuery code won't run in phonegap
            micha889 Level 1

            Thanks for the response. I run the app again in my iPad, and opened web inspector. And when I click on "Save Data", an error occurred:

             

            JSON Parse error: Unexpected identifier "Sat"

             

            pointing to the line: var dates = data ? JSON.parse(data) : [];

             

            Do you know why the error occurred? My onDeviceReady function does runs as I do have other codes in there that executes without any problem. I think the problem is within the saveData() function as the app works if I change the code within the saveData() to something simpler:

             

            function saveData()

            { var date= new Date();

            window
            .localStorage.setItem("date", JSON.stringify(date));
            alert
            ("Your data is stored");
            }

             

            So here the date will be stored in the local storage, however I can't use this because it overwrites the date when the button is clicked again.

             

            • 3. Re: jQuery code won't run in phonegap
              VectorP Level 4

              The 'Sat' is most likely the abbreviation of 'Saturday'. I assume that the value of the date in the JSON object is not wrapped in quotes, which makes the object invalid.

              Unfortunately, you didn't post the exact contents of the Json object, so I can't tell for sure.

              • 4. Re: jQuery code won't run in phonegap
                micha889 Level 1

                VectorP wrote:

                 

                The 'Sat' is most likely the abbreviation of 'Saturday'. I assume that the value of the date in the JSON object is not wrapped in quotes, which makes the object invalid.

                Unfortunately, you didn't post the exact contents of the Json object, so I can't tell for sure.

                Sorry but what do you mean by the exact contents of JSON object? I'm just storing the current date and time into the local storage? If you are saying what are the current date value stored within the local storage it's:

                date"2016-09-17T12:41:13.814Z"

                I generated that using this code:

                 

                function saveData()

                { var date= new Date();

                window
                .localStorage.setItem("date", JSON.stringify(date));
                alert
                ("Your data is stored");
                }

                • 5. Re: jQuery code won't run in phonegap
                  micha889 Level 1

                  I run the app again, and for some reason the previous error is gone when I click "Save Data", and this time the error changed to: TypeError: dates.push is not a function. (In 'dates.push( new Date() )', 'dates.push' is undefined)

                  • 6. Re: jQuery code won't run in phonegap
                    VectorP Level 4

                    Then 'dates' is not an array at that point.

                    Most likely, while testing, you stored something in localStorage which was not null, but couldn't be JSON.parsed, either.

                     

                    But let's get back to your original question, which titles:

                    jQuery code won't run in phonegap

                    What jQuery code doesn't run?

                    • 7. Re: jQuery code won't run in phonegap
                      kerrishotts Adobe Community Professional

                      jQuery has nothing to do with this, as far as I can tell (so not sure why it's in your title). The problem is that the result of JSON.parse(data) is not an array like you think it is, it's a string. String's don't respond well to `push`. I get that when using this code in jsfiddle it somehow is coming out as an Array, but I think this must be because of something jsfiddle is doing. When I do the same commands in my browser's console, I get a string, not an Array, hence your issue.

                       

                      Instead:

                       

                      function deserializeDates() {
                          var data = window.localStorage.getItem("date");
                          var dates = []; // worst case, we'll return an empty array.
                          if (data) {
                              try {
                                  dates = JSON.parse(data);
                                   // handle the case that dates is a single item and not an array
                                  if (!(dates instanceof Array)) {
                                      dates = [dates];
                                  }
                              } catch (err) {
                                   // the stored dates failed to parse for some reason; you might want to do something about it
                                   console.log("Failed to parse " + data);
                               }
                          }
                          return dates;
                      }
                      
                      function serializeDates(dates) {
                          window.localStorage.setItem("date", JSON.stringify(dates));
                      }
                      
                      function saveData(){
                           var dates = deserializeDates();
                          dates.push( new Date() );
                           serializeDates(dates);
                          alert("Your data is stored");
                      }
                      
                      function showData() {
                           var dates = deserializeDates();
                          console.log(dates);
                          ...
                        }
                      
                      • 9. Re: jQuery code won't run in phonegap
                        micha889 Level 1

                        kerrishotts wrote:

                         

                        jQuery has nothing to do with this, as far as I can tell (so not sure why it's in your title). The problem is that the result of JSON.parse(data) is not an array like you think it is, it's a string. String's don't respond well to `push`. I get that when using this code in jsfiddle it somehow is coming out as an Array, but I think this must be because of something jsfiddle is doing. When I do the same commands in my browser's console, I get a string, not an Array, hence your issue.

                         

                        Instead:

                         

                        1. functiondeserializeDates(){
                        2. vardata=window.localStorage.getItem("date");
                        3. vardates=[];//worstcase,we'llreturnanemptyarray.
                        4. if(data){
                        5. try{
                        6. dates=JSON.parse(data);
                        7. //handlethecasethatdatesisasingleitemandnotanarray
                        8. if(!(datesinstanceofArray)){
                        9. dates=[dates];
                        10. }
                        11. }catch(err){
                        12. //thestoreddatesfailedtoparseforsomereason;youmightwanttodosomethingaboutit
                        13. console.log("Failedtoparse"+data);
                        14. }
                        15. }
                        16. returndates;
                        17. }
                        18. functionserializeDates(dates){
                        19. window.localStorage.setItem("date",JSON.stringify(dates));
                        20. }
                        21. functionsaveData(){
                        22. vardates=deserializeDates();
                        23. dates.push(newDate());
                        24. serializeDates(dates);
                        25. alert("Yourdataisstored");
                        26. }
                        27. functionshowData(){
                        28. vardates=deserializeDates();
                        29. console.log(dates);
                        30. ...
                        31. }

                        This works! Thanks so much!!! I've been spending the past few days trying to figure out what went wrong and it's just so frustrating... May I ask one more thing, the date and time in my local storage is stored in this format: 2016-09-18T23:25:17.123Z, but this is not my timezone as I live in Australia and it's already the 19th Sept now, have no idea what time zone this is, is there a way to change it? I thought it should automatically display the date and time based on my current location?

                        • 10. Re: jQuery code won't run in phonegap
                          VectorP Level 4

                          The Z is Zulu time (generally spoken also GMT and UTC).

                          Coordinated Universal Time - Wikipedia, the free encyclopedia

                           

                          You are working in Javascript, client side. That works off-line and without GPS. So, how should your Javascript application know where you are and what your current Timezone is? How should your Javascript application react when you cross a Timezone border?

                           

                          If you want a current timezone, based upon the user's real location, then you need to:

                          - pick up that location in your application

                          - look up the time zone for that paticular location

                          - convert the Z zone to the user's zone.

                          - ....and then it gets even nicer if you want to consider daylight saving time, too

                           

                          Luckily, there's a nice Class to work with:

                          Date.prototype.getUTCDate() - JavaScript | MDN