Enesh Kumar
Enesh Kumar

Reputation: 43

only Insertion data in database through AJAX in php.

[enter image description here][1]     **add.php**
 I am not sure that my data is inserted through ajax or not, can anyone solve my issue.

This is my add.php file i am inserting the data in database, firstly i have included the database connection file in this file, using POST method to submit data using mysqli_real_escape_string to removing special character from string. checking empty fields, link to the previous page, display success message.

        <html>
<head>
    <title>Add Data</title>


</head>

<body>
<?php
//including the database connection file
include_once("config.php");

    $name = $_POST['name'];
    $age =  $_POST['age'];
    $email = $_POST['email'];

    // checking empty fields
    if(empty($name) || empty($age) || empty($email)) {

        if(empty($name)) {
            echo "<font color='red'>Name field is empty.</font><br/>";
        }

        if(empty($age)) {
            echo "<font color='red'>Age field is empty.</font><br/>";
        }

        if(empty($email)) {
            echo "<font color='red'>Email field is empty.</font><br/>";
        }

        //link to the previous page
        echo "<br/><a href='javascript:self.history.back();'>Go Back</a>";
    } else { 
        // if all the fields are filled (not empty) 

        //insert data to database   
        $result = mysqli_query($mysqli, "INSERT INTO users(name,age,email) VALUES('$name','$age','$email')");



        //display success message
        //echo "<font color='green'>Data added successfully.";
        //echo "<br/><a href='index.php'>View Result</a>";

}
?>
</body>
</html>




        **add.html**
        In this file i have included all my js file creating a small table for name, age, email. my method is post. i am unable to do this task first time i am using ajax without ajax i insert data many times.
    I am not sure that my data is inserted through ajax or not, can anyone solve my issue.


        <html>
<head>
    <title>Add Data</title>
    <script src="style/jquery-3.2.1.js"></script>
    <script src="style/insert.js"></script>

</head>

<body>
    <a href="index.php">Home</a>



    <br/><br/>
    <p id="alert"><span id="show"></span></p>

        <table align="center" width="25%" border="0">
            <tr> 
                <td>Name</td>
                <td><input type="text" name="name" id="name"></td>
            </tr>
            <tr> 
                <td>Age</td>
                <td><input type="text" name="age" id="age"></td>
            </tr>
            <tr> 
                <td>Email</td>
                <td><input type="text" name="email" id="email"></td>
            </tr>
            <tr> 
                <td></td>
                <td><input type="submit" name="Submit" id="submit" value="Add"></td>
            </tr>


    </table>
</body>
</html>






        **insert.js**
        In this file save input value in variable, my type is POST url is add.php, success function is result, my data is inserted but i am not sure that is this through AJAX or not.
    I am not sure that my data is inserted in database through ajax or not, can anyone solve my issue. 



      $(document).ready(function(e) {
    $('#submit').click(function()
    {

        var name = $('#name').val(); //save input value in variable
        var age = $('#age').val();
        var email = $('#email').val();


        $.ajax({
            data :{name:name,age:age,email:email}, 
            url  :"add.php", //php page URL where we post this data to save in database
            type :'POST',
            success: function(data){
                alert("Form submitted");
                 $('#name').val("");
                 $('#age').val("");
                 $('#email').val("");

            }
        })
    });
});

Upvotes: 0

Views: 883

Answers (2)

ADyson
ADyson

Reputation: 61977

This should work:

$(document).ready(function() {
    $('#submit').click(function(event){
        event.preventDefault();

        $.ajax({
            type:'POST',
            data: $(this).serialize(),
            url:"add.php", //php page URL where we post this data to save in database
            success: function(result){
                $('#alert').show();
                $('#show').html(result);
            }
        })
    });
});
  • That extra call to preventDefault will stop a normal postback from occurring (that would be the normal behaviour of your submit button, regardless of the JS event handler).
  • Also you are trying to retrieve your fields using IDs that don't exist in your markup - you'd need id="name" (for instance) on your textboxes for that to work. But an easier way to get all your form data is simply to use jQuery's serialize() method, as I've demonstrated above.
  • Lastly you had a syntax error (should be $.ajax not $ajax).

Meanwhile, an easy way to tell if it was an ajax request or not is whether your alert was shown or not. If it wasn't, did the page do a full postback? Or is there some kind of ajax error (in your browser's developer tools - console and network tabs)? Perhaps take a tutorial online about debugging JavaScript and ajax, it might help you.

P.S. using mysqli_real_escape_string is not completely safe to prevent SQL injection attacks etc. The best solution is to use prepared statements and parameterised queries. http://bobby-tables.com explains the risks and also shows you how to write queries safely using PHP and mysqli.

Upvotes: 1

Parth Sureliya
Parth Sureliya

Reputation: 256

Your Data is inserted using simple PHP Not through ajax. Because you get input value in ajax with ("#name") means Input id, but you do not define id attribute in an input field.

Upvotes: 1

Related Questions