Skip to main content

PHP, JSON and JavaScript usage

Today i want to introduce you to jSON (JavaScript Object Notation), in short, it is a simple format designed to exchange data between different programming languages. I will show you how to create JavaScript object, convert it to JSON string, and send to PHP script, which will decode jSON string to readable format (for PHP). But that’s not all, PHP script will create it’s own data object encode it to jSON string and send it back. All communication between JavaScript and PHP will be done thru AJAX.

If you haven’t heared about jSON yet, then you can visit Wikipedia for more information. The other technology you need to be familiar with before reading this article is AJAX. If you need to, you can read my Introduction to AJAX post.

Last note before we start, i am constantly working to make my articles as useful for you as possible, so beginning from this tutorial in each of my programming tutorials, at the end of the article you will find complete source code for download.

JSON objects

Usually when it comes to JSON we have an encoded string in mind, however JSON is a subset of JavaScript and in this programming language it can be used as is, to create objects. Simple JavaScript object created using JSON notation can look like this:

/*

var
JSONstring =
{
"firstname": "Greg",
"email": "greg@fake_email.com",
"hobby":
[
{
"hobbyName": "sport",
"isHobby": "true"
},
{
"hobbyName": "reading",
"isHobby": "true"
},
{
"hobbyName": "music",
"isHobby": "false"
}
]
};
*/
Accessing fields is done like in any other JS object (mainly because it
is “normal” JavaScript object), if we want to know if hobby “reading”
was checked then we would have to write:
/*
JSONstring.hobby[1].isHobby; // true
*/

Creating JavaScript Objects

Before we start, we will need something to work with. We will create HTML form with “validate” button, when someone clicks this button the whole proccess i described in the first paragraph will start. Also, despite JSON is a subset of JavaScript there are no built in function for converting JavaScript object into JSON string, so we will use already created class available at JSON homepage, the file is located here json2.js.

Here is the code for the HTML form, i think there is no need to explain it:
/*

</script>

&lt;html>
<head>/span></span>ditio.net jSon Tutorial<span style="color: rgb(0, 153, 0);"><span style="color: rgb(0, 0, 0); font-weight: bold;">
<script src="http://www.json.org/json2.js">
<script>
// JavaScript source code will be here
</head>
<body>
<form name="personal" action="" method="POST">
Name &ltinput type="text" name="firstname">
<br>
Email <input type="text" name="email">
<br>
Hobby <input type="checkbox" name="hobby" value="sport">
Sport <input type="checkbox" name="hobby" value="reading">
Reading <input type="checkbox" name="hobby" value="music">
Music <input type="button" name="valid" value="Validate" onclick="validate()">
</form>
</body>
</html>
*/
After clicking “validate” button validate() function will be called, we need to add it, in head section for example:
/*
function validate()
{
var p = document.forms['personal'];

var JSONObject = new Object;
JSONObject.firstname = p['firstname'].value;
JSONObject.email = p['email'].value;
JSONObject.hobby = new Array;

for(var i=0; i<3; i++)
{
JSONObject.hobby[i] = new Object;
JSONObject.hobby[i].hobbyName = p['hobby'][i].value;
JSONObject.hobby[i].isHobby = p['hobby'][i].checked;
}

JSONstring = JSON.stringify(JSONObject);
runAjax(JSONstring);

}
*/

Code is quite easy to understand. First i assign whole form to variable p just to make further access to this form data easier. In next lines JavaScript object is created, as you can see it consists only from Object and Array data objects.

Note that this is completely the same object as in first listing of this tutorial, however different method was used to create it.

Sending JSON object to PHP with AJAX
/*

var request;

function runAjax(JSONstring)
{
// function returns "AJAX" object, depending on web browser
// this is not native JS function!
request = getHTTPObject();
request.onreadystatechange = sendData;
request.open("GET", "parser.php?json="+JSONstring, true);
request.send(null);
}

// function is executed when var request state changes
function sendData()
{
// if request object received response
if(request.readyState == 4)
{
// parser.php response
var JSONtext = request.responseText;
// convert received string to JavaScript object
var JSONobject = JSON.parse(JSONtext);

// notice how variables are used
var msg = "Number of errors: "+JSONobject.errorsNum+
"\n- "+JSONobject.error[0]+
"\n- "+JSONobject.error[1];

alert(msg);
}
}

*/
hat’s it we are half way there, now we need to create PHP script to handle AJAX request.

