Here's a technique I use often to provide an alternative method to HTML Form submission for JS Disabled Browsers.
Here's a Basic HTML Form with its corresponding jQuery script: ( **note: for sake of simplicity, I have placed the messageDiv on top of form **)
The messageDiv:
<div id="messageDiv"><?php if( isset($_GET['msg']) ) {
echo $_GET['msg']; } ?></div>
The form:
<form name="addCustomerForm" id="addCustomerForm" method="post" enctype="application/x-www-form-urlencoded" action="somefile.php">
<p>Name: <br />
<input type="text" name="customerName" />
</p>
<p> Address: <br />
<input type="text" name="customerAddress" />
</p>
<p>
<input type="submit" name="submit" value="Submit" /> <input type="reset" name="reset" value="Reset" />
<input type="hidden" name="return_url" value="URL_OF_CURRENT_PAGE" />
</p>
</form>
<script language="javascript" type="text/javascript">
<!--
$(function() {
$('#addCustomerForm').submit(function() {
// do form validation here
$.ajax({
type : "POST",
url : "somefile.php",
data : $(this).serialize() + "&return_type=json",
dataType : "json",
success: function(data){
if( data.error != '0' ) {
$('#messageDiv').addClass('error').html(data.msg);
} else {
$('#messageDiv').addClass('success').html(data.msg);
}
}
});
return false;
});
});
// -->
</script>
In the above JS code, I am adding an extra Post variable 'return_type' with value 'json', whenever I am posting by $.ajax technique.
Now, the following is the PHP Code on submission Page:
<?php
/** After Server side validation is done.. **/
$responseArr = array();
/** Assuming the process was successful **/
if($success) {
$responseArr = array (
'error' => '0',
'msg' => 'New Customer Added');
} else {
$responseArr = array (
'error' => '1',
'msg' => 'Error Adding Customer');
}
if( isset($_POST['return_type']) && $_POST['return_type'] == 'json' ) {
header("Content-Type: text/plain");
echo json_encode($responseArr);
exit;
} else {
// so, jQuery submission was not made..
header('Location: '.$_POST['return_url'].'?'.http_build_query($responseArr));
exit;
}
?>
The PHP code itself is self-explanatory. If there's a return_type in $_POST and has value 'json', then echo JSON values, otherwise redirect to return_url on $_POST passing the response values as $_GET.
Comments
Post a Comment