Jquery Mobile: How to Correctly Submit Form Data

jQuery Mobile: How to correctly submit form data

Intro

This example was created using jQuery Mobile 1.2. If you want to see recent example then take a look at this article or this more complex one. You will find 2 working examples explained in great details. If you have more questions ask them in the article comments section.

Form submitting is a constant jQuery Mobile problem.

There are few ways this can be achieved. I will list few of them.

Example 1 :

This is the best possible solution in case you are using phonegap application and you don't want to directly access a server side php. This is an correct solution if you want to create an phonegap iOS app.

index.html

<!DOCTYPE html>
<html>
<head>
<title>jQM Complex Demo</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<style>
#login-button {
margin-top: 30px;
}
</style>
<script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script src="js/index.js"></script>
</head>
<body>
<div data-role="page" id="login" data-theme="b">
<div data-role="header" data-theme="a">
<h3>Login Page</h3>
</div>

<div data-role="content">
<form id="check-user" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label for="username">Enter your username:</label>
<input type="text" value="" name="username" id="username"/>
</div>
<div data-role="fieldcontain">
<label for="password">Enter your password:</label>
<input type="password" value="" name="password" id="password"/>
</div>
<input type="button" data-theme="b" name="submit" id="submit" value="Submit">
</fieldset>
</form>
</div>

<div data-theme="a" data-role="footer" data-position="fixed">

</div>
</div>
<div data-role="page" id="second">
<div data-theme="a" data-role="header">
<h3></h3>
</div>

<div data-role="content">

</div>

<div data-theme="a" data-role="footer" data-position="fixed">
<h3>Page footer</h3>
</div>
</div>
</body>
</html>

check.php :

<?php
//$action = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
//$formData = json_decode($_REQUEST['formData']); // Decode JSON object into readable PHP object

//$username = $formData->{'username'}; // Get username from object
//$password = $formData->{'password'}; // Get password from object

// Lets say everything is in order
echo "Username = ";
?>

index.js :

