Hello, thanks for reading my thread. I'm still new to web development so I appreciate your help in advance. Here is the issue I am having:

In my project, I have a index.php page with a sidebar menu and a div id called “content”.The user can select different menu items and perform searches from the database and make updates to their account. I’m using ajax to load all of the menu items and all of the forms into the div id "content" on the index page. The Forms all load into the target div as they are suppose to with ajax.

However, on the mysettings page I have two forms and two different buttons, one called save and the other called update. When a user wants to edit their account information and makes changes to their account they clicks on either button and the form processes the information and updates or inserts data into the database correctly but the problem is that after that the form or page does not display the form back in the div id "content" like how it was loaded originally in the index.php page. The problem is that it reloads or refreshes the form page without the index.php page being involved. That is does not get reloaded or updated inside the index.php page content div again.

What I would like do is have all of my forms process whatever is submitted on the page and display the results back inside the same content div on the index.php page again. I know I am missing something because all of my forms are doing the same thing. I am hoping someone can help me out. I would be very grateful for example code that I can learn from since I am still relatively new to web development. I am posting some sample code below. Many thanks in advance!

Here is my basic sample code:  index.php
<?php include('dbconfig.php'); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link href="twoColFixLt.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">

$(document).ready(function() {
 
   $('.sidebar1 a').click(function() {
	var $a = $(this);
	var url = $a.attr('href');
	var linkText = $a.html();
	var target = $a.attr('target');
	$.ajax({
      context: $('#'+target),
      error: function(XMLHttpRequest, textStatus, errorThrown){
        this.html('AJAX error<br>' + linkText + '<br>' + url);
	  },
      success: function(data, textStatus, XMLHttpRequest) {
        this.html(data);
      },
      timeout: 5000,
      type: 'GET',
      url: url
	  });
	return false;
  });

  $('form[name="MyForm"]').live('submit', function() {
	var form = $(this);
	var url = form.attr('action');
	var target = form.attr('target');
	var data = form.serialize();
    $.ajax({
      context: $('#'+target),
	  data: data,
      error: function(XMLHttpRequest, textStatus, errorThrown){
        this.html('AJAX error<br>Form submitted: ' + form.attr('name') + '<br>' + url);
      },
      success: function(data, textStatus, XMLHttpRequest) {
        this.html(data);
      },
      timeout: 5000,
      type: 'POST',
      url: url
    });
	alert("Post form submitted");
    return false;
  });
});

  $('form[name="form1"]').live('submit', function() {
	var form = $(this);
	var url = form.attr('action');
	var target = form.attr('target');
	var data = form.serialize();
    $.ajax({
      context: $('#'+target),
	  data: data,
      error: function(XMLHttpRequest, textStatus, errorThrown){
        this.html('AJAX error<br>Form submitted: ' + form.attr('name') + '<br>' + url);
      },
      success: function(data, textStatus, XMLHttpRequest) {
        this.html(data);
      },
      timeout: 5000,
      type: 'GET',
      url: url
    });
	alert("GET form submitted");
    return false;
  });

</script>
<script language="JavaScript" type="text/javascript" src="js/jquery.validate.js"></script>
  <script>
  $(document).ready(function(){
    $("#myform").validate();
	 $("#pform").validate();
  });
  </script>

</head>

<body>

<div class="container">
  <div class="sidebar1">
    <ul class="nav">
            <li><a href="mysettings.php" target="content">My Settings</a></li>
    </ul>
    <p> </p>
    <!-- end .sidebar1 --></div>
 <div id="content" style="border:red solid 1px;">
    <h1>Div &quot;content&quot;</h1>
    </div>
    <!-- end .content --></div>
  <!-- end .container --></div>
</body>
</html>


Here is the mysettings.php page:
<?php if (!isset($_SESSION)) {
    session_start();}
?>
<?php 
/********************** MYSETTINGS.PHP**************************
This updates user settings and password
************************************************************/

$_SESSION[user_id] = "3"; //Set variable for Testing only! 
$id = $_SESSION[user_id]; // Enabled to verify Session user_id is there. 
echo "SESSION user_id is:". $id ." <br />";

include 'dbc.php';
//page_protect();

$err = array();
$msg = array();

if($_POST['doUpdate'] == 'Update')  
{


$rs_pwd = mysql_query("select UserPassword from users where UserID='$_SESSION[user_id]'");
list($old) = mysql_fetch_row($rs_pwd);
$old_salt = substr($old,0,9);

//check for old password in md5 format
	if($old === PwdHash($_POST['pwd_old'],$old_salt))
	{
	$newsha1 = PwdHash($_POST['pwd_new']);
	mysql_query("update users set UserPassword='$newsha1' where UserID='$_SESSION[user_id]'");
	$msg[] = "Your new password is updated";
	//header("Location: mysettings.php?msg=Your new password is updated");
	} else
	{
	 $err[] = "Your old password is invalid";
	 //header("Location: mysettings.php?msg=Your old password is invalid");
	}

}

