Tuesday, March 19, 2013

jQuery / JSON / get some date from other file

How to retrieve some information from other page using JSON?

Example of how to use JSON.

1. index.php

<html>
<head>
<title>jQuery</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script type="text/javascript">
 
    $(document).ready(function()
    {
        $("#J_action_getData").click( function()        
        {
            $.post("fileWithData.php", { "getData": "cars" }, function(data)
            {
                var obj = jQuery.parseJSON(data);
                $("#mymsg").html( obj[0] + " " + obj[1] ); 
            });            
        });        
    });
 
</script>

</head>

<body> 
    
    <a id="J_action_getData" href="javascript:void(0)" >Show message</a>

    <div id="mymsg">
        
    </div>

</body>
</html>

2. fileWithData.php

<html>
<head>
<title>j</title>

</head>

<body> 
<?php
    if($_POST['getData'] == "cars")
    {
        $cars = array();
        $cars[1] = "Mercedes";
        $cars[2] = "Audi";
        echo json_encode($cars);
    }        
?>
</body>
</html>

Some details about parse JSON here.
Details of encoding and decoding JSON in PHP here.

No comments: