Reputation: 5322
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
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);
?>
Upvotes: 1
Views: 486
Reputation: 2625
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.
Upvotes: 1
Reputation: 2291
There is no mistake. Technically, its correct. It's just not fitting in your use-case.
It's default behaviour that page refreshes when user submits form.
You have two options:
preventDefault
method. Then, use return false
.Upvotes: 0
Reputation: 1548
The JavaScript code, binding the event handler, is executed too early. The DOM is not fully loaded yet so the form can't be found. jQuery doesn't warn about this.
Either wrap your code in jQuery's on doc loaded method $(function(){ /* code here */ } )
.
Or/and move your JavaScript to the bottom of your HTML. This is a preferred method. See Benefits of loading JS at the bottom as opposed to the top of the document for more details
Upvotes: 0