0

I've got a little JSONP / jQuery/Ajax Problem.

I use PHP script to get some data from a MySQL-Database and display them on a page.

This is the PHP code I use:

header('Content-type: application/json');

$server = "localhost";
$username = "XXXXX";
$password = "XXXXX";
$database = "XXXXX";

$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);

$sql = "SELECT id, vorname, nachname, beruf FROM myvalues";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());

$records = array();

while($row = mysql_fetch_assoc($result)) {
    $records[] = $row;
}

mysql_close($con);

echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';

The result I get is the following:

<br />
<b>Notice</b>:  Undefined index: jsoncallback in <b>C:\xampp\htdocs\jsontest\lcl_request_grp.php</b> on line <b>23</b><br />
([{"id":"1","vorname":"Hallo","nachname":"Bayer","beruf":"Student"},{"id":"2","vorname":"Romy","nachname":"Bayer","beruf":"Bank"},{"id":"3","vorname":"Walter","nachname":"Bayer","beruf":"Pensionist"},{"id":"4","vorname":"Ilaria","nachname":"Pirruccio","beruf":"Kleinkindererzieherin"},{"id":"5","vorname":"Marcel","nachname":null,"beruf":"Maurer"},{"id":"6","vorname":"Hans","nachname":"Muster","beruf":"Bauer"},{"id":"7","vorname":"Luca","nachname":"Stomeo","beruf":"informatiker"},{"id":"8","vorname":"Joan","nachname":"Lehmann","beruf":"Hausfrau"},{"id":"9","vorname":"Tanja","nachname":"Blumer","beruf":"Coiffeuse"},{"id":"10","vorname":"Vorname","nachname":"Nachname","beruf":"Internetseite"}]);

So far it works pretty good. Except the two first lines at the beginning.

This is my html to get out the information of the php-page:

<html>
<head> 
    <title>Produktkonfigurator</title> 

    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.1/jquery.mobile-1.2.1.min.css">
    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.2.1/jquery.mobile-1.2.1.min.js"></script>

        <script type="text/javascript">
        $(document).ready(function() {
            var output = $('#output');
            $.ajax({
                url: 'http://localhost/jsontest/lcl_request_grp.php',
                //url: 'http://qvixxtest.funpic.de/jsontest/request_grp.php',
                dataType: 'jsonp',
                data: 'data',
                jsonp: 'jsoncallback',
                timeout: 5000,
                success: function(data, status){

                    var html = '';
                    $.each(data, function(i,item){
                        //html += '<li><a href="#">' + item.bezeichnung_de + '</a></li>';
                        html += '<li><a href="#">' + item.vorname + '</a></li>';
                    });
                    $('#mylist').append($(html));
                    $('#mylist').trigger('create');    
                    $('#mylist').listview('refresh');
                    $('#online-offline').html("Diese Daten wurden online abgerufen");
                    // Daten im LocalStorage als JSON-String speichern
                    localStorage["liste"] = html;
                },
                error: function(){
                    html = ''
                    html = localStorage["liste"];
                    $('#mylist').append($(html));
                    $('#mylist').trigger('create');    
                    $('#mylist').listview('refresh');
                    $('#online-offline').html("Diese Daten wurden offline abgerufen");
                }
            });
        });
        </script>

</head>
<body>

<div data-role="page">
    <div data-role="content">

        <p align="center">Vielen Dank, dass sie den Produktkonfigurator Nutzen!</p>
        <h3 id="online-offline" style="color: red; text-align: center;"></h1>
        <ul data-role="listview" data-inset="true" id="mylist"></ul>

    </div>
</div>

</body>

</html>

The result is a list of all 'Vorname'-Values. The List-html is saved into the localstorage. If a connection isn't possible the script reuses the locally-saved html to build the list. Connection -> new List no connection -> old list from localstorage

What I want now is to save the whole JSONP-result-string in localstorage to reuse it whitout requesting the php-file every time.

All my tries resulted in [Object] or 'undefined'. A solution i thought about is to 'rebuild' the JSON-String in JS but i Think there should be a better solution.

Thanks for your answers!

bayerphi
  • 325
  • 1
  • 4
  • 12

1 Answers1

0

I store objects and arrays in the localStorage using :

json = [{"id":"1","vorname":"Hallo","nachname":"Bayer","beruf":"Student"},{"id":"10","vorname":"Vorname","nachname":"Nachname","beruf":"Internetseite"}];

    localStorage['json'] = JSON.stringify(json);

This stores an array or object as a string. Then return the string to JS object or array using :

json = eval("("+localStorage['json']+")");

This works perfectly with the JSONP list sent by your PHP. I tried, it's now stored in my LocalStorage.

Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • But how can I get the whole String? If I had the whole String returned by the PHP I could do it. – bayerphi Sep 16 '13 at 10:32
  • What do you mean "How can I get the whole string"? Well whatever your PHP sends you back, you can store it this way. success : function(json){ localStorage['json'] = JSON.stringify(json); } – Jeremy Thille Sep 21 '13 at 13:45