jQuery Mobile users know how form handling can be a pain in the ass. In jQuery Mobile, form submissions are automatically handled using Ajax whenever possible, creating a smooth transition between the form and the result page.
Unfortunately, this functionality blocks classic form handling. To submit a form without Ajax, you can either disable Ajax form handling globally, or per form via the data-ajax=”false” attribute.
Because Ajax is a necessary part of jQuery Mobile page handling, disabling it is usually not an option. That’s why data-ajax=”false” is our best choice in solving this conundrum.
This article will cover two different ways of form submitting in jQuery Mobile application. First example will use form and server side to generate jQuery Mobile content. This solution is mostly used in classic jQuery Mobile applications when server side page generation is still a viable option.
On the other hand, when working with jQuery Mobile hybrid applications (Android or iOS), classic server-side content generation is out of a question. This is mostly due to Apple app store rules which prohibit certain kind of hybrid mobile apps. We can circumvent this rule with a REST call and that’s going to be a second example.

Note: If this tutorial was helpful, need further clarification, something is not working or do you have a request for another Ionic post? Furthermore, if you don't like something about this blog, if something is bugging you, don't like how I'm doing stuff here, again leave me a comment below. I'm here to help you, I expect the same from you. Feel free to comment below, subscribe to my blog, mail me to dragan.gaic@gmail.com, or follow and mention me on twitter (@gajotres). Thanks and have a nice day!

PS. If you want my help, if possible (even if it takes you some time to do that), create a working example I can play with. Use Plunker for AngularJS based questions or jsFiddle for jQuery/jQuery Mobile based questions.


Table of Content


Classic form handling

I already told you that jQuery Mobile uses Ajax for form handling and that we can do it with a data-ajax=”false” attribute. It can be used like this:
<form data-ajax="false" method="post" action="second.php">
When the submit button is pressed, it will result in a full page refresh. This will prevent jQuery Mobile from using page transitions so be careful (if you still need page transitions then take a look at a second example).
First HTML file example – first.php
<!DOCTYPE html>
    <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.3.2/jquery.mobile-1.3.2.min.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script> 
    <div data-role="page" id="first" data-theme="b">
        <div data-role="header" data-theme="a">
            <h3>Login Page</h3>

        <div data-role="content">
            <form id="check-user" class="ui-body ui-body-a ui-corner-all" data-ajax="false" method="post" action="second.php">
                    <div data-role="fieldcontain">
                        <label for="username">Enter your username:</label>
                        <input type="text" value="" name="username" id="username"/>
                    <div data-role="fieldcontain">                                      
                        <label for="password">Enter your password:</label>
                        <input type="password" value="" name="password" id="password"/> 
                    <input type="submit" data-theme="b" name="submit" id="submit" value="Submit">
Second HTML file example – second.php
    // You can use username and password to authorize a user, I will just use it to display a welcome message
    $username = $_POST['username'];
    $password = $_POST['password'];	
<!DOCTYPE html>
    <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.3.2/jquery.mobile-1.3.2.min.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script> 
    <div data-role="page" id="second">
        <div data-theme="a" data-role="header">
            <h3>Welcome Page</h3>

        <div data-role="content">
            Welcome <?php if(isset($password)){echo $password;}?>
There’s nothing to be said here more than I already said. This is a classic form handling minimally changed to accommodate jQuery Mobile form handling fix.

Ajax form handling

