jQuery Mobile: How to correctly submit form data

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.


Solution 1:

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  
}

Solution 2:

I have run into same issue where I am calling another .php page from my index.html. The .php page was saving and retrieving data and drawing a piechart. However I found that when piechart drawing logic was added, the page will not load at all. The culprit was the line that calls the .php page from my index.html:

<form action="store.php" method="post">

If I change this to:

<form action="store.php" method="post" data-ajax="false">

, it will work fine.