Showing posts with label JSON. Show all posts
Showing posts with label JSON. Show all posts

Wednesday, 12 September 2018

Load JSON data with jQuery and PHP - Radio Buttons

A while back I wrote a series dealing with loading content and JSON data with jQuery and AJAX which culminated in the post "Load JSON data with jQuery, PHP and MySQL" which brought all the techniques together and loaded JSON data into select boxes when the first was changed. I was recently asked how to do this using radio buttons instead, which I show how to do in this post.

Previous posts

Working example

The example below doesn't actually make a JSON call with jQuery but does illustrate how the example detailed in this post works.
Fruit:    
Variety:  

HTML Code

The initial HTML code looks like this:
<form>
    <div>
        <strong>Fruit:</strong>
        <label><input type="radio" name="fruitName" value="Apple" checked="checked" />Apple</label>
        <label><input type="radio" name="fruitName" value="Banana" />Banana</label>
        <label><input type="radio" name="fruitName" value="Orange" />Orange</label>
        <label><input type="radio" name="fruitName" value="Pear" />Pear</label>
    </div>
    <div>
        <strong>Variety:</strong>
        <span id="varieties"></span>
    </div>
</form>
The set of fruit names was already populated on the server-side and the default set of varieties could be too; I have chosen to populate them with Javascript in this example.

jQuery Code

The jQuery code needs to initially populate the variety span with radio buttons based on the value of the selected fruit radio button. It then needs to update the variety if the fruit selection changes.
Assuming the PHP script to fetch the fruit is at /fruit-varieties.php do this:
function populateFruitVariety() {

    var fruitName = $('input[name=fruitName]:checked').val();

    $.getJSON('/fruit-varities.php', {fruitName: fruitName}, function(fruit) {

        var html = '';
        $.each(fruit[fruitName], function(index, array) {
            html = html + '<label><input type="radio" name="variety" value="' + array['variety'] + '" />' + array['variety'] + '</label> ';
        });
        $('#varieties').html(html);

    });

}

