Category search : jquery...

(3 results found)

Fix for jQuery Ajax and json_encode problem

Wed Aug 4 02:12:58 2010

I came across something that really interested and surprised me today. There I was coding happily for one of my latest projects in which I needed to return values from a .php file via Ajax / $.get using jQuery. The aim was to build an array of filtered results from the SQL database and then pass them on to jQuery which would update the HTML on the page and display the results in real time.

I used json_encode( array ) on the PHP side and jQuery.parseJSON(data) on the jQuery side to get the array into something usable for jQuery. The problem was that the array that was jSON encoded was, as I mentioned, filtered on the PHP side. Below is the sort of thing I was doing.

$checkAgainst=array("1","2","3","4","5");
$whatsMissing = array("1","3","4","5");
$finalArray=array_diff($checkAgainst,$whatsMissing);	
echo json_encode($finalArray);

Here's what's happening. I've set up an array $checkAgainst which contains values that I want to check to see if they exist in another array I've set up called $whatsMissing. In this simple example, you can probably see that the number that is missing is '2'. So when we run the array_diff() and save the results to $finalArray we should be left with the value '2'. The last thing to do is output this array as jSon using json_encode(). Done! Great ...or so I thought.

The code below is jQuery code and is similar to what I used to parse the json encoded data.

$.get('getJson.php',
   function(data){
      var obj = jQuery.parseJSON(data);	
      alert(obj)
   }
);

This bit of code simply makes contact with the PHP file containing the PHP code above and the returned data is then parsed using jQuery.parseJSON(); and the resulting data is saved to a variable called 'obj'. Simple, right? Wrong! The only thing that was returned seemed to be an empty array. Of course it isn't empty. We know it's not. So what went wrong?

Well, if we tried to return any old array from the PHP code, it would work fine. I noticed the problem was that the jSON returned was a mess. The nodes were out of order and sometimes missing. The culprit, you guess it, array_diff()!

Solving the problem is really easy. I added sort($finalArray); to the PHP file before outputting the data which sorted the data correctly and jQuery was successfully able to parse it properly. What an nuisance!

Parsing XML using jQuery

Mon Nov 30 01:56:20 2009

I have found that being able to parse XML is one of the most useful things a programmer can learn. It allows you to store a lot of information in one place and easily edit it without the need to update your program or website itself. The effects on a website can be astounding.

Today, for those who don't know, I would like to show you how to parse XML files using jQuery. First, you will need an XML file. XML is a markup language and uses tags very similar to HTML tags. The major difference with XML tags is the fact that you get to choose the names of your tags.

I have created an xml file which will be a list of the websites I have recently created. The code is as follows:

<list>
	<item id="1">
		<title>CuluCulu Flash</title>
		<url>http://www.culu-culu.com/culuculu/flash</url>
	</item>
	<item id="2">
		<title>CuluCulu HTML</title>
		<url>http://www.culu-culu.com/culuculu/html</url>
	</item>
	<item id="3">
		<title>Gakushu Support Juku</title>
		<url>http://www.supportjuku.com</url>
	</item>
	<item id="4">
		<title>Yokkaichi College of Information & Languages</title>
		<url>http://www.ssc.ac.jp</url>
	</item>
	<item id="5">
		<title>Tomojiro's Music Studio (v.2)</title>
		<url>http://www.musictomo.com</url>
	</item>
</list>

As you can see, inside the <list> tags there are five sets of <item> tags, each containing a <title> and a <url>. What we want to do is parse the information in <title> and <url> tags, which will allow us to create links. This is usefull to use for example in creating a sitemap for a list of urls to display on our website. Imagine you have 50 links you would like to display. Writing them out is quite a feet, let alone updating them. With a little jQuery, all of this becomes very simple.

<script type="text/javascript" charset="utf-8">

   $(document).ready(function() {
      $.ajax({
         url: "sites.xml",
         dataType: "xml",
         success: function(xml) {
  
            $(xml).find('item').each(function() {
               var id = $(this).attr('id');
               var title = $(this).find('title').text();
               var url = $(this).find('url').text();							
               $('#content').append("<p>"+id+") <a href= "+url+">"+title+"</a></p>");
            });

         }
      })
   });

</script>>

Ok, so here's what's happening. We start off with the jQuery ready function (line 3) which initiates everything. Then, using the $.ajax() method we tell jQuery to look for the sites.xml file (line 5) and give it the dataType: "xml" so that it knows what kind of file we are dealing with (line 6). When jQuery has succeeded in finding and loading the file, it will call the anonymous inline function on line 7 and this is where we get to write what is going to happen with the information we have parsed.

On line 9 we loop through each of the <item> tags and store the information inside the <id>, <title> and <url> tags inside variables (lines 10 ~ 12).

To find attributes we use $(this).attr('xx'); where ('xx') is the name of the attribute we are looking for, which in this case is 'id' on line 10.

Finally, we use the info stored in each variable to output a little html inside the <div> tag with an id of 'content' using HTML() on line 13, which in this case places the information inside a href to create links. The output is as follows:

Recent Work

1) CuluCulu Flash

2) CuluCulu HTML

3) Gakushu Support Juku

4) Yokkaichi College of Information & Languages

5) Tomojiro's Music Studio (v.2)

So there you go. Try it out and let me know how you get on. I also intend to write a post on AS3 xml parsing using the infamous E4X syntax, which is a delight to use. Until then, happy jQuery parsing!

'As-you-type Output' in jQuery

Sun Nov 22 07:03:46 2009

As some may have already gathered, I am actually programming this blog myself. The main reason is that I think that I can learn a lot from doing so. Plus, it gives me a getaway project when other work is stressing me out and I don't want to be away from coding. As a side note, I have tried WordPress and I think it is truly amazing and thoroughly recommend it.

Anyway, today I would like to share some more code with you. While working on this blog, I found I needed something that would help me get a sense of what the finish post would look like while I typed, so I developed an editor using jQuery to do just that.

The picture below is of the post editor that I use. As you can see, it is quite simple and I am yet to develop buttons that allow me to upload images and add html tags without having to type them myself, but for now, it does what it was meant to.

Basically, below the input area is an output area which displays the the post as it will look once posted. The display area also updates on the fly as you type. I have written a small example below since I can't actually give you access to the editor for obvious reasons.

Type in the box and watch it get displayed below: (Note*30 letter limit)

Output:


I set up an input textfield with an id of "typerArea" and a p-tag with an id of "showType". If you are trying this, you will also have to download jQuery and place it in the same directory and the html file or whatever file type you are coding in. The jQuery code is as follows:

$(document).ready(function() {
   $("#typerArea").keyup(displayType);
				
   function displayType(){
      var contents = $("#typerArea").val();
 	$("#showType").html(contents);
   }
 });

As usual in jQuery, once the document is ready (line 1), the "typerArea" textfield is set up to receive a keyup event (line 2) so that after every keystroke (up state) the function displayType() (line 4) will fire. This in turn takes the contents of the typerArea textfield using jQuery's val() function and places it inside the variable 'contents' (line 5), which then gets passed as the HTML of the paragraph "showType". Quite straight forward stuff, but fun none-the-less.

If you are interested in downloaded the example file you can find that here

Most recent posts

  1. Flashcards Maker - the app the helps you learn in a flash
  2. Convert Font Suitcase to TTF in 3 Easy Steps
  3. Rain or Shine - Weather Forecast Available Now!
  4. Getting around Apple's silly rules for iOS 10
  5. Localising App Names for iOS and Android

Search site:

Apps by Ubacoda.com

Click the app icons to see more info


Archives

Categories