Update string in a PHP without page refresh, AJAX type function

Solution:1

PHP runs on the server, not in the browser. There is no way for it to interact directly with a page loaded in a browser. PHP can generate a page and send it to the browser to display, but that’s the end of the story. If you want to manipulate the page without reloading, you need a client-side technology. This means Javascript in 99.9% of cases.

If you need something from the server, you can use Javascript to fetch the result of a PHP script and insert it on your page without reloading but, even though PHP can be involved, all of the client-side actions will be performed by Javascript.

Solution:2

<html>
<head>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
    $("form#submit").submit(function() {
    // we want to store the values from the form input box, then send via ajax below
    var fname     = $('#fname').attr('value');
    var lname     = $('#lname').attr('value');
    $.ajax({
            type: "POST",
            url: "ajax.php",
            data: "fname="+ fname +"&amp; lname="+ lname,
            success: function(){
                $('form#submit').hide(function(){$('div.success').fadeIn();});

            }
        });
    return false;
    });

});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
<title>Insert title here</title>
</head>
<body>
<form id="submit" method="post">
<fieldset><legend>Enter Information</legend> 
<label for="fname">Client First Name:</label>
 <input id="fname" class="text" type="text" name="fname" size="20" />
  <label for="lname">Client Last Name:</label> 
  <input id="lname" class="text" type="text" name="lname" size="20" /> 
  <button class="button positive">  Add Client </button>
  </fieldset>
</form>
<div class="success" style="display: none;">Client has been added.</div>
</body>
</html>

and ajax.php

<?php

    include ("../../inc/config.inc.php");

    // CLIENT INFORMATION
    $fname        = htmlspecialchars(trim($_POST['fname']));
    $lname        = htmlspecialchars(trim($_POST['lname']));

    $addClient  = "INSERT INTO clients (fname,lname) VALUES ('$fname','$lname')";
    mysql_query($addClient) or die(mysql_error());

?>