populateFruitVariety();
$('input[name=fruitName]').change(function() {
    populateFruitVariety();
});
The $.getJSON line retrieves the data via an AJAX request, passing it the currently selected fruit name. The data is then looped through (it's an array containing the index 'variety' containing the fruit variety name) and added to an html string, which is then finally injected into the web page's #varieties span replacing what was previously there.

Caching issues

Internet Explorer and Firefox will cache the subsequent requests made to the same fruit name but the other browsers might not, requesting them again each time. There are a couple of ways to solve this which is covered in another post.

jQuery JSON Ajax requests and caching

Last week I wrote how to load JSON data with jQuery, PHP and MySQL, noting at the end that there can be some caching issues which may or may not be a problem depending on your implementation. This post looks at which browsers cache the requests, and how to make sure it is not cached.

Which browsers cache the request?

If you do something like this to load the JSON data:
$.getJSON('/path/to/my/json/file.js', function(data) {
    // do something now that the data is loaded
});
then the browser will load the JSON file and then run the function to do something with it.
The following notes about which browsers cache and don't cache are accurate from my own testing in current released versions of the browsers as at March 12th 2010.
If you run the function again on the same page without reloading the page, the following browsers will not request the JSON file again, and nor will they on subsequent page requests:
  • Firefox
  • Internet Explorer
The following browsers will request the file again each time, whether it's requested for a second time on the same page or on a page loaded later:
  • Opera
  • Safari
And finally, the following will request the file again each time if it's requested on the same page, but will load it from the cache when requested from subsquent pages:
  • Chrome
When they don't cache, they still won't even if using $.ajax to fetch the data and setting the cache property to true.

How to make sure the file is not cached

Should you need to ensure the JSON file is loaded again each time it is requested without caching (in the event you need to load the same file again on the same page), then you need to provide either a unique URL or use a $.ajax call and set the cache property to false.
To use $.getJSON and prevent caching, add a unique value to the query string using the Date() object as shown below. Each time the function is run the url will be different.
$.getJSON('/path/to/my/json/file.js?' + new Date().getTime(), function(data) {
    // do something now that the data is loaded
});
To use the $.ajax function instead, do this:
$.ajax({
    cache: false,
    success: function(data) {
        // do something now that the data is loaded
    },
    url: '/path/to/my/json/file.js'
});
Another way to change the caching behavior is to change the AJAX settings like so:
$.ajaxSetup({ cache:false });
And then do the $.getJSON() request in the normal way. Be aware that this will affect all subsequent AJAX requests unless changed again. Thanks to Boiss for adding this tip in the comments below.

How to make sure the file is cached

The easiest method to make sure the file is cached is to deal with it on the server-side. I'll show how to do this using Apache's mod_expires and also with PHP in posts coming up over the next few days.
It can also be cached on the client side a few different ways, including using jQuery's data method or the new sessionStorage and localStorage capabilities of HTML 5. I'll cover these in subsequent posts as well.
 

Related posts:

Converting an array to JSON data with PHP

PHP's json_encode function converts a PHP variable into a JSON string which can then be used in Javascript, for example using jQuery's JSON functions. This is easy to do and I'll be combining the two together in tomorrow's post to show how to fetch data from a MySQL database with PHP into Javascript via JSON.

Converting a PHP array to JSON

Assuming data had been selected from the database using my example fruit table into a multidimensional array with PDO::fetchAll using "SELECT * FROM fruit WHERE name = 'Apple'", the array would look like so:
Array
(
    [0] => Array
        (
            [fruit_id] => 1
            [name] => Apple
            [variety] => Red Delicious
        )

    [1] => Array
        (
            [fruit_id] => 6
            [name] => Apple
            [variety] => Cox's Orange Pippin
        )

    [2] => Array
        (
            [fruit_id] => 7
            [name] => Apple
            [variety] => Granny Smith
        )

)
If the array was called $data, to convert and echo to the browser as JSON do this:
echo json_encode($data);
The resulting JSON encoded string would look like so:
[{"fruit_id":"1","name":"Apple","variety":"Red Delicious"},{"fruit_id":"6","name":"Apple","variety":"Cox's Orange Pippin"},{"fruit_id":"7","name":"Apple","variety":"Granny Smith"}]

Version requirements and further reading

PHP 5.2.0 or higher comes bundled with the JSON functions. Prior to 5.2.0 the PECL extension needs to be installed. Read the PHP JSON manual pages for more details.
There will be another post tomorrow which ties together three posts over the last few days and shows how to load JSON data with jQuery, PHP and MySQL.
 

Related posts:

Load JSON data with jQuery

JSON data can be retrieved using AJAX from a server either using jQuery's .ajax() function or the shorthand $.getJSON() function. If you have retrieved a JSON string without having jQuery decode it automatically using one of these functions, the string can also be parsed into a regular data array using the $.parseJSON() function.

$.getJSON()

The easiest way to load some JSON data in jQuery is with the $.getJSON() function and using the callback to do something with the data. If the URL to get the JSON data is at /json/somedata.json then it can be retrieved and something done with it like so:
$.getJSON('/json/somedata.json', function(data) {
    // do something with the data here
});

$.ajax()

The above is a shortcut to the $.ajax() method. If you needed to set some of the other AJAX properties use the $.ajax() function instead. The following is the equivilent of the above:
$.ajax({
    dataType: 'json',
    success: function(data) {
        // do something
    },
    url: '/json/somedata.json'
});

$.parseJSON();

Finally, a JSON encoded string can be converted to a Javascript array using $.parseJSON(). If "string" in the example below contains a JSON string it can be converted to an array like so:
data = $.parseJSON(string);
The string could potentially be retrived using AJAX from the server as plain text, and then converted to an array like this, although normally you would use the dataType 'json' and leave it up to jQuery to do it for you:
$.ajax({
    dataType: 'text',
    success: function(string) {
        data = $.parseJSON(string);
        // do something
    },
    url: '/json/somedata.json'
});

Encoding JSON data with PHP

This post has been followed up showing how to load JSON data with jQuery, PHP and MySQL.

Related posts:

Wednesday, 5 September 2018

JSON store does not return data correctly

I've had this problem for awhile now, but I keep narrowing down the issue and I think I have main problem figured out now. While my JSONstore calls to the PHP correctly, and firebug does give me the correct data back from the database, it will not display in my grid.

I have a grid with only 2 columns a date, and an entry from a log. When I take out the log entry, the grid will display the date just fine, and when I just create an array with static data from the log then it will display fine in the grid as well. I think my JSONstore just isn't parsing the data correctly from the mysql tables.
My code is:
  var logStore = new Ext.data.JsonStore({
    autoLoad: true,
    url: 'inc/interface/config.php?list=messages',
    root: 'dates',
    idProperty: 'ID',
    fields: ['ID', 'ReceivedAt', 'Message'],
    listeners: {
                loadexception: function() {
                    console.log('load failed -- arguments: %o', arguments);
                }
        }
}); 

  var logGrid = new Ext.grid.GridPanel({
        region: 'center',
        store: logStore,
        colModel: new Ext.grid.ColumnModel({
            columns: [{
                id: 'received',
                header: 'Received',
                dataIndex: 'ReceivedAt',
                width: 250
            },{
                id: 'message',
                header: 'Logs',
                dataIndex: 'Message',
                width: 750
            }]
        })
    });

An example of the log entry it's pulling is:
| Apr 9 00:00:02 dh1 dhcpd: Added new forward map from nfxxxxich-PC.wifi-uhs.osu to 10.xxx.xx.248 |
| Apr 9 00:00:02 dh1 dhcpd: added reverse map from 248.xxxx.xxx.10.in-addr.arpa. to nxxxxxh-PC.wifi-uhs.osu |
| Apr 9 00:00:02 dh1 dhcpd: DHCPREQUEST for 10.xxx.xxx.248 from 00:x:5c:x:8c:xx (nxxxxh-PC) via 10.xxx.xxx.254 |
| Apr 9 00:00:02 dh1 dhcpd: DHCPACK on 10.X.XX.248 to 00:X:5c:X8c:XX (nXXXich-PC) via 10.193.XX.XXX |
| Apr 9 00:00:02 dh1 dhcpd: Added new forward map from XX.wifi-uhs.XXX to 10.X.X.242 |
| Apr 9 00:00:02 dh1 dhcpd: added reverse map from 242.X.193.X.in-addr.arpa. to X.wifi-uhs.XXX |
| Apr 9 00:00:02 dh1 dhcpd: DHCPREQUEST for 10.X.X.242 from 00:X:ce:X21:63 (elena) via 10.X.X.254 |
| Apr 9 00:00:02 dh1 dhcpd: DHCPACK on 10.193.XXX.XX to 00:X:ce:X:21:63 (elena) via 10.X.X.254 |
| Apr 9 00:00:02 dh1 dhcpd: Added new forward map from P305-XXX.wifi-uhs.XXX to 10.193.X.X |
| Apr 9 00:00:02 dh1 dhcpd: added reverse map from 21.241.X.X.in-addr.arpa. to P305-XXXX.wifi-uhs.XXX |

There are various different characters and tabs between the date, dh1, and the log entry itself. Could there be an issue with escaping these characters? I'm just not quite sure how it's done. Any help would be appreciated.

You haven't specified the type and format in fields. And I'm guessing that your php json implementation doesn't generate a javascript Date object.
So... try returning an unix timestamp and use this as fields:
fields: [
  {name: 'ID', type: 'int'},
  {name: 'ReceivedAt', type: 'date', dateFormat: 'Y-m-d H:i:s'},
  'Message'
]

Optionally you could also specify a dateFormat next to the type: 'date'. See the documentation for more info: http://www.sencha.com/deploy/dev/docs/?class=Ext.data.Field

Wednesday, 29 August 2018

PHP echoing the multidimensional array as JSON

I am trying to display all the users in my database in JSON form in an array. This is what I have - but it is not in the form that I want it in

{
  "username": [
    "bobgreen",
    "jacksmitd",
    "samson",
  ]
  "forename": [
    "Bob",
    "Jack",
    "Sam",
  ],
  "surname": [
    "O'Conor",
    "Smitd",
    "Son",
  ]
}

This is my code that gives this output...
if(mysqli_num_rows($outcome)){
    while($row = mysqli_fetch_assoc($outcome)){
        $finalOutcome["username"][] = $row["username"];
        $finalOutcome["forename"][] = $row["forename"];
        $finalOutcome["surname"][] = $row["surname"];
    }
    echo json_encode($finalOutcome);
}

I want to store all of the relevant details within braces so like:
{
    "username":"bobgreen"
    "forename":"Bob"
    "surname":"O'Conor"
}
{
    "username":"jacksmitd"
    "forename":"Jack"
    "surname":"Smitd"
}
{
    "username":"samson"
    "forename":"Sam"
    "surname":"Son"
}

Also how do I extract all the relevant data from each brace and store in a list in Java? Because I am trying to store all the details on a per users basis and I wasn't sure how to do it with my first JSON array

Regarding main question:
You have to use this syntax:
while( $row = mysqli_fetch_assoc( $outcome ) )
{
    $finalOutcome[] = array
    (
        "username" => $row["username"],
        "forename" => $row["forename"],
        "surname"  => $row["surname"]
    );
}
echo json_encode( $finalOutcome );

Substantially, in your original query you increment $finalOutcome sub-arrays instead of $finalOutcome

Tuesday, 28 August 2018

PHP json does not show all related values

Hello I have this php code for printing json

<?php

include('databaseconnect.php');

$sql = "SELECT product_id,product_name FROM products WHERE product_id='1'";
$result = $conn->query($sql);

$sql2 = "SELECT GROUP_CONCAT(ss.Name,':',sv.value_s ) as Specifications FROM specifications ss, specification_value sv WHERE sv.specification_ID = ss.specification_ID AND sv.product_id =  '1'";
$fetch = $conn->query($sql2);

$sql3 = "select GROUP_CONCAT(v.name,':',vv.value) as variants from variant v,variant_value vv where v.variant_id=vv.variant_id and product_id='1'";
$fetch1 = $conn->query($sql3);

$json['products'] = array();

while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){

    $json['products'] = $row;

  }

