Tuesday, January 31, 2012

A simple Echo Machine to demonstrate basic $.ajax on Jquery Mobile page

This example uses the Jquery and Jquery Mobile application with HTML5 to send an asynchronous request to php on the server. 

<!DOCTYPE HTML>
<html>
<head>
    <title>Echo Machine</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js"></script>
</head>

<body>

<div data-role="page" id="easyloader" data-theme="e" data-add-back-btn="true">
    <div data-role="header">
        <h1>Ajax Echo Machine</h1>
    </div>
   
    <div data-role="content">   
        <p> Test Jquery $.get function.  Send an asynchronous request to the server and show results. </p>
        <label for="echo_term"> Enter a phrase (and then press tab or click outside of box): </label>
        <input type="text" name="echo_term" id="echo_term" onchange="makeEcho()"/>
    </div>
   
    <div id="echo_results" style="margin-left:50px" > Echo here. </div>

</div>

<script type="text/javascript">

    function makeEcho() {
        var echo_val=$("#echo_term").val();
        $.get("scripts.php", {echo_term : echo_val}, function(data){
            if (data.length>0){
                $("#echo_results").html("<p> " + data + " </p>");
               
            } else $("#echo_results").html('<p>no data returned! </p>');
        });
    }
</script>
</body>
</html>
 uses the php file called scripts.php

<?php
//a simple echo machine the returns what you sent it.
$term = strip_tags(substr($_GET['echo_term'],0, 100));
$term = mysql_escape_string($term);
$term = "Response from php: " . $term;
echo $term;
?>