treehouse : what would you like to learn today?
Web Design Web Development iOS Development

jQuery - Auto Refresh Page

  • Hello,

    I'm writing some code for a postcode calculation, what I want to happen is instead of hitting submit to calculate the distances I want JQuery / Ajax to do this automatically when the text box changes...



    Below is the code I have currently got, is there an easy way to inject so Ajax into this?



    // Connect to the database server

    $dbcnx = mysql_connect("", "", "");

    if (!$dbcnx) {

    echo( "

    Unable to connect to the " .

    "database server at this time (this is a host connect problem).

    " );
    exit();

    }

    // Select the database

    if (! mysql_select_db("", $dbcnx) ) {

    echo( "

    Unable to locate the " .

    "database at this time(this is a dbconnect problem).

    " );
    exit();

    }

    function calc_postcode_seperation($pcodeA,$pcodeB)

    {

    // PCODE A

    $result=mysql_query("SELECT * FROM postcodes WHERE Pcode='{$_POST['pcodeA']}' LIMIT 1");

    $row=mysql_fetch_array($result);

    $gridn[0]=$row[Grid_N];

    $gride[0]=$row[Grid_E];

    // PCODE B
    $result=mysql_query("SELECT * FROM postcodes WHERE Pcode='{$_POST['pcodeB']}' LIMIT 1");

    $row=mysql_fetch_array($result);

    $gridn[1]=$row[Grid_N];

    $gride[1]=$row[Grid_E];

    // TAKE GRID REFS FROM EACH OTHER.

    $distance_n=$gridn[0]-$gridn[1];

    $distance_e=$gride[0]-$gride[1];

    // CALCULATE THE DISTANCE BETWEEN THE TWO POINTS

    $hypot=sqrt(($distance_n*$distance_n)+($distance_e*$distance_e));

    $text.= round($hypot/799,0);

    return $text;

    }

    ?>

    <div class="main-content">

    <h1><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h1>

    <h2>Step 1 - Please enter your postcode.</h2>

    <form action="" id="cakeform" method="post">
    <input type="hidden" name="pcodeA" value="BS30" />
    Please Enter Your Postcode:<input type="text" id="pcodeB" name="pcodeB" />
    <input type="hidden" id="postcode_value" value="<?php echo calc_postcode_seperation($_POST['pcodeA'],$_POST['pcodeB']); ?>" />

    <script type="text/javascript">

    $('#pcodeB').change(function() {
    $(this).closest("form").submit();
    });

    </script>



    Thanks,

    Scott
  • Have you tried looking into the documentation to work out something at least?

    http://api.jquery.com/jQuery.ajax/

    Has some great resources...

    and as a starting point, instead of using .change() consider .blur()

    e.g.:


    $('#pcodeB').blur(function() {
    // your ajax calls here...
    });