Skip to main content

HTML Form submission technique via jQuery


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

Popular posts from this blog

Android WorkManager

What is WorkManager? WorkManager is one of the  Android Architecture Components  and part of Android Jetpack, a new and opinionated take on how to build modern Android applications. WorkManager is an Android library that runs  deferrable  background work when the work’s  constraints  are satisfied. WorkManager is intended for tasks that require a  guarantee  that the system will run them even if the app exit s. In other words, WorkManager provides a battery-friendly API that encapsulates years of evolution of Android’s background behavior restrictions. This is critical for Android applications that need to execute background tasks! When to use WorkManager WorkManager handles background work that needs to run when various constraints are met, regardless of whether the application process is alive or not. Background work can be started when the app is in the background, when the app is in the foreground, or when the app star...

Getting Lat and Lon from Address in Google Maps Using PHP

Recently, I am working on an application where I have to convert addresses to their corresponding Lat and Lon. So, I decided to write on how to get Latitude and Longitude in Google Maps using only PHP. To use the technique explained below, you need to have a  Google Maps Key . The idea is simple. Make a request to Google Maps server, and it will return an XML (or JSON). Then, parse the XML to get the Lat and Lon. I use DomDocument and DomXPath for processing it. Below I have used the address:  100 City Centre Dr., Mississauga, Ontario . 1. $key    =  "....." ;  // your Google Maps key 2.   3. $address   = urlencode( '100 City Centre Dr., Mississauga, ON' ); 4.   5. $url   =  ' http://maps.google.com/maps/geo?q= ' . $address . '&output=xml&oe=utf8&key=' . $key ; 6. $dom   =  new   DomDocument(); 7. $dom ->load( $url ); At this point, the XML is loaded into the $dom. Now, it...

Sending Email in Android using JavaMail API without using the default android app(Builtin Email application)

I find a way sending a mail in android using the JavaMail API using Gmail authentication Steps to create a simple Project: MailSenderActivity.java YOUR PACKAGE ; import android . app . Activity ; import android . os . Bundle ; import android . util . Log ; import android . view . View ; import android . widget . Button ; public class MailSenderActivity extends Activity {     /** Called when the activity is first created. */     @Override     public void onCreate ( Bundle savedInstanceState ) {         super . onCreate ( savedInstanceState );         setContentView ( R . layout . main );         final Button send = ( Button ) this . findViewById ( R . id . send );         send . setOnClickListener ( new View . OnClickListener () {             public void onClick ( View v ) {       ...