Simple Ajax with JQuery and PHP (very quick and dirty tutorial)

Well some dudes asked me how to learn ajax quickly without a lot of hassle by learning XHR and such. So, here is the quick way: use jquery and some simple knowledge of HTML and PHP and you’re done.

First, some HTML(5):

<!doctype html>
<html>
<head><title>Just test</title>
<script type='text/javascript' src='jquery.min.js'></script>
</head>
<body>
What's your name, dude?
<input id='name'>
<input id='send' value='Send' type='button'>
<div id='repson'></div>
<script type='text/javascript'>
$('#send').click(function(){
  $.get('test.php',{data:$('#name').val()},
  function(resp){
    $('#repson').html(resp);
  });
});
</script>
</body>
</html>

As you can see, input elements don’t really need FORM tag, even they don’t need any name assigned, because we’ll send it without form. When we click button ‘Send’, we are sending the name value into PHP script, and display the response from PHP into the ‘repson’ DIV.

Now, for the PHP:

<?php
echo "Hi, ".$_GET{'data'];
echo ", nice to see you around...";
?>

And that’s it all. You’ve done ajax coding! We can then extend the form into fully featured HTML5 form, or using JQuery UI, and we definitely need database operations on PHP side.

No Comments »

RSS feed for comments on this post. TrackBack URL


Leave a Reply

*

Skip to toolbar