$json['products']['specification'] = array();

while ($row = mysqli_fetch_assoc($fetch)){

    $specification_array  = explode(',', $row["Specifications"]);
    $speci_array = array();
    foreach($specification_array as $spec){
        $spec = explode(':',$spec);
        $speci_array[$spec[0]] = $spec[1];
    }
    $json['products']['specification'] = $speci_array;

    //array_push($json['products'],$row_temp);
   }

$json['products']['specification']['variants'] = array();

while ($row = mysqli_fetch_assoc($fetch1)){

    $variants_array  = explode(',', $row["variants"]);
    $vari_array = array();
    foreach($variants_array as $var){
        $var = explode(':',$var);
        $vari_array[$var[0]] = $var[1];
    }
    $json['products']['specification']['variants'] = $vari_array;

    //array_push($json['products'],$row_temp);
   }

echo Json_encode($json);

?>

and output of this is
{
    "products": {
        "product_id": "1",
        "product_name": "Face Wash",
        "specification": {
            "brand": "Python",
            "product_Description": "very good",
            "variants": {
                "size": "long"
            }
        }
    }
}

but in this i have one more value for variant i.e. "size":"small" and that is not showing up. sorry for bad English please ask me for any clarification before answering
my desired output
{
    "products": {
        "product_id": "1",
        "product_name": "Face Wash",
        "specification": {
            "brand": "Python",
            "product_Description": "very good",
            "variants": {
                "size": "small"
                "size": "long"
            }
        }
    }
}


