dev_marshell08
dev_marshell08

Reputation: 1101

How to make a connection to PHP file on a Webserver using PhoneGap(Android app) in real time?

The below given code works fine using a wamp server on localhost.It is calling a php file that connects to the MySql DB and returns data.

However i am trying to build a mobileapp using PhoneGap. The below code is in a HTML file. My questions is how will my html file make a connection with the server using ajax once I upload it to phonegap and generate the .apk file. Since the below code just calls the getbustime.php file without any web server parameters.

i have devloped my app in phonegap using HTML,jQueryMobile,Ajax and now willing to upload help ?

  function getBusTime(){



                         if (window.XMLHttpRequest)
                        {// code for IE7+, Firefox, Chrome, Opera, Safari
                        xmlhttp=new XMLHttpRequest();
                        }
                      else
                        {// code for IE6, IE5
                        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                        }
                      xmlhttp.onreadystatechange=function()
                        {
                        if (xmlhttp.readyState==4 && xmlhttp.status==200)
                          {

                         document.getElementById("resultLogBus").innerHTML=xmlhttp.responseText;

                    // $('#resultLogBus').html(xmlhttp.responseText).selectmenu( "refresh");
                         }
                        }

                      xmlhttp.open("GET","getbustime.php?direction="+direction+"&busnum="+busnum+"&dayofweek="+dayofweek+"&stopname="+stopname+"&starttime="+starttime+"&endtime="+endtime,true);
                      xmlhttp.send();



    }//End of function getBusTime


</script>

Upvotes: 3

Views: 2502

Answers (1)

SoldierOfFortran
SoldierOfFortran

Reputation: 782

Basically, you need to set a full path to the server/php file in your ajax call like so:

xmlhttp.open("GET","http://<YOUR_SERVER_NAME>/getbustime.php?direction="+direction+"&busnum="+busnum+"&dayofweek="+dayofweek+"&stopname="+stopname+"&starttime="+starttime+"&endtime="+endtime,true);


A couple other things you may ALSO need to do depending on your circumstances are:

  1. set this tag in the phonegap config.xml:

    <access origin="*" />

  2. I do all my phonegap development in Chrome and it enforces Cross-Origin security. Once you try to test against your server's real address (instead of localhost) Chrome will block it unless the server is set up for CORS. Easy way to enable this for testing in PHP on your server is:

    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Headers: X-Requested-With, Content-Type');

Upvotes: 2

Related Questions