Sandeep Kumar
Sandeep Kumar

Reputation: 158

Data is not inserting into database by jQuery and ajax method

I have to insert data through jQuery and ajax method. But data is not inserting in database. Pleas help me is this method is wrong?

Here is my code,

form.html

<!DOCTYPE html> <html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <!--        <script src="jquery-3.1.0.js" type="text/javascript"></script>-->
        <script type="text/javascript">
            function submitData()
            {
                var name = document.getElementById('name');
                var age = document.getElementById('age');
                var contact = document.getElementById('contact')

                $.ajax({
                    type: 'POST',
                    url: 'data_ins.php',
                    data:{
                     uname:name,
                     uage:age,
                     ucontact:contact
                    },
                    success: function(response){
                        $('#success_para').html("Data inserted");
                    }
                });

                return false;
            }
        </script>
    </head>
    <body>
        <form method="POST" onsubmit="return submitData();">

            name : <input type="text" name="name" id="name"> <br>
            age : <input type="text" name="age" id="age"> <br>
            contact : <input type="text" name="contact" id="contact"> <br>
            <input type="submit" name="submit" >

        </form>

        <p id="success_para"></p>
    </body> </html>

and, data_ins.php

<?php
       $conn = mysqli_connect("localhost","root","","test_db");
       $name = $_POST['uname'];    $age = $_POST['uage'];    $contact = $_POST['ucontact'];
       if(!$conn)    {
       echo"<script>alert('Database Connection Failed or invalid connection');</script>";    }
       else    {
       $sql = "insert into records (name, age, contact) values ('$name', '$age', '$contact')";    mysqli_query($conn, $sql);
    mysqli_error($conn);    }
    ?>

Please let me know what's wrong in my code. Thanks, in advance.

Upvotes: 0

Views: 810

Answers (1)

aliczab
aliczab

Reputation: 116

var name = document.getElementById('name').value;
var age = document.getElementById('age').value;

Your "submit" button causes page reloading, so you'll not be able to see the result of a query in your onSuccess.

<input type="button" name="submit" onclick="submitData();" >

Have you checked your response? You can also view it in browser's inspector.

                success: function(response){
                    $('#success_para').html(response);
                }

Upvotes: 1

Related Questions