You can't add same key size twice. The previous key gets overwritten by later.

PHP - JSON array can not return the value associated with the indexless name

I have a json array that looks like this:

[{"name":"title_one","value":"something"},{"name":"title_two","value":"something 2"},{"name":"title_three","value":"something three"}]

I can get the array and access values like so:
$configarray = json_decode($configfile, true);

$valueone = $configarray[0]['value'];
$valuetwo = $configarray[1]['value'];
$valuethree = $configarray[2]['value'];

BUT I will have different pairs (and thus different orders) at different times in this json, so I would like to access these values by getting their associated name, I have tried variations on:
 $valueone = $configarray['title_one']['value'];
 $valuetwo = $configarray['title_two']['value'];
 $valuethree = $configarray['title_three']['value'];

but it fails and tells me I have an undefined index. How can I access these values by the name in the pair?

Assuming you only have two properties inside of each json object you can do something like this:
$configfile  = '[{"name":"title_one","value":"something"},{"name":"title_two","value":"something 2"},{"name":"title_three","value":"something three"}]';
$configarray = json_decode($configfile, true);
$configarray = array_combine(array_column($configarray, 'name'), array_column($configarray, 'value'));

$valueone   = $configarray['title_one'];
$valuetwo   = $configarray['title_two'];
$valuethree = $configarray['title_three'];

Tuesday, 14 August 2018

PHP: Get POST JSON



My recent work at Mozilla has me creating an OAuth-like authentication transaction between Bugzilla and Phabricator. This task has thrust me back into the world of PHP, a language I haven't touched much (since version ~5.2) outside of creating WordPress themes and plugins for this blog. Coming back to a language you haven't touched in years feels like a completely new experience; you notice patterns and methods that you wouldn't have guessed of in years past.


Part of the authentication transaction requires Phabricator to receive a POST request that contains JSON data. I had expected the data to land in $_POST but the variable was empty; how the hell do I get the POST data? To get POST JSON with PHP, you use the following:

# Get JSON as a string 
$json_str = file_get_contents('php://input'); 
 # Get as an object 
$json_obj = json_decode($json_str);


file_get_contents, which I though was only used to retrieve content from local files or traditional URLs, allows you to use the special php://input address to retrieve JSON data as a string. From there you use json_decode to turn the JSON string into a workable object/array.

Thursday, 9 August 2018

Convert A CSV File Into JSON Using PHP

This is a short tutorial on how to convert the data in a CSV file into a JSON string format. For this example, we will assume that we have a CSV file called names.csv and that it contains the following data:
As you can see – it’s pretty simple and straight-forward. To convert it into JSON, we will need to read the CSV file using PHP before converting it into JSON.
Here’s a quick example using the CSV file above:
Explained:
  1. We opened our CSV file using the fopen function. We set the second parameter to “r” because we only need to read the file – not modify it.
  2. We created a PHP array called $csvData. This array will contain the data from our CSV file.
  3. We looped through the rows in our CSV file using the fgetcsv function and added them to our $csvData array.
  4. Finally, once our loop is completed, we convert the CSV data into a JSON string by using the function json_encode.