JSON and PHP

Decoding JSON string is very simple with PHP only one line of code is needed to parse string into object. Similary only one function is needed to encode PHP object or array into JSON string, look at the code:

/*php


// decode JSON string to PHP object
$decoded = json_decode($_GET['json']);

// do something with data here

// create response object
$json = array();
$json['errorsNum'] = 2;
$json['error'] = array();
$json['error'][] = 'Wrong email!';
$json['error'][] = 'Wrong hobby!';

// encode array $json to JSON string
$encoded = json_encode($json);

// send response back to index.html
// and end script execution
die($encoded);

*/
It is also interesting what is inside $decode variable
stdClass Object
(
[firstname] => fgfg
[email] =>
[hobby] => Array
(
[0] => stdClass Object
(
[hobbyName] => sport
[isHobby] => 1
)

[1] => stdClass Object
(
[hobbyName] => reading
[isHobby] =>
)

[2] => stdClass Object
(
[hobbyName] => music
[isHobby] =>
)

)
)

PHP finished execution, then “request” object status in JavaScript is now equal to 4. Response text (in sendData() function) will be parsed with JSON class to object and used to display message on the screen. Note that instead of using JSON.parse() we could use JavaScriipt eval() function.

Conclusion

This tutorial was intended to introduce you to JSON, and i wanted to make this tutorial as clear as possible so i intentionally used the simplest methods to achieve my goal. However this tutorial wouldn’t be complete if i wouldn’t give you further resources from which you can learn more.

First you should check out is Zend_Json class (a part of Zend Framework), it has the same functionality as json_decode() and json_decode(), but can handle more complicated JSON strings then those two functions.

Second is json.org home of JSON, check especially this tutorial, it has got great examples of more advanced JSON class usage.
courtsy: http://ditio.net

Comments

Popular posts from this blog

Financial Engineering

Financial Engineering: Key Concepts Financial engineering is a multidisciplinary field that combines financial theory, mathematics, and computer science to design and develop innovative financial products and solutions. Here's an in-depth look at the key concepts you mentioned: 1. Statistical Analysis Statistical analysis is a crucial component of financial engineering. It involves using statistical techniques to analyze and interpret financial data, such as: Hypothesis testing : to validate assumptions about financial data Regression analysis : to model relationships between variables Time series analysis : to forecast future values based on historical data Probability distributions : to model and analyze risk Statistical analysis helps financial engineers to identify trends, patterns, and correlations in financial data, which informs decision-making and risk management. 2. Machine Learning Machine learning is a subset of artificial intelligence that involves training algorithms t...

Wholesale Customer Solution with Magento Commerce

The client want to have a shop where regular customers to be able to see products with their retail price, while Wholesale partners to see the prices with ? discount. The extra condition: retail and wholesale prices hasn’t mathematical dependency. So, a product could be $100 for retail and $50 for whole sale and another one could be $60 retail and $50 wholesale. And of course retail users should not be able to see wholesale prices at all. Basically, I will explain what I did step-by-step, but in order to understand what I mean, you should be familiar with the basics of Magento. 1. Creating two magento websites, stores and views (Magento meaning of website of course) It’s done from from System->Manage Stores. The result is: Website | Store | View ———————————————— Retail->Retail->Default Wholesale->Wholesale->Default Both sites using the same category/product tree 2. Setting the price scope in System->Configuration->Catalog->Catalog->Price set drop-down to...

How to Prepare for AI Driven Career

  Introduction We are all living in our "ChatGPT moment" now. It happened when I asked ChatGPT to plan a 10-day holiday in rural India. Within seconds, I had a detailed list of activities and places to explore. The speed and usefulness of the response left me stunned, and I realized instantly that life would never be the same again. ChatGPT felt like a bombshell—years of hype about Artificial Intelligence had finally materialized into something tangible and accessible. Suddenly, AI wasn’t just theoretical; it was writing limericks, crafting decent marketing content, and even generating code. The world is still adjusting to this rapid shift. We’re in the middle of a technological revolution—one so fast and transformative that it’s hard to fully comprehend. This revolution brings both exciting opportunities and inevitable challenges. On the one hand, AI is enabling remarkable breakthroughs. It can detect anomalies in MRI scans that even seasoned doctors might miss. It can trans...