0

I am trying to make -

  • an android WEB application
  • with phonegap
  • layout with JqueryMobile

What Im doing -

  • An html form that takes ID, name, and address as input
  • 'Serialize's this data using ajax
  • makes a json object out of it
  • Should send it to a file called 'connection.php'
  • Where, this data is put into a database (MySql)

Other details -

  • My server is localhost, Im using xampp
  • I have already created a database and table using phpmyadmin

The problem -

  • My html file, where my json object is created, does not connect to the php file which is hosted by my localhost

Here is my COMPLETE html file:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
"http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 

<!-- Change this if you want to allow scaling --> 
   <meta name="viewport" content="width=default-width; user-scalable=no" /> 
   <meta http-equiv="Content-type" content="text/html;charset=utf-8"> 

   <title>Trial app</title>
   <link rel="stylesheet" href="thestylesheet.css" type="text/css">
    <script type="text/javascript" charset="utf-8" src="javascript1.js"></script>
    <script type="text/javascript" charset="utf-8" src="javascript2.js"></script>
    <script type="text/javascript" charset="utf-8" src="cordova-1.8.0.js"></script>

    <script>
    $(document).ready(function () {
        $("#btn").click( function() {
        alert('hello hello');

        $.ajax({
            url: "connection.php",
            type: "POST",
            data: {
                id: $('#id').val(),
                name: $('#name').val(),
                Address: $('#Address').val()
            },
            datatype: "json",
            success: function (status)
            {
                if (status.success == false)
                {
                    alert("Failure!");
                }
                else 
                {
                    alert("Success!");
                }
            }
        });

    });
    });
</script> 
</head> 

<body> 

<div data-role="header">
        <h1>Heading of the app</h1>
    </div><!-- /header -->
<div data-role="content">
    <form id="target" method="post">
        <label for="id">
            <input type="text" id="id" placeholder="ID">
        </label>

        <label for="name">
            <input type="text" id="name" placeholder="Name">
        </label>

        <label for="Address">
            <input type="text" id="Address" placeholder="Address">
        </label>
<div id="btn" data-role="button" data-icon="star" data-theme="e">Add record</div>
        <!--<input type="submit" value="Add record" data-icon="star" data-theme="e">
        -->
    </form>

</div>
</body> 
</html>

And here is my 'connection.php' hosted by my localhost

  <?php header('Content-type: application/json');

$server = "localhost";

$username = "root";

$password = "";

$database = "jqueryex";

$con = mysql_connect($server, $username, $password);
if($con) { echo "Connected to database!"; }
else { echo "Could not connect!"; }
//or die ("Could not connect: " . mysql_error());

mysql_select_db($database, $con);

/*
 CREATE TABLE `sample` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  `Address` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

*/
    $id= json_decode($_POST['id']);

$name = json_decode($_POST['name']);

$Address = json_decode($_POST['Address']);

    $sql = "INSERT INTO sample (id, name, Address) ";
    $sql .= "VALUES ($id, '$name', '$Address')";
    if (!mysql_query($sql, $con)) {
        die('Error: ' . mysql_error());
    } else {
        echo "Comment added";
    }
    mysql_close($con);
?>

My doubts:

  • No entry is made in my table 'sample' when i view it in phpmyadmin
  • So obviously, i see no success messages either
  • I dont get any errors, not from ajax and neither from the php file.

Stuff Im suspecting:

  • Should i be using jsonp instead of json? Im new to this.
  • Is there a problem with my php file?
  • Perhaps I need to include some more javascript files in my html file?

I assume this is a very simple problem so please help me out! I think there is just some conceptual error, as i have only just started with jquery, ajax, and json. Thank you.

A FEW EDITS:

I was getting the following syntax errors:

Connected to database!
Notice: Undefined index: id in C:\xampp\htdocs\connection.php on line 28

Notice: Undefined index: name in C:\xampp\htdocs\connection.php on line 31

Notice: Undefined index: Address in C:\xampp\htdocs\connection.php on line 34
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' '', '')' at line 1

So i changed my code to

if (isset($_POST['id']))
$id= json_decode($_POST['id']);

if (isset($_POST['name']))
$name = json_decode($_POST['name']);

if (isset($_POST['Address']))
$Address = json_decode($_POST['Address']);

Still getting the same errors

Please help!

  • Try a complete URL instead of connection.php, seeing your JS is not delivered from a server. – Devraj Jul 10 '12 at 08:54
  • What sould the url be? I mean the file 'connection.php' is hosted by my localhost. Its here on my pc in a folder called 'htdocs' (Im using xampp). So what should the url be? – Madhulika Mukherjee Jul 10 '12 at 08:56
  • Assuming you're running the PhoneGap on the same computer, try http://localhost/connection.php basically a FQDN – Devraj Jul 10 '12 at 08:58
  • Connected to database!
    Notice: Undefined index: id in C:\xampp\htdocs\connection.php on line 27

    Notice: Undefined index: name in C:\xampp\htdocs\connection.php on line 29

    Notice: Undefined index: Address in C:\xampp\htdocs\connection.php on line 31
    Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' '', '')' at line 1
    – Madhulika Mukherjee Jul 10 '12 at 09:07
  • Follow my answer below and please remove the syntax errors before proceeding further. – Usman Chaudhry Jul 10 '12 at 09:15
  • I have edited my question towards the end. Please see – Madhulika Mukherjee Jul 10 '12 at 09:26

3 Answers3

1

As you're using android so direct connection.php won't work, here is the general method to get this done:

http://www.mobitechie.com/android-2/how-to-access-localhost-on-android-over-wifi/

After you setup things given in above link, the network address you'll get will be something like 10.0.0.2 then change your server to http://10.0.0.2/connection.php where connection.php is placed in htdocs directory.

Above step is necessary because android treats localhost as its own device localhost and doesn't pick the system's localhost directly.

Comment under this answer further to ask if you have more issues.

Usman Chaudhry
  • 430
  • 4
  • 11
1

You can use JSONP for ajax request in Phonegap. But for that, you have to use Cross domain request to the server page using JSONP. Here you have to use callback method.

Just go through my post $.ajax() on phonegap.

And one more thing, dont make request from android to the localhost. Just put your file in webserver and try to make request.

Community
  • 1
  • 1
Akilan
  • 1,707
  • 1
  • 16
  • 30
1

Please change this script from :

$sql = "INSERT INTO sample (id, name, Address) ";
$sql .= "VALUES ($id, '$name', '$Address')";

To:

$sql = "INSERT INTO sample (id, name, Address) ";
$sql .= "VALUES ('$id', '$name', '$Address')";

Add the character ' around $id

Hugo Dozois
  • 8,147
  • 12
  • 54
  • 58
Fahrul
  • 11
  • 1