Monday 27 June 2011

PHP Form, jQuery, working in IE

Some days, you start by saying, "'I'll just get this out of the way, then I can concentrate on something heavier". You then write code without testing because you know how it works, and apart from a little syntax change, you get it working fine. About 15 minutes. This was my experience with writing a page with a form. It stored the data in a text file, then updated the page tag with the new contents. It worked fine in Chrome and Firefox. Then the dreaded IE pulled me back. 3 hours later, I find the solution. Below are code examples to a common problem.
Create a html form.
On submission, write the contents of the form to a file.
Once the file has been updated, refresh a section showing the new content.

Here is the code for readdata.php. Notice the @ before file_get_contents. This suppresses a warning if the file does not already exist.

<?php
foreach (explode("\n", @file_get_contents('data.data')) as $value)
{
echo $value."<br />";
}
?>
Here is the code for writedata.php. Nothing particularly clever here.

<?php
file_put_contents('data.data', $_POST['stuff']."\n", FILE_APPEND);
?>
Now to the main page. A few of important items here:
  1. Only $.get works in IE .load doesn't.
  2. $.ajaxSetup({cache: false}) is also required for IE otherwise you get all sorts of content varients coming through.
  3. I used the jQuery Form Plugin from http://jquery.malsup.com/form/ It saves a lot of problems.


Have fun.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Read and write using jquery</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
body
{
font-family:Sans-serif;
line-height:1.5em;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
</script>
<script type="text/javascript" src="jquery.form.js"></script>
<script>
$.fn.readStuff = function()
{
$.get('readdata.php', null, function(data)
{
    $('section').html(data);
});
$('#stuff').val('');
}
$(document).ready(function()
{
$.ajaxSetup({cache: false});
$('form').ajaxForm(function()
{
$(this).readStuff();
});
});
</script>
</head>
<body>
<h1>PHP and jQuery read/write test</h1>
<h2>Write data</h2>
<form action="writedata.php" method="POST">
<input type="text" name="stuff" id="stuff" />
<input type="submit" />
</form>
<h2>Read data</h2>
<section>
<?php
include 'readdata.php';
?>
</section>
</body>
</html>

No comments:

Post a Comment