jquery - Ajax form Submit vizualizing the php file
Get the solution ↓↓↓This is the js
<script>
$(document).ready(function()
{
$("#create-admin").submit(function(e)
{
var forms = document.getElementsByClassName('needs-validation');
if(forms == null)
{
$.ajax({
type: "POST",
url: "crud_admin.php",
dataType: "html",
data: $("#create-admin").serialize()
}).done(function(data){
toastr.success(data, 'Success Alert', {timeOut: 5000});
})
}
/**/
})
})
this is the form
<form id="create-admin" class="needs-validation" autocomplete="off" action="crud_admin.php" method="POST" novalidate> ... </form>
this is the crud_admin.php vars and db stuff .................. the response
if($db_connection->query($sql_add)){
echo "success";
}else {
echo "fail";}
When i click on submit the form all data goes to db, and it redirect me to the page crud_admin.php enter image description here
Answer
Solution:
You can do it this way, how @msg says, try to usepreventDefault()
method to prevent common behavior of the form. Try this:
$(document).on('submit', "#create-admin", function(e)
{
e.preventDefault();
if($(this).hasClass('needs-validation'))
{
//Make validation before the ajax request
$.ajax({
type: "post",
url: "crud_admin.php",
data: $(this).serialize()
}).done(function(data){
toastr.success(data, 'Success Alert', {timeOut: 5000});
})
}
/**/
})
Hope it helps.
Answer
Solution:
Try add a line of code using function preventDefault. It should place before var forms = ......
https://www.w3schools.com/jsref/event_preventdefault.asp
Hope it can help.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: attempt to read property "id" on null
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.