Search code examples
phpajaxajaxform

Problems in submitting form data using ajax


i am new in ajax. i am aware to html,php. i want to do the CRUD operation in ajax. i have created a two file

  1. index.php
  2. insert.php as below.

when i click on submit button it submit data and inserted in database. But it resfresh the page. please suggest me that where i made mistake.

my code as below:

index.php

<!DOCTYPE html>
<html>
<head>
    <title>Ajax test</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
    <script type="text/javascript">
    var frm = $('#contactForm1');
    frm.submit(function (ev) {
        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success: function (data) {
                alert('ok');
            }
        });

        ev.preventDefault();
    });
</script>


</head>
<body>
<form id="contactForm1" action="insert.php" method="post">
 <label>Name</label><input type="text" name="user_name"><br>
  <label>Age</label><input type="number" name="user_age"><br>
   <label>Course</label><input type="text" name="user_course">
   <br>
   <input type="submit" name="sumit" value="submit">
</form>

</body>
</html>

insert.php

<?php


$conn = mysqli_connect("localhost", "root", "" ,"aj");

$name = $_POST['user_name'];
$age = $_POST['user_age'];
$course = $_POST['user_course'];




$insertdata=" INSERT INTO test3 (name,age,course) VALUES( '$name','$age','$course' ) ";
mysqli_query($conn,$insertdata);


?>

Solution

  • Close the script tag

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    

    Use when document is ready

    $( document ).ready(function() {
        var frm = $('#contactForm1');
        frm.submit(function (ev) {
            $.ajax({
                type: frm.attr('method'),
                url: frm.attr('action'),
                data: frm.serialize(),
                success: function (data) {
                    frm[0].reset();
                    alert('ok');
                }
            });
    
            ev.preventDefault();
        });
    });
    

    The ready event occurs when the DOM (document object model) has been loaded. Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions. Like in the example above. The ready() method specifies what happens when a ready event occurs.