Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am making a web app (android) with phonegap and jquery mobile.

I am trying to send three fields from an html form as json, to a php page which will decode the json string/object (im new to json, ajax, jquery) and add the three fields as a mysql query to a database on my localhost.

My html page looks like this:

<script type="text/javascript">
$(document).ready(function(){  
$('#btn').bind('click', addvalues);
});
  function addvalues(){
  $.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 a failure message
    } 
    else { 
          //alert a success message
        }  
   }  
 });  
} 
</script> 
</head> 
<body> 

<div data-role="header">
<h1>My header text</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>
<input type="submit" id "btn" value="Add record" data-icon="star" data-theme="e">
</form>
</div>
</body> 

The Question is:

How exactly do i extract the three fields (ID, name, Address) from the string that i have sent to my php file (connection.php)? connection.php is hosted by my local server.

I am familiar with making connections to database, as also with adding queries to mysql. I only need help with extracting the three fields, as i am new to ajax and jquery and json.

As of now, this is ALL i have done in connection.php:

<?php
$server = "localhost";
$username = "root";
$password = "";
$database = "jqueryex";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);

//I do not know how to use the json_decode function here


//And this is how, i suppose, we will add the values to my table 'sample'
$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);
?>

Please add the relevant code in this file and help me out. I will be highly obliged. :)

share|improve this question

4 Answers

use:

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

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

in place of :

$sql .= "VALUES ($id, '$name', '$Address')";
share|improve this answer
Thank you. But dont i have to use the json_decode(data..) function to tokenize my json string (thats been sent from the html form) into id, name, Address ? Thats what it said wherever i read. I think what you are suggesting is how to insert form elements ordinarily into database. My question is, how to do it the json way? Thanks for the help though – Madhulika Mukherjee Jul 6 '12 at 13:43
Hi. Im getting syntax errors! It says undefined variables id, name and Address! PLease help! – Madhulika Mukherjee Jul 10 '12 at 11:43
on which line.. – Shehzad Bilal Jul 10 '12 at 12:00
This is what im getting. 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 – Madhulika Mukherjee Jul 10 '12 at 12:07
Have you checked the post variables,, are they coming in your PHP file via ajax,, – Shehzad Bilal Jul 10 '12 at 12:17
show 4 more comments

what you want to do this this

           $(document).ready(function () {
        $('#btn').on('click', function () {
            $.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 a failure message
                    } else {
                        //alert a success message
                    }
                }
            });
        });
    });

then in your php do this

   //set varables from json data
    $id = json_decode($_POST['id']);
    $name = json_decode($_POST['name']);
    $Address = json_decode($_POST['Address']);

    //And this is how, i suppose, we will add the values to my table 'sample'
    $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);

be sure you sanitize those inputs before you insert them though.

share|improve this answer
1  
Great! Thanks a lot for such a detailed and thorough answer! – Madhulika Mukherjee Jul 7 '12 at 7:15
I replaced the code but there is yet another problem: My clicking of button makes no difference to the addvalues function :( Its not getting called at all! – Madhulika Mukherjee Jul 7 '12 at 7:35
Ah sorry it should be addvalues() not addvalues – Clark T. Jul 7 '12 at 16:25
Made the change. And nope, still the function is not called. Do you think there might be something wrong in the way i have declared my button in the html file? – Madhulika Mukherjee Jul 7 '12 at 17:10
Sorry for the delay a better solution for this is to use it as an unnamed function i've edited my answer to reflect the new method – Clark T. Jul 7 '12 at 21:35

use $id_json_encoded = json_encode($_POST['id']); to encode the posts of the form then use jquery script like this

<script type="text/javascript">

$(document).ready(function() {

        $("#audit").click(function(){
            $.post("/audit_report/"+$('#branch').val()+"/"+$('#ttype').val()+"/"+$('#from').val()+"/"+$('#to').val(),

                    {
                        targetDiv:"divswitcher"
                    }
                ,
                    function(data){

                     $("#imagediv").html('<img src="/public/images/spinner_white.gif"> loading...');  
                //alert(data);
                $("#bodydata").html(data);
                 $("#imagediv").html('');  
                    //  $("#divswitcher").html(data);
        });                 
        });     
        });     

share|improve this answer
Im thankful for your help but im really new to this so can you please write the complete function and post here? Or atleast, please explain from which line exactly will this code connect to my php file? I'll be really grateful. thanks – Madhulika Mukherjee Jul 10 '12 at 11:42
this is the complete code that encodes form data and send it to the server using ajax


<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <script type="text/javascript" charset="utf-8" src="jquery.js"></script>
<script type="text/javascript" language="javascript" src="jquery-ui-1.8.16.custom.min.js"></script> 





    <script type="text/javascript">
$(document).ready(function()
  { 


            $("#btn").click(function(){

            var encoded = json_encode("/audit_report/"+$('#id').val()+"/"+$('#name').val()+"/"+$('#Address').val());
                $.post(encoded,

                        {
                            targetDiv:"divswitcher"
                        }
                    ,
                        function(data){

                         $("#imagediv").html('<img src="spinner_white.gif"> loading...');  
                    //alert(data);
                    $("#bodydata").html(data);
                     $("#imagediv").html('');  
                        //  $("#divswitcher").html(data);
            });                 
            });     
            });     
</script>


</head>
<body>

    <div data-role="header">
<h1>My header text</h1>
</div><!-- /header -->
<div data-role="content">
<form id="target" method="post">
<label for="id">
<input type="text" id="id" name="id" >
</label>
<label for="name">
<input type="text" id="name" name="name" >
</label>
<label for="Address">
<input type="text" id="Address" name="Address" >
</label>

<input type="button" id="btn" name="btn" value="Add record" />
</form>
</div>

</body>
</html>


<div id="bodydata" class="class">

</div>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.