$(document).on('pagebeforeshow', '#login', function(){  
$(document).on('click', '#submit', function() { // catch the form's submit event
if($('#username').val().length > 0 && $('#password').val().length > 0){
// Send data to server through ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({url: 'check.php',
data: {action : 'login', formData : $('#check-user').serialize()}, // Convert a form to a JSON string representation
type: 'post',
async: true,
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (result) {
resultObject.formSubmitionResult = result;
$.mobile.changePage("#second");
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all nececery fields');
}
return false; // cancel original event to prevent form submitting
});
});

$(document).on('pagebeforeshow', '#second', function(){
$('#second [data-role="content"]').append('This is a result of form submition: ' + resultObject.formSubmitionResult);
});

var resultObject = {
formSubmitionResult : null
}

Simple Form Submit in Jquery Mobile

I changed your html as below

<html> 
<head>
<title>Facility</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js"></script>
</head>
<body>

<div data-role="page" id="arealistpage">

<div data-role="header" data-theme="b">
<a href="Facility.aspx" class='ui-btn-left ui-btn-back' data-icon='arrow-l' rel="external">Back</a>
</div><!-- /header -->

<div data-role="content">
<form id="form1" method="post">
<div id="AreaNoDiv" data-role="fieldcontain" class="field">
<label for="Facility">Facility*</label>
<input id="Facility" name="shipNo_r" type="text" required/>
</div>

<div id="desDiv" data-role="fieldcontain" class="field">

<label for="des" id="Label1" name="fnameLabel">Description*</label>
<input id="des" name="fname_r" type="text" required/>

</div>
<div id="submitDiv" data-role="fieldcontain" style="width: 30%">
<button class="btnLogin" data-theme="b" type="submit" id='mysubmit'>submit</button>
</div>

</form>

</div><!-- /content -->

<div data-role="footer" data-theme="b" data-position="fixed">

<div data-role="navbar">
<ul>

<li><a href="" data-role="tab" data-icon="arrow-u" class="returnTopAction">Top</a></li>
</ul>
</div>
</div>
</div><!-- /page -->
<script src="Submitscript.js" type="text/javascript"></script>
</body>
</html>

and your js as below

$('#arealistpage').live('pageshow',function(event){
var serviceURL = 'service1.asmx/SubmitList';
$('#mysubmit').bind('click', function(e){
var name = "chamara";
e.preventDefault();
$.ajax({
type: "POST",
url: serviceURL,
data: '{"name":"' + name + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
});

function successFunc(data, status) {

// parse it as object
var outStr = JSON.parse(data.d);
alert(outStr);
}

function errorFunc() {
alert('error');
}
});

and it works just fine.

Btw why do you serialise a string in your service. Serialise will helpful when you wanna convert C# objects into JSON string. Hope it would help you out.

How to submit a form inside a jQuery Mobile page?

I copied your code and inserted jquery mobile and after making a couple minor changes I am getting data posted. I ran it through echo commands, not DB inserts.

Take a look at the following:

Call on Jquery Mobile:

<!DOCTYPE html> 
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>
</head>

Rest of index.php page:

<div data-role="page">
<center>
<h3>Watch our videos above and share your opinion which manufacturer produces the best sport sedans</h3>
<form name="vote" action="logicDB.php" method="post" data-ajax="false">
<fieldset style = "width:60%;" data-role="controlgroup">
<legend>Choose a car:</legend>
<input type = "radio" name="rc1" id = "radio-choice-1" value = "Audi"/>
<label for="radio-choice-1">Audi</label>

<input type = "radio" name="rc1" id = "radio-choice-2" value = "BMW"/>
<label for="radio-choice-2">BMW</label>

<input type = "radio" name="rc1" id = "radio-choice-3" value = "Mercedes"/>
<label for="radio-choice-3">Mercedes</label>
</fieldset>
<input value = "SUBMIT" type = "submit" />
</form>
</center>

And finally the logicDB.php

if ($_POST['rc1'] == 'Audi') {
echo "Audi <br>";
}
if ($_POST['rc1'] == 'BMW') {
echo "BMW <br>";
}
if ($_POST['rc1'] == 'Mercedes') {
echo "Mercedes <br>";
}

The primary changes were to the

<fieldset style = "width:60%;" data-role="controlgroup">

and the data-ajax="false" I mentioned prior.

See if that works for you.

jQuery mobile form self-submit and calculate from inputs

Here's a solution for a single page application that doesn't send any data to the server:

<!doctype HTML>

<html class="ui-mobile">
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
</head>

<body class="ui-mobile-viewport">
<div data-role="page" data-theme="b" id="index">
<form name="formInput" method="post" data-ajax="false">
<div class="ui-field-contain">
<label for="name-1">Name:</label>
<input name="name-1" id="name-1" value="" minlength="2" type="text" />
</div>
<div class="ui-grid-a">
<div class="ui-block-a">
<input type="reset" value="Reset" data-icon="back"data-theme="a"/>
</div>
<div class="ui-block-b">
<a data-role="button" onclick="yourName();" data-theme="a">Submit</a>
</div>
</div>
</form>
</div>

<!-- Start of third page -->
<div data-role="page"data-theme="b"data-add-back-btn="true" data-back-btn-text = "Home" id="report">
<div data-role="header">
<a href="#" data-icon="back" data-rel="back" title="Go back">Back</a>
<h1>This is your name</h1>
</div>

<div data-role="content">
<label for="name-rep">Name:</label>
<input name="name-rep" id="name-rep" value="" minlength="2" type="text" />
</div>
</div>
</body>

<script>
function yourName() {
var name = $('#name-1').val();
$('#name-rep').val(name);

$.mobile.pageContainer.pagecontainer("change", "#report");
};
</script>
</html>

The crucial changes are:

  • Replacing the submit button with a link to avoid JQM handling the form submission.
  • Manually changing the page in the onclick handler.

This is for JQuery Mobile 1.4. The way you manually change the page is quite different from how it was in 1.3, so if you're using an older version just check the docs (the function is called changePage if I recall correctly).

Basic POST with JQuery Mobile from form using php

Just try jquery Ajax

<body>
<form>
<p>Username: </p><input type="text" id="username" value="" />
<p>Password: </p><input type="text" id="password" value="" />
<input type="button" onclick="submitLogIn()" value="Log In" />
</form>
<script>
function submitLogIn() {
alert("Submitting: " + $('#username').val() + $('#password').val());
var username =$('#username').val();
var password = $('#password').val();
$.ajax({
type: "POST",
url: "http://localhost/testerpage.php",
data:{"Username":username,"Password":password},
success: function(data) {
if (data) {

alert(data);
}
else {
alert('Successfully not posted.');
}
}
});

}

</script>
</body>
</html>

in PHP

<?php
$Username=$_POST["Username"]; //Also tried _POST
$Password=$_POST["Password"]; //Also tried _POST

//VALIDATION
if(
$Username=="" ||
$Password==""
) {
echo "Error";
} else {
echo "Success";
}
?>

jquery mobile changePage on form submit not working properly

You are missing your action attribute in your form tag. This often breaks functionality of forms in browsers. Try this:

<form id="fhome" method="POST" action="mainpage">

It shouldn't negatively affect your code as you hijack the submit action anyway.

UPDATE

Also, you are missing your closing </form> tag and another closing </div> tag after that.

Do you need to use a submit button? Would it work to use a button and its corresponding click event?

http://jsfiddle.net/shanabus/7yRph/3/

UPDATE 2, working with form submit

After you resolve the closing tags, add the preventDefault method call and the data-ajax="false" attribute as outlined here in the docs.

example: http://jsfiddle.net/shanabus/7yRph/9/



Related Topics



Leave a reply



Submit