Sending a post request using jquery

Trick to running a post request using jquery is to store the variables in an object then pass the object into the $.ajax or $.post jquery api. Here is an example.

var data = {
    data1: "My Name",
    data2: "Joe"

Suppose you have setup a php script(script.php) on your hosting account on the server that accepts a $_post['chapter']; variable from an input field either from a phoneGap or Cordova mobile App. yourbook/script.php script could query a mysql database on server and outputs chapter headings in plain html.

    <li>Heading one</li>
    <li>Heading two</li>
    <li>Heading three</li>

To make a post request to this php script to retrieve the chapter headings above to display in jquerymobile listview on your PhoneGap app you would do this: In your App you are using jquery, jquerymobile js files embeded in between head tags.

<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/"></script>

Note: stylesheets come before need jquerymobile css file then include jquery and right below include jquery mobile. Then you have the following inside the body tag of index.html in your phonegap App:

<!-- data-role page tells jquerymobile it's a page and the page is called welcome. -->
<div id="welcome" data-role="page">
<div data-role="header">
<h1>My Book</h1>
<div data-role="content">
<ul id="showchapters" data-inset="true" data-role="listview">
<!-- this is where post request will load chapter list in list view -->
In an external script file

<script type="text/javasscript" src="myscript.js"></script>
or between script tags inside head tags in your Apps index.html document.

<script type="text/javascript"></script>
Place the following code. The comments in this code explain what is going on.

function grabChList(chlist){
//create an object to store chapter number request
var chlistplease ={
chapter: chlist
//in apache cordova 'yourbook/script.php' will be full url to the script file on your server
//chlistplease is an object sent as a post request to your script. After it's sent then DoSomethingWithResult function is run. DoSomethingWithResult function is being used as a callback.
$.post('', chlistplease, DoSomethingWithResult);

function DoSomethingWithResult(chlistplease) {


//this refreshes list view in JQueryMobile after loading data.
//if you don't refresh  listview nothing will display


//This is what starts the whole process. This is telling your App, once document is loaded(document ready) then grab the chapters for 1. 1 here could be a book or it could be grabbing subchapters from chapter one. It's up to you.
grabChList(1);//grab chapter list for the first chapter

Thanks for reading. If you have a comment or suggestion please leave them below.
Z Data Tech Last modified: November 2, 2013

Recent Posts