Get XOOPS XOOPS FAQ Forums News Themes Modules
News World of XOOPS Developers Hacks Modules Themes Archive Submit News

XOOPS vs. Herko Coomans

Make a donation

Please select an amount to donate


Do you want your username revealed with your donation?
Yes - List me as a Generous Donor
No - List my donation as from an Anonymous Donor


Search

Local Support Sites

Cumulus Tag Cloud

admin Arabic banner block Christmas comments cumulus DayDawn dhsoft e-Commerce E-Learning Google GUI hacks instant-zero jQuery module news Nordic Olédrion oxygen PageRank security SEO simple-XOOPS sport tag Theme wiki xoops

New Users

Registering user

# 96568

dvsshoescom

Welcome to XOOPS!

Archives

XOOPS Code hosted on SourceForge

Jquery Tutorial: Passing php arrays through JSON

Posted by kaotik on 2009/11/16 5:40:00 (4002 reads) | Posted on Developer News
This tutorial is a continuation of my previous one. This will teach you the benefits of using JSON.


Method 2


What is JSON?
JSON stands for "javascript object notation", quote:
"Widely hailed as the successor to XML in the browser, JSON aspires to be nothing more than a simple, and elegant data format for the exchange of information between the browser and server; and in doing this simple task it will usher in the next version of the World Wide Web itself."
So basically think of JSON as being a conection language between PHP and Javascript (and in our case, jQuery). So when building web pages (with jquery) we can use ajax calls (be it $.load, $.ajax or other) to go from the client to the server, then we use JSON to go from the server back to the client. Now you might ask, couldn't we use json in both directions? Yes we could, but since we are using jquery, it already sends info nicely formated to the server in $_GET or $_POST format.

Step 1- Setting the php file

With json, setting the php file becomes much easier. Copy my previous tutorial into a new folder. Now open myserv.php and replace all code with this:


<?php

if ($_GET['action']=='getlink'){

$ld=loadInfo ($_GET['link']);
echo 
$ld;
}


function 
loadInfo ($lnk){

switch (
$lnk) {
case 
1:
$list['name']='name john';
$list['desc']='my desc fsdfsd';
break;
case 
2:
$list['name']='orians gate';
$list['desc']='bla for bla';
break;
case 
3:
$list['name']='space 1999';
$list['desc']='whos there anyone';
break;
}
//properly format for use in javascript
$str=json_encode($list);

return 
$str;
}
?>


Notice that my arrays now have names "$list['name']" and I've also changed this:
$str=json_encode($list);
This line takes our php array and encodes it as a json string.
As I've said in my previous tutorial, javascript does not support associative arrays, however, we can use json to simulate them.

Step 2- The HTML

Open test.html and replace all code with this:



<style type="text/css">
#ajaxBox { background-color:#FFFF99; border:thin solid #FF0000; width:70%; height:50px;}
#formHeader{text-align:center; font-size:18px; color:#0000FF;}
#myform{text-align:center;}
</style>


<
script language="javascript" src="jquery-1.3.2.min.js"></script>
<script language="javascript" src="jquery.delay.js"></script>

<script language="javascript">
$(document).ready(function() { //Finish loading the entire page before processing any javascript

$("#hidden").hide();
$("#textfield").val("");
$("#textarea").val("");

$("#mylist a").bind("click", function() { 
var hol=$(this).attr('myval');
var formContent ="action=getlink&link="+hol;

$.getJSON("myserv.php",formContent, function(json){
$("#textfield").val(json.name);
$("#textarea").val(json.desc);
$("#formHeader").text("Edit");
$("#ajaxBox").text("All info loaded OK");
}); //End json

}); //End click

}); //End ready function
</script>

<div id="ajaxBox"></div>

<div id="mylist">
<ul>
<li><a href="#" myval="1">cool site</a></li>
<li><a href="#" myval="2">new name</a></li>
<li><a href="#" myval="3">great space</a></li>
</ul>
</div>

<div id="myform">
<div id="formHeader">Add New</div>
<form name="form1" method="post" action="">
<label>Name<input type="text" name="textfield" id="textfield"></label><br /><br />
<label>Desc<textarea name="textarea" id="textarea" cols="45" rows="5"></textarea></label>
</form>
</div>



Now try running the page. Nice isn't it? Let me explain the changes. The piece of code that really matters here is this:



$.getJSON("myserv.php",formContent, function(json){
$(
"#textfield").val(json.name);
$(
"#textarea").val(json.desc);
$(
"#formHeader").text("Edit");
$(
"#ajaxBox").text("All info loaded OK");
}); 
//End json



I'm now using a jquery function that does an ajax call and returns the data as a json object ($.getJSON). This data then gets placed in a variable called "json" which simulates an associative array. Notice this line:

$("#textfield").val(json.name);

I am assigning the form element "textfield" with "json.name". One of the cool things about json is, besides simulating associative arrays, you can write them as deep as you want, for ex:



$list
['country']='england';
$list['country']['city']='london';
$list['country']['city']['zip code']='12345';
etc



Now that we are retrieving properly formated data from the server, we can now generate html in a whole different way, but I'll leave that for a new tutorial.

Step 3- Looking back

So now we have looked at several ways of doing ajax calls and jquery function, let's briefly go over some of them.:

$.load - Does an ajax call and returns html.

$.getJSON - Does an ajax call and returns data formated as json.

$.change - Detect a change on a selector.

.bind("click", function()) - wait for a click on a selector

$.hide - hide a selector such as div, p, etc

$.show - show a selector


Printer Friendly Page Send this Story to a Friend Create a PDF from the article


Bookmark this article at these sites

                   

The comments are owned by the poster. We aren't responsible for their content.

What a kewl tutorial, yeah JSON is really useful, especially with Select Boxes... Make sure you use the PEAR library file for PHP in generating JSON Strings makes it easy..

Using JSON in a module I am writting at the moment.. Which is good!!
Posted: 2009/11/16 18:54 • Updated: 2009/11/16 18:54
very helpful, thanks for this tutorial.
Posted: 2009/11/17 9:01 • Updated: 2009/11/17 9:01
Glad you both like it :)
Jquery never ceases to amaze me. It's simplicity makes the job of a web designer or coder so much more easier. I see more and more php developers diving into javascript thank's to jquery.
Posted: 2009/11/17 9:44 • Updated: 2009/11/17 9:44
Note of caution:
When using json_encode, all characters and strings it doesn't recognize get transformed into their unicode equivalent, meaning;
If you try to pass "€" from the database back to the client by encoding it using json_encode, it gets transformed into this "\u20ac".

I just discovered this while trying to pass non-standard characters back and forth
Posted: 2009/12/4 8:17 • Updated: 2009/12/4 8:17