if($_POST['doSave'] == 'Save')  
{
// Filter POST data for harmful code (sanitize)
foreach($_POST as $key => $value) {
	$data[$key] = filter($value);
}


mysql_query("UPDATE users SET
			`UserName` = '$data[name]',
			`UserAddress` = '$data[address]',
			`UserPhone` = '$data[tel]',
			`UserFax` = '$data[fax]',
			`UserCountry` = '$data[country]',
			`UserWebsite` = '$data[web]'
			 WHERE UserID='$_SESSION[user_id]'
			") or die(mysql_error());

//header("Location: mysettings.php?msg=Profile Sucessfully saved");
$msg[] = "Profile Sucessfully saved";
 }
 
$rs_settings = mysql_query("select * from users where UserID='$_SESSION[user_id]'"); 
?>
<html>
<head>
<title>My Account Settings</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="JavaScript" type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script language="JavaScript" type="text/javascript" src="js/jquery.validate.js"></script>
  <script>
  $(document).ready(function(){
    $("#myform").validate();
	 $("#pform").validate();
  });
  </script>
<link href="styles-login.css" rel="stylesheet" type="text/css">
</head>

<body>
<table width="100%" border="0" cellspacing="0" cellpadding="5" class="main">
  <tr> 
    <td colspan="3">&nbsp;</td>
  </tr>
  <tr> 
    <td width="160" valign="top"><?php 
/*********************** MYACCOUNT MENU ****************************
This code shows my account menu only to logged in users. 
Copy this code till END and place it in a new html or php where
you want to show myaccount options. This is only visible to logged in users
*******************************************************************/
if (isset($_SESSION['user_id'])) {?>
      <?php } 
/*******************************END**************************/
?>
  <?php 
if (checkAdmin()) {
/*******************************END**************************/
?>
	  <?php } ?>
  <td width="732" valign="top">
<h3 class="titlehdr">My Account - Settings</h3>
      <p> 
        <?php	
	if(!empty($err))  {
	   echo "<div class=\"msg\">";
	  foreach ($err as $e) {
	    echo "* Error - $e <br>";
	    }
	  echo "</div>";	
	   }
	   if(!empty($msg))  {
	    echo "<div class=\"msg\">" . $msg[0] . "</div>";

	   }
	  ?>
      </p>
      <p>Here you can make changes to your profile. Please note that you will 
        not be able to change your email which has been already registered.</p>
	  <?php while ($row_settings = mysql_fetch_array($rs_settings)) {?>
      <form action="mysettings.php" method="post" name="myform" id="myform">
        <table width="90%" border="0" align="center" cellpadding="3" cellspacing="3" class="forms">
          <tr> 
            <td colspan="2"> Your Name / Company Name<br> <input name="name" type="text" id="name"  class="required" value="<?php echo $row_settings['UserName']; ?>" size="50"> 
              <span class="example">Your name or company name</span></td>
          </tr>
          <tr> 
            <td colspan="2">Address <span class="example">(full address with ZIP)</span><br> 
              <textarea name="address" cols="40" rows="4" class="required" id="address"><?php echo $row_settings['UserAddress']; ?></textarea> 
            </td>
          </tr>
          <tr> 
            <td>Country</td>
            <td><input name="country" type="text" id="country" value="<?php echo $row_settings['UserCountry']; ?>" ></td>
          </tr>
          <tr> 
            <td width="27%">Phone</td>
            <td width="73%"><input name="tel" type="text" id="tel" class="required" value="<?php echo $row_settings['UserPhone']; ?>"></td>
          </tr>
          <tr> 
            <td>Fax</td>
            <td><input name="fax" type="text" id="fax" value="<?php echo $row_settings['UserFax']; ?>"></td>
          </tr>
          <tr> 
            <td>Website</td>
            <td><input name="web" type="text" id="web" class="optional defaultInvalid url" value="<?php echo $row_settings['UserWebsite']; ?>"> 
              <span class="example">Example: http://www.domain.com</span></td>
          </tr>
          <tr> 
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
          <tr> 
            <td>User Name</td>
            <td><input name="user_name" type="text" id="web2" value="<?php echo $row_settings['UserName']; ?>" disabled></td>
          </tr>
          <tr> 
            <td>Email</td>
            <td><input name="user_email" type="text" id="web3"  value="<?php echo $row_settings['UserEmail']; ?>" disabled></td>
          </tr>
        </table>
        <p align="center"> 
          <input name="doSave" type="submit" id="doSave" value="Save">
        </p>
      </form>
	  <?php } ?>
      <h3 class="titlehdr">Change Password</h3>
      <p>If you want to change your password, please input your old and new password 
        to make changes.</p>
      <form name="pform" id="pform" method="post" action="">
        <table width="80%" border="0" align="center" cellpadding="3" cellspacing="3" class="forms">
          <tr> 
            <td width="31%">Old Password</td>
            <td width="69%"><input name="pwd_old" type="password" class="required password"  id="pwd_old"></td>
          </tr>
          <tr> 
            <td>New Password</td>
            <td><input name="pwd_new" type="password" id="pwd_new" class="required password"  ></td>
          </tr>
        </table>
        <p align="center"> 
          <input name="doUpdate" type="submit" id="doUpdate" value="Update">
        </p>
        <p>&nbsp; </p>
      </form>
      <p>&nbsp; </p>
      <p>&nbsp;</p>
	   
      <p align="right">&nbsp; </p></td>
    <td width="196" valign="top">&nbsp;</td>
  </tr>
  <tr> 
    <td colspan="3">&nbsp;</td>
  </tr>
</table>

</body>
</html>

Thank you very much to anyone who can help with this issue! If you don't mind please post sample code.

Chris,

If my understanding is correct, then you first need to fix MYSETTINGS.PHP (and any other pages) to make its output suitable for insertion into the document.

You don't need, and should not have, all the page-structure stuff, which is already in place in index.php. Content is inserted into a div, not a frame/iframe.

In MYSETTINGS.PHP, purge out the html, head and body tags, and the head's contents. This should leave you with raw HTML starting with <table ...> and ending with </table>.

Then, there appears to be nothing to suppress regular HTML form submission in MYSETTINGS.PHP. In the absense of such suppression, submission is guaranteed to reload MYSETTINGS.PHP as a top-level document (ie. the behaviour you describe) not as an ajax-handled response.

The main reason would appear to be that there'e no handler in place for $('form[name="pform"]').live('submit', function() {...}); , which, like the two form handlers that are in place, must return false to suppress regular form submission.

With a bit of luck, that will fix it.

Airshow

Airshow, thank you very much for your feedback and help on this issue. Your understanding is exactly correct. I would like the output to always be displayed back inside the div that the form was submitted from. That way the user interface does not change.

As you had suggested, I cleaned up the mysettings.php page and purged out the HTML, HEAD and BODY Tags so that it now starts and ends with the TABLE. Unfortunately, that was not enought to make it work. I'm not clear on how to suppress the regular HTML on form submission. If I take out of the form action "mysettings.php" and just leave it empty "", then the database does not get updated.

I also tried to create a form handler for $('form[name="pform"]').live('submit', function() {...}); similar to others already in the index.php page but still no luck..

If there is any possibility to get some sample code, I would very much appreciated it. Im going to post some updated code for both the mysettings.php and the index.php. Thanks you very much again for all your help!

<?php include('dbconfig.php'); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link href="twoColFixLt.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script language="JavaScript" type="text/javascript" src="js/jquery.validate.js"></script> 
<script type="text/javascript">

$(document).ready(function() {
 
   $('.sidebar1 a').click(function() {
    var $a = $(this);
    var url = $a.attr('href');
    var linkText = $a.html();
    var target = $a.attr('target');
    $.ajax({
      context: $('#'+target),
      error: function(XMLHttpRequest, textStatus, errorThrown){
        this.html('AJAX error<br>' + linkText + '<br>' + url);
      },
      success: function(data, textStatus, XMLHttpRequest) {
        this.html(data);
      },
      timeout: 5000,
      type: 'GET',
      url: url
      });
    return false;
  });

  $('form[name="MyForm"]').live('submit', function() {
    var form = $(this);
    var url = form.attr('action');
    var target = form.attr('target');
    var data = form.serialize();
    $.ajax({
      context: $('#'+target),
      data: data,
      error: function(XMLHttpRequest, textStatus, errorThrown){
        this.html('AJAX error<br>Form submitted: ' + form.attr('name') + '<br>' + url);
      },
      success: function(data, textStatus, XMLHttpRequest) {
        this.html(data);
      },
      timeout: 5000,
      type: 'POST',
      url: url
    });
    alert("Post form submitted");
    return false;
  });
});

  $('form[name="form1"]').live('submit', function() {
    var form = $(this);
    var url = form.attr('action');
    var target = form.attr('target');
    var data = form.serialize();
    $.ajax({
      context: $('#'+target),
      data: data,
      error: function(XMLHttpRequest, textStatus, errorThrown){
        this.html('AJAX error<br>Form submitted: ' + form.attr('name') + '<br>' + url);
      },
      success: function(data, textStatus, XMLHttpRequest) {
        this.html(data);
      },
      timeout: 5000,
      type: 'GET',
      url: url
    });
    alert("GET form submitted");
    return false;
  });

  $(document).ready(function(){
    $("#myform").validate();
     $("#pform").validate();
  });
  </script>

</head>

<body>

<div class="container">
  <div class="sidebar1">
    <ul class="nav">
            <li><a href="index.php" target="content">Home</a></li>
            <li><a href="mysettings.php" target="content">My Settings</a></li>  
    </ul>
    <p> </p>
    <!-- end .sidebar1 --></div>
 <div id="content" style="border:red solid 1px;">
    <h1>Div &quot;content&quot;</h1>
    </div>
    <!-- end .content --></div>
  <!-- end .container --></div>
</body>
</html>

Updated mysettings.php

<?php if (!isset($_SESSION)) {
    session_start();}
?>
<?php 
/********************** MYSETTINGS.PHP**************************
This updates user settings and password
************************************************************/

$_SESSION[user_id] = "3"; //Set variable for Testing only! 
$id = $_SESSION[user_id]; // Enabled to verify Session user_id is there. 
echo "SESSION user_id is:". $id ." <br />";

include 'dbc.php';
//page_protect();

$err = array();
$msg = array();

if($_POST['doUpdate'] == 'Update')  
{


$rs_pwd = mysql_query("select UserPassword from users where UserID='$_SESSION[user_id]'");
list($old) = mysql_fetch_row($rs_pwd);
$old_salt = substr($old,0,9);

//check for old password in md5 format
    if($old === PwdHash($_POST['pwd_old'],$old_salt))
    {
    $newsha1 = PwdHash($_POST['pwd_new']);
    mysql_query("update users set UserPassword='$newsha1' where UserID='$_SESSION[user_id]'");
    $msg[] = "Your new password is updated";
    //header("Location: mysettings.php?msg=Your new password is updated");
    } else
    {
     $err[] = "Your old password is invalid";
     //header("Location: mysettings.php?msg=Your old password is invalid");
    }

}

if($_POST['doSave'] == 'Save')  
{
// Filter POST data for harmful code (sanitize)
foreach($_POST as $key => $value) {
    $data[$key] = filter($value);
}


mysql_query("UPDATE users SET
            `UserName` = '$data[name]',
            `UserAddress` = '$data[address]',
            `UserPhone` = '$data[tel]',
            `UserFax` = '$data[fax]',
            `UserCountry` = '$data[country]',
            `UserWebsite` = '$data[web]'
             WHERE UserID='$_SESSION[user_id]'
            ") or die(mysql_error());

//header("Location: mysettings.php?msg=Profile Sucessfully saved");
$msg[] = "Profile Sucessfully saved";
 }
 
$rs_settings = mysql_query("select * from users where UserID='$_SESSION[user_id]'"); 
?>

<table width="100%" border="0" cellspacing="0" cellpadding="5" class="main">
  <tr> 
    <td colspan="3">&nbsp;</td>
  </tr>
  <tr> 
    <td width="160" valign="top"><?php 
/*********************** MYACCOUNT MENU ****************************
This code shows my account menu only to logged in users. 
Copy this code till END and place it in a new html or php where
you want to show myaccount options. This is only visible to logged in users
*******************************************************************/
if (isset($_SESSION['user_id'])) {?>
      <?php } 
/*******************************END**************************/
?>
  <?php 
if (checkAdmin()) {
/*******************************END**************************/
?>
      <?php } ?>
  <td width="732" valign="top">
<h3 class="titlehdr">My Account - Settings</h3>
      <p> 
        <?php    
    if(!empty($err))  {
       echo "<div class=\"msg\">";
      foreach ($err as $e) {
        echo "* Error - $e <br>";
        }
      echo "</div>";    
       }
       if(!empty($msg))  {
        echo "<div class=\"msg\">" . $msg[0] . "</div>";

       }
      ?>
      </p>
      <p>Here you can make changes to your profile. Please note that you will 
        not be able to change your email which has been already registered.</p>
      <?php while ($row_settings = mysql_fetch_array($rs_settings)) {?>
      <form action="mysettings.php" method="post" name="MyForm" id="MyForm">
        <table width="90%" border="0" align="center" cellpadding="3" cellspacing="3" class="forms">
          <tr> 
            <td colspan="2"> Your Name / Company Name<br> <input name="name" type="text" id="name"  class="required" value="<?php echo $row_settings['UserName']; ?>" size="50"> 
              <span class="example">Your name or company name</span></td>
          </tr>
          <tr> 
            <td colspan="2">Address <span class="example">(full address with ZIP)</span><br> 
              <textarea name="address" cols="40" rows="4" class="required" id="address"><?php echo $row_settings['UserAddress']; ?></textarea> 
            </td>
          </tr>
          <tr> 
            <td>Country</td>
            <td><input name="country" type="text" id="country" value="<?php echo $row_settings['UserCountry']; ?>" ></td>
          </tr>
          <tr> 
            <td width="27%">Phone</td>
            <td width="73%"><input name="tel" type="text" id="tel" class="required" value="<?php echo $row_settings['UserPhone']; ?>"></td>
          </tr>
          <tr> 
            <td>Fax</td>
            <td><input name="fax" type="text" id="fax" value="<?php echo $row_settings['UserFax']; ?>"></td>
          </tr>
          <tr> 
            <td>Website</td>
            <td><input name="web" type="text" id="web" class="optional defaultInvalid url" value="<?php echo $row_settings['UserWebsite']; ?>"> 
              <span class="example">Example: http://www.domain.com</span></td>
          </tr>
          <tr> 
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
          <tr> 
            <td>User Name</td>
            <td><input name="user_name" type="text" id="web2" value="<?php echo $row_settings['UserName']; ?>" disabled></td>
          </tr>
          <tr> 
            <td>Email</td>
            <td><input name="user_email" type="text" id="web3"  value="<?php echo $row_settings['UserEmail']; ?>" disabled></td>
          </tr>
        </table>
        <p align="center"> 
          <input name="doSave" type="submit" id="doSave" value="Save">
        </p>
      </form>
      <?php } ?>
      <h3 class="titlehdr">Change Password</h3>
      <p>If you want to change your password, please input your old and new password 
        to make changes.</p>
      <form name="pform" id="pform" method="post" action="">
        <table width="80%" border="0" align="center" cellpadding="3" cellspacing="3" class="forms">
          <tr> 
            <td width="31%">Old Password</td>
            <td width="69%"><input name="pwd_old" type="password" class="required password"  id="pwd_old"></td>
          </tr>
          <tr> 
            <td>New Password</td>
            <td><input name="pwd_new" type="password" id="pwd_new" class="required password"  ></td>
          </tr>
        </table>
        <p align="center"> 
          <input name="doUpdate" type="submit" id="doUpdate" value="Update">
        </p>
        <p>&nbsp; </p>
      </form>
      <p>&nbsp; </p>
      <p>&nbsp;</p>
       
      <p align="right">&nbsp; </p></td>
    <td width="196" valign="top">&nbsp;</td>
  </tr>
  <tr> 
    <td colspan="3">&nbsp;</td>
  </tr>
</table>

Chris,

A couple of things:

  • Still no handler for 'pform'....'submit'...
  • $(document).ready closes at the wrong point. It should wrap all the form handler structures.

the pform handler will look something like this (on the index page):

$(document).ready(function() {
  //...

  $('#pform').live('submit', function() {
    var $form = $(this);
    var url = 'mysettings.php';
    var $target = $('#content');
    var data = $form.serialize();
    $.ajax({
      data: data,
      error: function(XMLHttpRequest, textStatus, errorThrown){
        $target.html('AJAX error<br>Form submitted: ' + $form.attr('name') + '<br>' + url);
      },
      success: function(data, textStatus, XMLHttpRequest) {
        $target.html(data);
      },
      timeout: 5000,
      type: 'POST',//POST or GET depending on what mysettings.php expects.
      url: url
    });
    alert("pform submitted");
    return false;
  });

  //...
});//Make sure this is in the right place

If it still doesn't work, then try deleting the second $(document).ready(function() {...}); . I'm not sure how jQuery behaves when there's more than one. You can always move its two lines of code inside the first $(document).ready(function() {...}); structure.

Airshow

Airshow, Thank you very much for helping me with this issue. I went ahead and tried as you suggested the code for the “pform” but no joy yet.. With the supplied code, pform appears to be working as I wanted and it even triggers the alert "pform submitted". The mysettings form then successfully redisplays back inside the target div on the index page as I have been trying to do. However, there is a new problem in that the password field in the data table is not getting updated with the new password and I am not getting the msg from mysettings.php that "Your new password is updated". It appears that form has lost it functionality.

As a test, I loaded the mysettings form directly without using the index page. When I process the form the password gets updated in the data table and the success message displays. So while I am now able to keep the mysettings.php in the target div after submitting the request, I am losing the form function.

Also in the index.php page, I have a few different “Alerts” to show me that the ajax code is excuting. However, at this time the only one that is actually working is the one for “pform”. The others for “MyForm” POST and GET are not being triggered, so I am thinking as you suggested, that I have a few problems with either $(document).ready closing at the wrong point or some other coma, bracket or other syntax problem interfering with the code.

I really appreciate your help! Any sample code that you can provide to help fix this would be greatly appreciated.

Here is the updated index.php page:

<?php include('dbconfig.php'); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link href="twoColFixLt.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script language="JavaScript" type="text/javascript" src="js/jquery.validate.js"></script> 
<script type="text/javascript">

$(document).ready(function() {

   $('.sidebar1 a').click(function() {
    var $a = $(this);
    var url = $a.attr('href');
    var linkText = $a.html();
    var target = $a.attr('target');
    $.ajax({
      context: $('#'+target),
      error: function(XMLHttpRequest, textStatus, errorThrown){
        this.html('AJAX error<br>' + linkText + '<br>' + url);
      },
      success: function(data, textStatus, XMLHttpRequest) {
        this.html(data);
      },
      timeout: 5000,
      type: 'GET',
      url: url
      });
    return false;
  });

 
  $('form[name="MyForm"]').live('submit', function() {
    var form = $(this);
    var url = form.attr('action');
    var target = form.attr('target');
    var data = form.serialize();
    $.ajax({
      context: $('#'+target),
      data: data,
      error: function(XMLHttpRequest, textStatus, errorThrown){
        this.html('AJAX error<br>Form submitted: ' + form.attr('name') + '<br>' + url);
      },
      success: function(data, textStatus, XMLHttpRequest) {
        this.html(data);
      },
      timeout: 5000,
      type: 'POST',
      url: url
    });
    alert("Post form submitted");
    return false;
  });

  $('form[name="form1"]').live('submit', function() {
    var form = $(this);
    var url = form.attr('action');
    var target = form.attr('target');
    var data = form.serialize();
    $.ajax({
      context: $('#'+target),
      data: data,
      error: function(XMLHttpRequest, textStatus, errorThrown){
        this.html('AJAX error<br>Form submitted: ' + form.attr('name') + '<br>' + url);
      },
      success: function(data, textStatus, XMLHttpRequest) {
        this.html(data);
      },
      timeout: 5000,
      type: 'GET',
      url: url
    });
    alert("GET form submitted");
    return false;
  });
      
      //$(document).ready(function(){
    $("#myform").validate();
     $("#pform").validate();
  }); 
    $('#pform').live('submit', function() {
    var $form = $(this);
    var url = 'mysettings.php';
    var $target = $('#content');
    var data = $form.serialize();
    $.ajax({
      data: data,
      error: function(XMLHttpRequest, textStatus, errorThrown){
        $target.html('AJAX error<br>Form submitted: ' + $form.attr('name') + '<br>' + url);
      },
      success: function(data, textStatus, XMLHttpRequest) {
        $target.html(data);
      },
      timeout: 5000,
      type: 'POST',//POST or GET depending on what mysettings.php expects.
      url: url
    });
    alert("pform submitted");
    return false;
  });
  
  </script>

</head>

<body>

<div class="container">
  <div class="sidebar1">
    <ul class="nav">
            <li><a href="index.php" target="content">Home</a></li>
            <li><a href="mysettings.php" target="content">My Settings</a></li>  
    </ul>
    <p> </p>
    <!-- end .sidebar1 --></div>
 <div id="content" style="border:red solid 1px;">
    <h1>Div &quot;content&quot;</h1>
    </div>
    <!-- end .content --></div>
  <!-- end .container --></div>
</body>
</html>

Chris,

I can't immediately see why it shouldn't be working.

I think that HTML inputs of type="password" won't redisplay a value so temporarily set to type="text" for debugging (and remember to remove the value="$pwd" from the php file before deploying so it ca't be read with 'view source').

$(document).ready(function(){...}) still doesn't bracket the new 'pform' block, though that is probably not critical ( because it uses .live() ).

Try alert(data) immediately after var data = $form.serialize(); . Inspect to see it's what you would expect.

Airshow

Hi Airshow, Thanks for all of the advice and for the tip on adding alert(data)to see the data being passed on the form. That is now showing me the old and new password, but for some reason the form is still not validating or processing that information and sending it to the database. The change password pform by design does not echo results from the database. For some reason, which I cannot figure out, the validation process is not triggering or happening and maybe that is why the form does not finish processing and possibly the problem with both forms on the mysettings.php page. Because they both use a validation.

For debugging my focus had been on trying to get the first form on the mysettings.php page, "MyForm" to work. It seems to ignore the AJAX script altogether. Even though I think I have the AJAX script correct for "MyForm", submit and POST. None of the Alerts are triggering for the MyForm script. I have looked over the script carefully but as a newbie, I cannot seem to see anything that would cause it not to work.

I really appreciate your help and advice! Your code suggestions have been a big help to me to get this moving in the right direction. Thanks for all your help and any code suggestions that you may have.

I'm not sure if this applies to your code, but something to be aware of is that jQuery's form.serialize() does not, unlike regular HTML form submission, include a submit button's name|value pair in the serialization so the php script must not depend on seeing this pair. I don't know why the good people at jQuery decided to code it this way.

For single-action scripts, this is not an issue.

For multiple-action php scripts, you need to signal the required action in a different way - ie. not involving the submit button's name|value. Typically, you will have a hidden name="action" field which can be staticly or dynamically populated with a string to determine the right action (ie the right branch on the php code).

Alternatively, you can have different php scripts for different actions. Any common blocks of code can be pullud in with include(..).

Airshow

Airshow, Thanks for your suggestion. After a lot of reading, googling, trial and error.. Im still not able to get the form to successfully POST to the database and then redisplay the new results back inside the content div on the index.php page.

At this point after I change some data on the form and click Save, the alert(data) shows the correct information from the text fields being captured but then it gets lost. The code does not seem to go back through the mysettings.php code and excute the update database code. In mysettings.php file there is a line that states: if($_POST == 'Save')which is empty when the form initially loads but once new user information is entered and submit is clicked then the value should change to = Save and then the UPDATE script runs at that point.

It seems as though the AJAX script does not go back through that PHP code looking for that change and executing the UPDATE To the database? I tried creating a separate script to just isolate and run the MySQL UPDATE script but I was unsuccessful.

The mysettings.php page has not changed since the original post because I believe the problem is with my AJAX code in the index.php page. Here is the lastest AJAX script that I have been working with. If you or anyone else can possibly see a problem with it or help me with example code that would help me fix this issue, I would greatly appreciate it. Thanks for all your help in advance.

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script language="JavaScript" type="text/javascript" src="js/jquery.validate.js"></script> 
<script type="text/javascript">

$(document).ready(function() {
    $('#myform').live('submit', function() {
    var $form = $(this);
    var url = "mysettings.php";
    var $target = $('#content');
    var data = $form.serialize();
    alert(data); 
    $.ajax({
      data: data,
      error: function(XMLHttpRequest, textStatus, errorThrown){
        $target.html('AJAX error<br>Form submitted: ' + $form.attr('name') + '<br>' + url);
      },
      success: function(data, textStatus, XMLHttpRequest) {
        $target.html(data);   
      },
      timeout: 5000,
      type: 'POST',//POST or GET depending on what mysettings.php expects.
      url: url
    });
    return false;
  });  
</script>

Chris,

I think the javascript is OK.

Read my last post again then consider the following condition in mysettings.php :

if($_POST['doUpdate'] == 'Update')  { .... }

That clause contains the block of code to update the password, which is the action that's not happening.


Airshow

Hi Airshow, thanks for trying to point me in the right direction again.. I did read your previous post again and again.. I was have a hard time fully understanding it and trying to make it work. As we know there are two if($_POST... in the mysettings.php.

The first one is the one I would most like to figure out which is: if($_POST == 'Save'.. This is the one that will perform the Update to the table for user's information except the password.

I have been trying to figure out how to use the hidden name="action" to trigger the UPDATE to take place. But I have not been able to figure out how to make that work. Alternatively as you suggested, I have also been trying to figure out where I would put ie.. include(update.php) so that it would be triggered properly to UPDATE the data table and then allow the form to show the new results in the Content div..

You have been very helpful and I appreciate all of your suggestions and advice. If you could show me how to use the hidden name code to trigger this UPDATE and the include ().. I would be very grateful and I think I could resolve this. As you also mentioned, I believe now that the javascript is ok and it a matter of re-triggering the PHP code the started the UPDATE for the MySQL that was originally excuted on the initial load of the form and is now getting ignored by the javascript... Thanks again in advance.

Chris,

First make the "MyForm" handler match the "pform" handler:

$(document).ready(function() {

  // .........

  $('form[name="MyForm"]').live('submit', function() {
    var $form = $(this);
    var url = 'mysettings.php';
    var $target = $('#content');
    var data = $form.serialize();
    $.ajax({
      data: data,
      error: function(XMLHttpRequest, textStatus, errorThrown){
        $target.html('AJAX error<br>Form submitted: ' + $form.attr('name') + '<br>' + url);
      },
      success: function(data, textStatus, XMLHttpRequest) {
        $target.html(data);
      },
      timeout: 5000,
      type: 'POST',
      url: url
    });
    alert("MyForm submitted");
    return false;
  });

  $('#pform').live('submit', function() {
    var $form = $(this);
    var url = 'mysettings.php';
    var $target = $('#content');
    var data = $form.serialize();
    $.ajax({
      data: data,
      error: function(XMLHttpRequest, textStatus, errorThrown){
        $target.html('AJAX error<br>Form submitted: ' + $form.attr('name') + '<br>' + url);
      },
      success: function(data, textStatus, XMLHttpRequest) {
        $target.html(data);
      },
      timeout: 5000,
      type: 'POST',
      url: url
    });
    alert("pform submitted");
    return false;
  });

  // .........

});

(I'm not sure about the "form1" handler but presumably it will also be very similar)

Then, in mysettings.php, adjust to read $_POST.

if($_POST['action'] == 'save') {
  ...
}
if($_POST['action'] == 'update') {
  ...
}

(Alternatively, use a switch/case structure)

In the HTML (as built further down in mysettings.php), your two forms are each dedicated to a single action, so you can have hard-coded, hidden name="action" fields, like this:

<form id="MyForm">
          ......
          <input type="hidden" name="action" value="save">
          <input type="submit" value="Save">
          ......
      </form>

      <form id="pform">
          ......
          <input type="hidden" name="action" value="update">
          <input type="submit" value="Update">
          ......
      </form>

There's no need to use include(), just be aware that it can be useful if one day you have separate php scripts to handle different actions.

I have not been able to test but this certainly stands a chance of working.

Airshow

Airshow, this time it worked! Thank you very much!
It turns out as you suggest that the PHP script that triggers the UPDATE or INSERT function for MySQL was dependent on the forms submit button name|value which gets ignored by jquery’s form serialization.
So in order to work around this I had to add into each form: <input type="hidden" name="doUpdate" value="Update"> to excute the PHP code necessary to perform the function. I put this code above the normal HTML submit code: <input name="doUpdate" type="submit" id="doUpdate" value="Update">. This way the PHP code gets triggered regardless if the user has java enable or disabled.
Now when using jquery the form performs the required PHP code and redisplays the results back inside the target div “content” in the index.php page as well.
Thanks again for taking time and getting me on the right track and fixing the problem. This thread is Solved!
For anyone else that may have the same issue or want to do the same thing, I am posting the final working “fairly” clean code below for both index.php and mysettings.php.

index.php

<?php include('dbconfig.php'); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link href="twoColFixLt.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script language="JavaScript" type="text/javascript" src="js/jquery.validate.js"></script> 
<script type="text/javascript">

$(document).ready(function() {

   $('.sidebar1 a').click(function() {
    var $a = $(this);
    var url = $a.attr('href');
    var linkText = $a.html();
    var target = $a.attr('target');
    $.ajax({
      context: $('#'+target),
      error: function(XMLHttpRequest, textStatus, errorThrown){
        this.html('AJAX error<br>' + linkText + '<br>' + url);
      },
      success: function(data, textStatus, XMLHttpRequest) {
        this.html(data);
      },
      timeout: 5000,
      type: 'GET',
      url: url
      });
    return false;
  });

 //* myform - working with mysettings.php*/ 
 // *need to have in myform in mysetting.php <input type="hidden" name="doSave" value="save"> to trigger the PHP & MySQL UPDATE to database**
    $('#myform').live('submit', function() {
    var $form = $(this);
    var url = "mysettings.php";
    var $target = $('#content');
    var data = $form.serialize();
    //alert(data); 
    $.ajax({
      data: data,
      error: function(XMLHttpRequest, textStatus, errorThrown){
        $target.html('AJAX error<br>Form submitted: ' + $form.attr('name') + '<br>' + url);
      },
      success: function(data, textStatus, XMLHttpRequest) {
        $target.html(data);   
      },
      timeout: 5000,
      type: 'POST',//POST or GET depending on what mysettings.php expects.
      url: url
    });
    //alert("Post myform submitted");
    return false;
  });  
 
    $('#pform').live('submit', function() {
    var $form = $(this);
    var url = 'mysettings.php';
    var $target = $('#content');
    var data = $form.serialize();
    alert(data); 
    $.ajax({
      data: data,
      error: function(XMLHttpRequest, textStatus, errorThrown){
        $target.html('AJAX error<br>Form submitted: ' + $form.attr('name') + '<br>' + url);
      },
      success: function(data, textStatus, XMLHttpRequest) {
        $target.html(data);
      },
      timeout: 5000,
      type: 'POST',//POST or GET depending on what mysettings.php expects.
      url: url
    });
    //alert("pform submitted");
    return false;
  });
                
     $("#myform").validate();
     $("#pform").validate();
  });  
 
 </script>                 
  
</head>

<body>

<div class="container">
  <div class="sidebar1">
    <ul class="nav">
            <li><a href="index.php" target="content">Home</a></li>
            <li><a href="mysettings.php" target="content">My Settings</a></li> 
    </ul>
    <p> </p>
    <!-- end .sidebar1 --></div>
 <div id="content" style="border:red solid 1px;">
    <h1>Div &quot;content&quot;</h1>
    </div>
    <!-- end .content --></div>
  <!-- end .container --></div>
</body>
</html>

mysettings.php:

<?php if (!isset($_SESSION)) {
    session_start();}
?>
<?php 
/********************** MYSETTINGS.PHP**************************
This updates user settings and password
************************************************************/

$_SESSION[user_id] = "3"; //Set variable for Testing only! 
$id = $_SESSION[user_id]; // Enabled to verify Session user_id is there. 
echo "SESSION user_id is:". $id ." <br />";
echo "POST doSave value is:  " . $_POST['doSave'] . "<br />";
echo "POST upDate value is:  " . $_POST['doUpdate'] . "<br />";  

include 'dbc.php';
//page_protect();

$err = array();
$msg = array();

if($_POST['doUpdate'] == 'Update')  
{

$rs_pwd = mysql_query("select UserPassword from users where UserID='$_SESSION[user_id]'");
list($old) = mysql_fetch_row($rs_pwd);
$old_salt = substr($old,0,9);

//check for old password in md5 format
    if($old === PwdHash($_POST['pwd_old'],$old_salt))
    {
    $newsha1 = PwdHash($_POST['pwd_new']);
    mysql_query("update users set UserPassword='$newsha1' where UserID='$_SESSION[user_id]'");
    $msg[] = "Your new password is updated";
    //header("Location: mysettings.php?msg=Your new password is updated");
    } else
    {
     $err[] = "Your old password is invalid";
     //header("Location: mysettings.php?msg=Your old password is invalid");
    }
}

if($_POST['doSave'] == 'Save')  
{
// Filter POST data for harmful code (sanitize)
foreach($_POST as $key => $value) {
    $data[$key] = filter($value);
}

mysql_query("UPDATE users SET
            `UserName` = '$data[name]',
            `UserAddress` = '$data[address]',
            `UserPhone` = '$data[tel]',
            `UserFax` = '$data[fax]',
            `UserCountry` = '$data[country]',
            `UserWebsite` = '$data[web]'
             WHERE UserID='$_SESSION[user_id]'
            ") or die(mysql_error());

//header("Location: mysettings.php?msg=Profile Sucessfully saved");
$msg[] = "Profile Sucessfully saved";
 }
 
$rs_settings = mysql_query("select * from users where UserID='$_SESSION[user_id]'"); 
?>
<html>
<head>
<title>My Account Settings</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="styles-login.css" rel="stylesheet" type="text/css">
</head>

<body>
<table width="100%" border="0" cellspacing="0" cellpadding="5" class="main">
  <tr> 
    <td colspan="3">&nbsp;</td>
  </tr>
  <tr> 
    <td width="160" valign="top"><?php 
/*********************** MYACCOUNT MENU ****************************
This code shows my account menu only to logged in users. 
Copy this code till END and place it in a new html or php where
you want to show myaccount options. This is only visible to logged in users
*******************************************************************/
if (isset($_SESSION['user_id'])) {?>
      <?php } 
/*******************************END**************************/
?>
  <?php 
//if (checkAdmin()) {
/*******************************END**************************/
?>
      <?php //} ?>
  <td width="732" valign="top">
<h3 class="titlehdr">My Account - Settings</h3>
      <p> 
        <?php    
    if(!empty($err))  {
       echo "<div class=\"msg\">";
      foreach ($err as $e) {
        echo "* Error - $e <br>";
        }
      echo "</div>";    
       }
       if(!empty($msg))  {
        echo "<div class=\"msg\">" . $msg[0] . "</div>";

       }
      ?>
      </p>
      <p>Here you can make changes to your profile. Please note that you will 
        not be able to change your email which has been already registered.</p>
      <?php while ($row_settings = mysql_fetch_array($rs_settings)) {?>
      <form action="mysettings.php" method="post" name="myform" form id="myform">
        <table width="90%" border="0" align="center" cellpadding="3" cellspacing="3" class="forms">
          <tr> 
            <td colspan="2"> Your Name / Company Name<br> <input name="name" type="text" id="name"  class="required" value="<?php echo $row_settings['UserName']; ?>" size="50"> 
              <span class="example">Your name or company name</span></td>
          </tr>
          <tr> 
            <td colspan="2">Address <span class="example">(full address with ZIP)</span><br> 
              <textarea name="address" cols="40" rows="4" class="required" id="address"><?php echo $row_settings['UserAddress']; ?></textarea> 
            </td>
          </tr>
          <tr> 
            <td>Country</td>
            <td><input name="country" type="text" id="country" value="<?php echo $row_settings['UserCountry']; ?>" ></td>
          </tr>
          <tr> 
            <td width="27%">Phone</td>
            <td width="73%"><input name="tel" type="text" id="tel" class="required" value="<?php echo $row_settings['UserPhone']; ?>"></td>
          </tr>
          <tr> 
            <td>Fax</td>
            <td><input name="fax" type="text" id="fax" value="<?php echo $row_settings['UserFax']; ?>"></td>
          </tr>
          <tr> 
            <td>Website</td>
            <td><input name="web" type="text" id="web" class="optional defaultInvalid url" value="<?php echo $row_settings['UserWebsite']; ?>"> 
              <span class="example">Example: http://www.domain.com</span></td>
          </tr>
          <tr> 
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
          <tr> 
            <td>User Name</td>
            <td><input name="user_name" type="text" id="web2" value="<?php echo $row_settings['UserName']; ?>" disabled></td>
          </tr>
          <tr> 
            <td>Email</td>
            <td><input name="user_email" type="text" id="web3"  value="<?php echo $row_settings['UserEmail']; ?>" disabled></td>
          </tr>
        </table>
        <p align="center"> 
          
          <input type="hidden" name="doSave" value="Save">  
          <input name="doSave" type="submit" id="doSave" value="Save">
          
        </p>
      </form>
      <?php } ?>
      <h3 class="titlehdr">Change Password</h3>
      <p>If you want to change your password, please input your old and new password 
        to make changes.</p>
      <form name="pform" form id="pform" method="post" action="">
        <table width="80%" border="0" align="center" cellpadding="3" cellspacing="3" class="forms">
          <tr> 
            <td width="31%">Old Password</td>
            <td width="69%"><input name="pwd_old" type="password" class="required password"  id="pwd_old"></td>
          </tr>
          <tr> 
            <td>New Password</td>
            <td><input name="pwd_new" type="password" id="pwd_new" class="required password"  ></td>
          </tr>
        </table>
        <p align="center"> 
          <input type="hidden" name="doUpdate" value="Update">     
          <input name="doUpdate" type="submit" id="doUpdate" value="Update">
        </p>
        <p>&nbsp; </p>
      </form>
      <p>&nbsp; </p>
      <p>&nbsp;</p>
       
      <p align="right">&nbsp; </p></td>
    <td width="196" valign="top">&nbsp;</td>
  </tr>
  <tr> 
    <td colspan="3">&nbsp;</td>
  </tr>
</table>

</body>
</html>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.