Solved

Fastest/Best Method of Parsing Data with AJAX

Posted on 2009-05-19
14
477 Views
Last Modified: 2013-12-12
I made an AJAX/php/mysql poker game around 3 years ago.  I had never done anything with AJAX before, so I was pretty much making it up as I went along.  I am now looking to improve this application to take it to a larger scale, and looking for some best practices input.

Current the way I have it setup, is that every 2 seconds I make a call to a script that prints a bunch of data, seprated with "~!@#~" (I know this probably sounds moronic), and I then split this data when it is returned to the javascript and update what the user sees.  I am looking for a better way of doing this (or if this actually is the best way...which I find hard to believe...then great!).  Whether that is doing it with XML, JSON, etc I am not sure.  Or if I am thinking through this completely wrong that would be great to know.  Any references or examples would be great as well.
0
Comment
Question by:jls33fsls
  • 9
  • 4
14 Comments
 
LVL 40

Accepted Solution

by:
RQuadling earned 500 total points
ID: 24426680
I would recommend using a pattern called JSONP.Essentially you have JavaScript functions which can process JSON encoded data.You use AJAX to make a request of the server (sending any data you want) along with the name of a function that will handle the response.The server processes the received data and encodes it using json_encode().It then wraps it with the name of the function that will handle it.Then it supplies the appropriate header to make the client process the response as JavaScript.I use the prototype library for this as it is much easier to work cross-platform (http://prototypejs.org).
0
 
LVL 40

Assisted Solution

by:RQuadling
RQuadling earned 500 total points
ID: 24426829
Below I've got 4 snippets dealing with the function that will handle the JSON encoded data and a PHP script which would be the handler for an AJAX request which would return the JSON encoded data with a JSONP concept call.Essentially, PHP generates the JavaScript call (and appropriate headers) so that when it gets to the client it can be called without problems.Now, if you ARE using PrototypeJS, then this is all done for you by their AJAX library.The next snippet is one of my forms Delete button JS code.The code makes an AJAX call, supplying the server with the data required to delete a report.The page will need to be updated with the updated list of reports, so a JSONP parameter is also passed. That is actually a function name in the same JS script.The last snippet is that function.
<script type="text/javascript">

// Example of a JSONP handler. The parameter is a single JSON object.

function updateUser(o_User) {

 $('username').update(o_User.userName);

 $('email').update(o_User.email);

}

</script>

 

<?php

// Example PHP script to generate the data for the above example.

 

// We've got our data ...

$a_User = array (

 'userName' => 'Richard Quadling',

 'email'    => 'RQuadling@nowhere_in_particular.com',

);

 

header("{$_SERVER['SERVER_PROTOCOL']} 200 OK", True, 200);

header('Content-type: application/javascript');

echo $_POST['JSONP'] . '(' . json_encode($a_User) . '); //';

?>

 

 

 

<script type="text/javascript">

// Real code used daily.

function tabRA_DeleteClick(ev)

	{

	ev.stop();

 

	if (confirm('Please confirm the deletion of "' + $('tabRA_ReportFilename').value + '".'))

		{

		new Ajax.Request

			(

			location.href,

				{

				method : 'post',

				parameters :

					{

					Action : 'ClientDropReport',

					JSONP  : 'tabRA_UpdateReportIDs',

					ReportID : $('tabRA_ReportID').value

					},

				Spinner    : $('tabS_ReportAdminAJAX'),

				Form       : $('formReportAdmin')

				}

			);

		}

 

	return false;

	}

 

 

function tabRA_UpdateReportIDs(o_JSONReports)

	{

	tabRA_ReportIDOriginalValue = null;

 

	$('tabRA_ReportID')

		.populateSelect

			(

			o_JSONReports,

			null,

			{'-2' : 'Select a report to edit', '-1' : 'Refresh list of reports', '0' : 'Add a new report'}

			)

		.enable();

 

	$('formReportAdmin')

		.reset();

 

	if (0 == $('tabRA_ReportID').value)

		{

		el_Form

			.getElements()

			.invoke('enable');

		}

	else

		{

		tabRA_ReportIDOriginalValue = null;

		tabRA_ReportIDChange();

		}

	}

 

 

 

</script>

Open in new window

0
 
LVL 40

Expert Comment

by:RQuadling
ID: 24426856
The main advantage I have when using this code is that I don't have any page refreshes. I like this a LOT.

Sure it requires JS, but the code is added unobtrusively so if there is no js available, the standard way is used and that involves page refreshes.

What I've shown above are elements from one of the frameworks I've built. Hopefully it'll make sense.
0
 
LVL 12

Expert Comment

by:alien109
ID: 24426883
RQuadling: not questioning your answer - but why use jsonp when the request isn't cross domain? just curious...
0
 

Author Comment

by:jls33fsls
ID: 24426892
Thank you for the great answer, though I am wondering if this would actually be faster than what I am already doing.  It seems like this would increase the data size, can JavaScript parse JSONP faster, or?
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 24426935
The code is in several parts.

Specific JS <-> Generic JS <-> Generic PHP <-> Specific PHP

JSONP allows my to code the specific ends without the generic bits caring.

The code I supplied is actually quite old. The whole AJAX code is now part of a generic AjaxJsonpUpdator call within the Generic JS.

I know I could have added onSuccess responders to the AJAX request, but I wanted to keep the actual data handler function within the Specific layer and not the generic layer.

The cross domain issue wasn't/isn't part of the concern.

Essentially, I hardly touch the GenericJS/PHP part.

I create Specific JS/CSS/HTML/PHP parts and drop them on the server and they then auto-magically incorporate themselves into the site due to the way my Generic  JS/CSS/HTML/PHP parts work.


0
 
LVL 40

Expert Comment

by:RQuadling
ID: 24426996
JSON IS Javascript. No need to manually decode the string.

It IS javascript.


JSONP is a "pattern", a way of doing something.

By using the correct headers, the AJAX code simply runs a JS function, supplying a JS object as the parameter.

No deconstructing of a string into parts for processing. Well, at least not in the userland aspects of the JS. Sure, it does this internally, but that is no different to it reading the JS code you created.

Hmm..
Not very well explained.

Using the first 2 snippets I supplied, the JS code looks like this ...


updateUser({"userName":"Richard Quadling","email":"RQuadling@nowhere_in_particular.com"}); //


That is what PHP generated.

It is pure javascript.

The parameter to the updateUser() function is usable instantly. No need to break it apart into bits. You also know what bits have been supplied as it is a hash.

Oh.

If you use this, make sure you use json_encode($a_Data, JSON_FORCE_OBJECT); as an empty array ends up as something different in JSON.

See example 2 on http://docs.php.net/json_encode
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:jls33fsls
ID: 24427026
Okay this is making a little more sense.  I still don't get how I would do something as simple as updating the innerHTML of a div element with this method.
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 24427035
$('some_div_ID').update('some_text');
$('some_div_ID').update(o_JSON.userName);



0
 
LVL 40

Expert Comment

by:RQuadling
ID: 24427038
See the first snippet.
0
 

Author Comment

by:jls33fsls
ID: 24427104
So you really don't need an onSuccess function doing this since what the AJAX calls is javascript that does the update itself?
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 24427141
More or less.
0
 

Author Comment

by:jls33fsls
ID: 24427350
Okay so I tested this out at http://pokerrpg.com/test3.php.  Can I just use that basic format and have PHP output all of the functions needed and pass it all back to run and update?  Also, did I do anything wrong there even though it works?
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 24429466
That's pretty much it.

Well done.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
These days socially coordinated efforts have turned into a critical requirement for enterprises.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now