This is a followup of a previous question: "iframe versus div + jquery". I load a form (form1.php) in a div of main.php. I want to be able to run the form within the div without refreshing main.php to populate a db. Here is main.php:
<html>
<head>
<script type="text/javascript" src="javascript/update-div.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
$("#submit_btn").click(function(e) {
e.preventDefault();
$.post('form1.php', $("#form1").serialize(), function(result) {
$("#fc").html(result); });
});
</scrip>
</head>
<body leftmargin="0px" topmargin="0px" marginheight="0px" marginwidth="0px" bgcolor="#FFFFFF">
<a href="javascript:ajaxpage('form1.php','fc')">form1</a>
<br>
<div id="fc"></div>
</body>
</html>
and this is the code for form1.php
<?php
$link = mysql_connect('localhost', 'login', 'pwd');
if (!$link) {die('Not connected : ' . mysql_error());}
$db_selected = mysql_select_db('db_name');
$name = strtoupper($_POST['name']);
$birth = strtoupper($_POST['birth']);
$act = $_POST['act'];
if($act == "save"){
$query="INSERT INTO `mnl_people` ( `name` , `birth`) VALUES ('$name', '$birth')";
mysql_query($query);
$idalbum=mysql_insert_id();
}
if(!empty($name)){
$html = "<p>Your name: <b>".$name."</b></p>";
$html .= "<p>Your birthplace: <b>".$birth."</b></p>";
echo("$html");
}
else{ ?>
<form name="form1" enctype='multipart/form-data'>
Name <input type='text' name='name' value=""><br>
<br/>
<br/>
Birthplace : <input type="text" name="birth"><br/>
<input type='submit' name='act' class='submit' value='save' id="submit_btn"/>
</form>
<?php
}
?>
Unfortunately, on submit click, main.php refreshes and show the following url: mnl/main.php?name=Johnb&birth=us&act=save. Also, eventhough a new field is added to the table 'mnl_people', there is no values for the field name
and birth
: i.e it seems that $name and $birth are empty. Could someone le me know what I am doing wrong. I am definitely missing something here. Thanks.
Use the .live version, so instead of
Use
The problem is that the moment you are attaching the click handler the form does not exist in the DOM, since you load it with ajax.
You did not declare the method of your form as
POST
so it uses theGET
method, but you try to get thePOST
values.Either add an attribute
method="POST"
to your form tag or use$_GET['field_name']
to retrieve it.