php - example - jQuery Mobile: How to correctly submit form data



jquery mobile data-role (8)

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  
}

https://src-bin.com

This is a jQuery Mobile question, but it also relates to pure jQuery.

How can I post form data without page transition to the page set into form action attribute. I am building phonegap application and I don't want to directly access server side page.

I have tried few examples but each time form forwards me to the destination php file.


Answer #1

Add this attribute :

data-ajax="false"

to your form. It will prevent jQuery Mobile from hijacking form handling.

Also read my other answer on how form should be handled with jQuery Mobile: https://.com/a/15205612/1848600

And a link to an official documentation: http://jquerymobile.com/demos/1.2.0/docs/forms/forms-sample.html


Answer #2

Is there a problem with simply using a standard button for your form submit, writing a click function for it, and then calling form submit when you are done validating? Something simple like this where I have a button named "inquire"

  $("#inquire").click(function () {
    if (validates()) {
        $("form").submit();
    } else showValidationErrors();

});

Answer #3

On using PHP and posting data

Use data-ajax = "false" is the best option on <form> tag.


Answer #4

Your code is correct so I would guess problem occurs during the ajax call.

First take a look at my other answer, I made a working example of jQuery Mobile ajax form submition: https://.com/a/15205612/1848600. My example uses PHP but logic is the same.

My call looks like this:

$.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!');
    }
}); 

Debugging with Firebug :

Your next step should be error debugging.

  • If you are using Firefox or Chrome install a plugin called Firebug.

    Here's a link: https://addons.mozilla.org/en-US/firefox/addon/firebug/

  • Install firebug, Firefox version is better then a Chrome one.

  • Open your page and Firebug plugin.

  • Inside a firebug window there's a tab bar on the top that starts with Console, HTML, CSS .. up to Cookies. Click on a Net tab. New tab bar will open below the main one. Now click on XHR tab and click on clear button (same tab bar, clear button is on the left side).

  • Click Submit form. Inside a firebug windows a new log line should appear something like "POST ..." or "GET ...". Click on it.

  • New content will be shown. Inside a new tab bar there's a Request (or Post or Get) tab. It is your request. If ajax call has reached its destination another tab should exist by the name Response.

  • Open Response and take a look. There should be error or real response like this JSON: {"message":"0","draftSaved":true,"disableEditor":false}. In case your response has a proper JSON output than an ajax call is a successful one.

Debugging with FIDLER :

You can even use tool called FIDLER: http://www.fiddler2.com/fiddler2/, it is a much better tool but it requires more time to get used to.

Fiddler is a Web Debugging Proxy which logs all HTTP(S) traffic between your computer and the Internet. Fiddler allows you to inspect all HTTP(S) traffic, set breakpoints, and "fiddle" with incoming or outgoing data. Fiddler includes a powerful event-based scripting subsystem, and can be extended using any .NET language.

Here's a video tutorial of Fiddler usage: http://www.youtube.com/watch?v=YkJ_Wsd-rtM


Answer #5

try event.preventDefault();

instead of return false;


Answer #6

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.


Answer #7

how to prevent jquery mobile page refresh on form submit?

You can either move the button out of the form or stop form from submitting at all, example

$("#form1").on('submit',function(){return false;});

That will stop the refresh.

Also I would recomend using jquery for handling click events, instead of onclick. example

$("#button1").on('vclick',function(){});

If you use click handlers on mobile devices that will delay the click for 200ms, which is a lot, so use vclick, you can read about vclick here





jquery-mobile