Using AJAX with JQuery Mobile

Post to Twitter

JQuery Mobile is a rapidly growing framework for smartphones and tablets and is gaining a lot of developer attention. The nice thing about it is we can also use all the power of JQuery along with it. Today I’ll cover a simple example that uses JQuery Mobile and PHP to send some data to the server and get a personalized message back. A “Hello World JQuery Mobile with PHP” if you will.

I have a previous JQuery Mobile tutorial that uses Ajax so you can also refer to the code in there. The difference is that article uses a form, this one doesn’t.


Update – Nov. 11, 2010: Code updated to reflect changes in JQuery Mobile Alpha 2.

To get started I had a local web server and created a folder to put my files. I used Apache 2 but feel free to use anything that can run PHP. The PHP code is dead simple:

<?php
	echo "Hello " . $_REQUEST["name"];
?>

Save that in a file called callajax.php.

Note: Using Ajax in JQuery is simple, see the docs for more information.

The full code for the index.html file is as follows:

<!DOCTYPE html>
<html>
	<head>
	<title>JQuery Mobile AJAX</title>
	<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a2/jquery.mobile-1.0a2.min.css" />
	<script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
	<script src="http://code.jquery.com/mobile/1.0a2/jquery.mobile-1.0a2.min.js"></script>
</head>

<body>

	<script>
		$(function() {

			$("#callAjax").click(function() {
				var theName = $.trim($("#theName").val());

				if(theName.length > 0)
				{
					$.ajax({
					  type: "POST",
					  url: "http://10.0.2.2/mobileajax/callajax.php",
					  data: ({name: theName}),
					  cache: false,
					  dataType: "text",
					  success: onSuccess
					});
				}
			});

			$("#resultLog").ajaxError(function(event, request, settings, exception) {
			  $("#resultLog").html("Error Calling: " + settings.url + "<br />HTTP Code: " + request.status);
			});

			function onSuccess(data)
			{
				$("#resultLog").html("Result: " + data);
			}

		});
	</script>

    <div data-role="page" id="indexPage">
        <div data-role="header">
            <h1>JQuery Mobile</h1>
        </div>
        <div data-role="content">
			<div data-role="fieldcontain">
				<label for="theName">Please enter your name:</label>
				<input type="text" id="theName" name="theName" value="" />
			</div>
			<input id="callAjax" type="button" value="Call Ajax" />
			<div id="resultLog"></div>
        </div>

        <div data-role="footer">
        	<h1>AJAX Demo</h1>
        </div>
    </div>

</body>
</html>

A few things to note:

– The call to the server uses this address: http://10.0.2.2/mobileajax/callajax.php
This is because when I use the Android emulator to run this web app it doesn’t currently support “localhost” so you need to use the 10.0.2.2 address instead.

– I’m simply passing the value of the textbox to the PHP script (obviously you need some real security here in a production app as you should never trust data from the client). PHP processes this data and sends the reply back. If an error occurs in the Ajax call I capture that and print some data out.

Here are a couple screenshots:

Post to Twitter

This entry was posted in AJAX, JavaScript, Mobile, Online Games, PHP. Bookmark the permalink.

7 Responses to Using AJAX with JQuery Mobile

  1. SFdude says:

    Hi Chad,

    Thanks for the clear & thoughtful tutorial
    on “Using AJAX with JQuery Mobile”.
    Tried it. Works great!

    Q:
    Your clear example code,
    passes 1 User-entered field to the PHP script:
    – Name (dataType: “text”).

    Now…if you wanted to pass 2 User-entered fields
    to the PHP script:
    – Name (dataType: “text”) AND
    – Age (dataType: “number?”)

    Then, what would be the changes to the present Code ?:

    $(“#callAjax”).click(function() {
    var theName = $.trim($(“#theName”).val());

    if(theName.length > 0)
    {
    $.ajax({
    type: “POST”,
    url: “callajax.php”,
    data: ({name: theName}),
    cache: false,
    dataType: “text”,
    success: onSuccess
    });
    }
    });

    Thanks!
    SFdude

  2. Chad Lung says:

    @SFDude,

    Check out my article here where I pass more than one field (the form is serialized and passed via AJAX): http://www.giantflyingsaucer.com/blog/?p=1856

    Chad

  3. wHiTeHaT says:

    @SFdude :
    ajax code:

    $(function() {

    $("#callAjax").click(function() {
    var formData = $("#newPostForm").serialize();

    // if(theName.length > 0)
    //{
    $.ajax({
    type: "POST",
    url: "http://localhost/mobileajax/callajax.php",
    cache: false,
    data: formData,
    dataType: "text",

    success: onSuccess
    });
    // }
    });

    $("#resultLog").ajaxError(function(event, request, settings, exception) {
    $("#resultLog").html("Error Calling: " + settings.url + "HTPP Code: " + request.status);
    });

    function onSuccess(data)
    {
    data = $.trim(data);

    $("#resultLog").html(data);
    }

    });

    HTML Code:

    Post Title:

    Post Content:

    callajax.php code:


    <?php
    echo "PostTitle: " . $_REQUEST["postTitle"] . "PostHidden: " . $_REQUEST["postHidden"] . "PostContent: " . $_REQUEST["postContent"];
    ?>

    @Chadd in html5 it isnt needed to use the script language= “”, simply use

  4. Pingback: Submit a JQuery Mobile form via AJAX with PHP | Giant Flying Saucer

  5. alessandro says:

    if i load a form into a div with ajax call it can’t have the style of jquery mobile
    cause it laoded to the dom after jquery mobile trasformation

    how can i set the jquery mobile style to a content loaded with ajax? i need to include jquerymobile.js also in the content that i need to load?

  6. alessandro says:

    i’ve solved, just call page() method on the conteiner of the new content added to the dom

  7. Boris says:

    Thank you!!!!

Comments are closed.