1

I have made form of customer details form when I click the button, It send Json data to customer. But my code is not inserting data into database. I am new in web technology, please tell me where I am wrong.

my Script:

 <script>   
    $(document).ready(function(){              
            $("#btnBooking").on("click", function(){                   

                var uName = document.getElementById('userName').value;        
                var mailId = document.getElementById('addressemailId').value;           
                var mobNum = document.getElementById('userContactNumber').value;                    
                $.ajax({
                    url:"http://192.168.1.11/customerhomes/customer.php", 
                    type:"GET", 
                    dataType:"json", 
                    data:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum}, 
                    //type: should be same in server code, otherwise code will not run
                    ContentType:"application/json", 
                    success: function(response){ 
                            alert("13");                                                 
                        }, 
                        error: function(err){ 
                        alert(JSON.stringify(err)); 
                    } 
                })              
            }); 
    });
</script>

form in html

<body>
    <div class="page-header text-center">
        <form >
            <div class="col-lg-8">                                  
                <div class="form-group">
                        <label class="col-lg-3 control-label">Name:<font style="color: red;">*</font></label>
                        <div class="col-lg-9">
                            <input type="text" class="form-control" id="userName" name="userName" placeholder="Full Name" value="">
                        </div>
                </div>


                <div class="form-group">
                    <label class="col-lg-3 control-label">Mobile:<font style="color: red;">*</font></label>
                    <div class="col-lg-9">
                        <input type="text" class="form-control" id="userContactNumber" name="userContactNumber" type="number" placeholder="" onkeypress="enableKeys(event);" maxlength="10" placeholder="9966778888">
                    </div>
                </div>

                <div class="form-group">
                        <label class="col-lg-3 control-label">Email:<font style="color: red;">*</font></label>
                        <div class="col-lg-9">                                  
                            <input type="text" class="form-control" name="addressemailId" id="addressemailId" placeholder="[email protected]" value="">
                        </div>
                </div>  
                <div class="form-group marg-bot-45">
                    <label class="col-lg-3 control-label"></label>
                    <div class="col-lg-9">

                        <a href="" class="btn btn-info"  id="btnBooking">Confirm Booking</a>
                    </div>
                </div>
            </div>
        </form>
    </div>
</body>

server code

<?php
header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
mysql_connect("localhost","root","1234");
mysql_select_db("customer_details");
if(isset($_GET['type']))
{
    if($_GET['type']=="booking"){
        $name = $_GET ['Name'];
        $mail = $_GET ['Email'];
        $mobile = $_GET ['Mob_Num'];
        $query1 = "insert into customer(cust_name, cust_mobile, cust_email) values('$name','$mail','$mobile')";
        $result1=mysql_query($query1);
    }
}
else{
    echo "Invalid format";
}
5
  • It seems that you are sending json formatted data to php but on the server side you don't decode it --> check out this answer stackoverflow.com/questions/4343596/parsing-json-file-with-php Commented Jan 17, 2015 at 9:06
  • Also, for learning purposes, have a look at prepared statements here (at as I believe one of the most useful answers around) Commented Jan 17, 2015 at 9:13
  • @ Jan Legner, thanks for reply but this link about for sqlinjection.... Commented Jan 17, 2015 at 9:16
  • any errors while executing code ? Commented Jan 17, 2015 at 9:18
  • You need to decode your json data, when you send them to php. Commented Jan 17, 2015 at 9:38

3 Answers 3

1

Use this

JavaScript Code:

<script>
        $(document).ready(function(){
            $("#btnBooking").on("click", function(e){

                // as you have used hyperlink(a tag), this prevent to redirect to another/same page
                e.preventDefault();

                // get values from textboxs  
                var uName = $('#userName').val();
                var mailId = $('#addressemailId').val();
                var mobNum = $('#userContactNumber').val();

                $.ajax({
                    url:"http://192.168.1.11/customerhomes/customer.php",
                    type:"GET",
                    dataType:"json",
                    data:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum},
                    //type: should be same in server code, otherwise code will not run
                    ContentType:"application/json",
                    success: function(response){
                        alert(JSON.stringify(response));
                    },
                    error: function(err){
                        alert(JSON.stringify(err));
                    }
                })
            });
        });
    </script>

PHP Code

<?php
header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
 mysql_connect("localhost","root","1234");
 mysql_select_db("customer_details");
if(isset($_GET['type']))
{
    $res = [];

    if($_GET['type'] =="booking"){
        $name  = $_GET ['Name'];
        $mail  = $_GET ['Email'];
        $mobile  = $_GET ['Mob_Num'];
        $query1  = "insert into customer(cust_name, cust_mobile, cust_email) values('$name','$mail','$mobile')";
        $result1 = mysql_query($query1);

        if($result1)
        {
            $res["flag"] = true;
            $res["message"] = "Data Inserted Successfully";
        }
        else
        {
            $res["flag"] = false;
            $res["message"] = "Oppes Errors";
        }

    }
}
else{
    $res["flag"] = false;
    $res["message"] = "Invalid format";
}

    echo json_encode($res);
?>

If data is inserted successfully it return true flag with message, otherwise false flag with message

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Now data is inserting into database, Could you tell me why Previously It was not inserting..
Probably its because you are clicking on link Confirm Booking, and its a link so what happen when you click on that it redirect to same page(refresh page), use button instead of link while using ajax or use preventDefault()
confirmed that`s the only problem.
0

I would first of all change the "GET" to a "POST" on both the ajax call and the receiving PHP page on the server.

Secondly, I'd check that the values are actually being passed to the PHP page by using echo to output each of them on the PHP side. That way you'll know at least the values are coming through.

JavaScript:

var uName = $('#userName').val();        
var mailId = $('#addressemailId').val();           
var mobNum = $('userContactNumber').val();                    
$.ajax({
    url:"http://192.168.1.11/service4homes/customer.php", 
    type:"POST", 
    data:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum}, 
    complete: function(response){ 
        var test = $.parseHTML(response);
        alert(test);
    }
 });

PHP Code:

echo $_POST["type"];
echo $_POST["Name"];
//etc...

3 Comments

my code is to make sure the values are actually being passed from one place to the other. The PHP will output values (if available) and then the ajax will alert the result. You could also use Chrome dev tools (Ctrl+Shift+i) and click the "Network" tab to view the request and response of the PHP file when you click submit. Once you've proved the submit works and data is correctly passed, my next step would be to check the db connection and then the insert. Check everthing one step at a time basically!
But I have echoed in my code else{ echo "Invalid format"; }
yes, but my logic is that you need to actually confirm that the Ajax is actually passing the values from the web form to your PHP code.
0

try this it might help you.

in your ajax function:

1st change : ContentType:"application/json" to contentType: "application/json; charset=utf-8"

2nd

in data:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum} change to data:{type1:"booking",Name:uName, Email:mailId, Mob_Num:mobNum}. see you set type as GET in ajax function so i am thinking that "type" is reserved word, so it might not work. and also check your url where you are sending ajax request if it is correct or not bcoz you are using ip address.

in your server code i am seeing typo. there is space between

$_GET ['name'], $_GET ['Email'], $_GET ['Mob_Num'].

there should be no space so change it to this,

$_GET['name']

$_GET['Email']

$_GET['Mob_Num']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.