If you’re planning to create a hybrid mobile application, this solution is going to be your best choice. Hybrid mobile apps occasionally get a bad rap as being more difficult to get approved in the iOS app store versus their native counterparts. If you application looks and feels like a web-site, it probably won’t pass the review, this is especially true to server-side content generation.
Continue Reading
  • Jimmy

    But how you prevent user directly type the index.html#second without type user name and password? since the Javascript shows ‘$.mobile.changePage(“#second”); ‘

    • This is an easy example made to show you how to best handle forms with jQuery Mobile. I never intended to create full proof jQuery Mobile login form.

  • eddy

    Ok cool
    but this doesn’t work on Phonegap with jqm 1.4.0 so something maybe wrong thanks

  • eddy

    i mean the ajax submit don’t work i copied it exactly as is and run on phonegap not working form the ajax call don’t get exectued

  • Stefano

    Hi! Excuse me, i tried to realize this example but i failed. I can’t post data from index.html to check.php. I alerted username and password before the asynchronus call in index.js and i find them correctly (?username=ste&password=ste), but when i’ve tried to catch them in check.php I’ve got a “null”. I’ve tried also to force the value of $username in check.php and it returned the correct value. I don’t know where is the mistake. Can you help me please? ty

    • Have you used some kind browser development tool to check if data is successfully posted to your php page? For example Firefox/Chrome Firebug tool? Or Chrome/Firefox Developer tools?

  • Stefano

    I controlled the request with chrome developer’s tools and the formData sent is right. The problem is in the receiving of posted data in check.php page, which is null. Better, i checked with if(isset($_POST[‘formData’])) and it return true. But $_POST[‘formData’] is null.

  • Stefano
    • Try this code:

      parse_str($_POST[‘formData’], $output);

      // Get username
      $username = $output[‘username’];
      // Get password
      $password = $output[‘password’];

      parse_str function will parse serialized string into variables, or in my case into an array. I have tested this snipet on my files and it works correctly.

      Basically let check.php looks like this:

      // Prevent caching.
      header(‘Cache-Control: no-cache, must-revalidate’);
      header(‘Expires: Mon, 01 Jan 1996 00:00:00 GMT’);

      // The JSON standard MIME header.
      header(‘Content-type: application/json’);

      // We don’t need action for this tutorial, but in a complex code you need a way to determine Ajax action nature
      $action = $_POST[‘action’];
      // Decode parameters into readable PHP object
      parse_str($_POST[‘formData’], $output);

      // Get username
      $username = $output[‘username’];
      // Get password
      $password = $output[‘password’];

      // Lets say everything is in order
      $output = array(‘status’ => true, ‘massage’ => $username);
      echo json_encode($output);

  • Stefano

    Thankyou for your help. I tried your suggestion but I can’t make it work. The only way I can work around the problem is removing “header(‘Content-type: application/json’);” from check.php and posting directly “data: $(‘#check-user’).serialize(),” in ajax call. In this way i found my form fields in $_POST array. Do you have any idea about why my system filters those requests that have a “json application” header?

    • In this case you can remove those headers. They are more problematic then useful and your code will work just fine without them.

      I will even remove them from my example, just to be on a safe side.

  • Stefano

    here I have posted all the adventure. If you want to check:


    thank you again for your help and for your code! =)

  • lmueller74

    what if i want the mobile form handler to handle the form submission – how do i get the results of the ajax request?

  • Edi

    Nonetless best article about ajax form handling on the internet thumbs up Thanks for the sharing 😉

  • Harley

    This is indeed the best article about ajax form I have seen online so far. You are a lifesaver.

  • ali

    How can I fieldcontain link to another page
    back to page
    back to page2
    back to page3
    back to page4
    please help me
    thank you very

    • It would be easy if you could show me your question on some specific example, but I can give you non specific answer. In your case you would need to bind a click event to each element of field container. Also give each element some dummy attribute like this: data-link=”” and fill each one of them with destination page (index.html, show.html ….). When click event resolves, get data-link attribute of that specific clicked element and programatically (using method $.mobile.changePage) change your page.

  • Ramkumar

    how to pass first page textbox value into next page in jquerymobile.

  • Greg

    This is really good. I did steal this and some of what Stefano tweaked to achieve what I needed to do. Great write up !

  • Zach

    When I run the code I keep getting the following error in the PHP file:

    Notice: Trying to get property of non-object

    The non-object it is referring to is formData.

    Here is the snippet from the AJAX call with the formData object
    data: {formData: $(‘#form-set-the-bar’).serialize()},

    Here is the PHP script that cant seem to grab the formData object
    // Decode JSON object into readable PHP object
    $formData = json_decode($_POST[‘formData’]);

    // Get atosphere
    $atmosphere = $formData->{‘atmosphere_slider’};

  • Paula Davis

    Thanks for this useful post! I’ve bookmarked for future reference. Another site that I also recommend that you haven’t included in your post is http://www.dreame.biz. I love it because it has more than 50+ Tutorials.

  • GranTitot

    I thank for this tutorial. It deeps and guides about the ajax difficulties.
    I have been googling about a navigation problem after the ajax call with no success, it is a hard question, and I am not able to find any help googling.

    I’m developing an App with JQuery Mobile + Phonegap + PHP that includes a call to bank html page for credit card payment validation. I can send the buy info and make the payment, but the App can’t take the control again.

    The steps are as following:
    1. App sends the import to PHP in server1
    2. PHP creates the form with a encrypted signature field and send back to device
    3. Device inserts the received form in the dom
    4. Device sends the form to the bank url in server2
    5. Bank url is showed in user’s device, user makes the payment correctly and press ‘Continue’ button’
    6. In case of success the bank url redirect to SuccessTransfer.php in server1

    All is Ok.

    The question is how can the ajax call retrieve the Ok from SuccessTransfer.php and make a $.mobile.changePage(). The Application don’t seems to receive anything.

    For interact with the App, the user can press device back button for see the previous pages, but it would be interesting retrieve the original instance of the open App.

    I have included jQuery.support.cors = true; $.mobile.allowCrossDomainPages = true; in mobileinit.

    The ajax call is as:

    type : “POST”,
    url : “http://www…./CreateForm.php”,
    traditional : true,
    data : ({Import: Total, Language:Language}),
    async: true,
    datatype : “json”,
    // response
    success: function(arrayPHP){
    //alert(“: ” + arrayPHP);
    Form = arrayPHP;

    The first form line is as:

    I tried with data-ajax=”false” also but no success.

    I tried to change .submit() for $.Post, include a handler, etc… but nothing seems to work.

    How must I post the data via ajax call in this case?

  • I am getting XMLHttpRequest cannot load check.php Origin null is not allowed by Access-Control-Allow-Origin.:1″

    Please help me

    • You are suffering from cross-domain access error, just goggle it and you will find more then enough working solutions.

  • Hafizur Rachman

    hai master, i want to ask you about ..
    on android isn’t work .. such as not function .. can you help me ?

  • Prolaznik Zeljan Znanja

    Pozz, pratio sam tvoje uputstvo i sklempao stranicu, ali iz nekog razloga login nece da radi uopste (Nedobijam nikakve greske, samo se stranica osvezi i tako stoji)

    Evo koda od jsa: http://pastebin.com/B58SRZP9
    Html kod: http://pastebin.com/ruYwNyNX

    Da li bi mogao da mi popravis ovaj kod?
    Unapred hvala 🙂

  • Amigo como faço para capturar dados do form sem precisar adicionar a pagina no action?


    $(‘form’). submit(function() {
    url: ”,
    type: ‘post’,
    cache: false,
    data: “acao=controlando”
    }).success(function() {
    alert(‘Cadastrado Com Sucesso!’);



    Dessa forma ai o json consegue enviar mas não encaminha os dados do formulário para a pagina informada via url

    Fico grato por um retorno.

  • Yacine

    Thank you for this great tuto. It helps me a lot to start learning how to deal with form data combining CodeIgniter php framework and jquery-mobile.

    But to go deeper, I need to know the best way to populate dynamically a div content in the page #second, after the success of the login process. Since in our case, if is set in the first load of the login page, it is always possible to edit the page within the browser and see the content.

    My php programming skill’s are okay. But I’m new with jquery.

    Best Regards.

  • Ni neu

    How could print the username on the second page?


  • neha

    hello my login page doesnt work(database connection) i did the same as the above code but it shows only error function i.e Network error has occurred please try again! can u please help me,it never goes to success function.

  • Hey Dragan,

    Thanks for you this great tutorial…. it is very helpful to me. But how to send image file with form data ??


    • It’s easy, convert your image to BASE64 string representation and send it via form. Just google: javascript convert image to base64 or find it here:

  • Tan

    This is a great help. This is my contribution to making the tutorial better.
    I actually couldn’t get it to work the first time .
    The codes snippnets in index.js has to change:

    $.mobile.showPageLoadingMsg(true) needs to be replaced with $.mobile.loading(‘show’)
    $.mobile.hidePageLoadingMsg() needs to be replaced with $.mobile.loading(‘hide’)

  • Mbakatre

    Hi DRAGAN,

    Seriouly I like your tuts but when I want to do other thing it doens’t work.
    For example when php file return the json data I Want to do for example:

    success: function (response,status) {
    $.each(response, function(i,item){
    if((item.status == ‘success’) && (item.username == myuser’)) {
    } else {


    It does not work. the result is : Undefined

    But when I do

    success: function (response,status) {


    The result is :

    {“username” : “myuser”, “pwd” : “mypwd”, “status” : “success”}

    But I cant access to the data in the array.

    How can I do? I trying to solve this there is more than 2 weeks.

    Thank you by advance.

  • Seth

    Thank you for the write up! I’m new to app development and using PhoneGap to build a hybrid with HTML/JS/CSS. I’ve written previous web projects with PHP and am struggling to understand how to structure the app pages efficiently without the dynamic element that PHP provides. I want the same footer on every page but all the jQuery Mobile docs show the footer hard coded in each page. This seems crazy to me. Is the answer to perform Ajax calls to footer.html, return the code, and put it where I want it? You said something about Apple rejecting apps which download code. Is this what they are frowning upon? Please advise, I’ve read many of your jQuery Mobile write ups and find them the most helpful. Thanks for your response!

  • Jason


    How do you get this to POST as JSON? Your current code does not work as is. It POSTs as a normal query and the JSON decode fails. I have to grab my variables in PHP from POST not the decoded Form Data.

    • You will find the answer among these comments. If you still can’t manage to make it work I will create you a working example.

      • Calm down and learn some manners, you’re a guest here, so act accordingly.

        A simple warning would suffice.

        The problem is fixed now.

  • Ali

    Thanks a lot. Its very useful info

  • Julio Ribeiro

    Thanks man! The first example save my day! Great job.

  • Edi Munoz Din Din

    HI!!! and thank you in advance for your great work here, i need help with some coding, i got a web page where i show a list of records in a mysql table, with a hyperlink when you click on it creates a variable liek world.php?id=1&xx=1050&yy=300 so when the user clicks it takes him to next page and scrool down and up to the x and y it works in web browers but not ok mobiles. can you help me?

  • Edi Munoz Din Din

    please please please help me when i use manuel type values it works but when i get values from php variable it doesnt works

  • John William

    Great & Helpful Tutorial. So easy to understand and use, Thanks for sharing with us.

    I have also created another Ajax Login Form Using jQuery and PHP

  • Theodore Yapi

    Hello family I want to make an application without redirection of privilege WebView , I ‘ll put my charger When mite privilege Whether it opens with The portable navigator Whereas I want Whether execute In ‘ application … ..

    Help me thank you

  • Firouzeh Tahbaz

    I have a multi-step form that I want to collect its data into a mysql table how should I do that?