I’m trying to write a php page which will do the following,
- contains an input form,
- submit the data to the same php page using AJAX
- does some mysql insert stuff (not included in the following code)
- echo the mysql results in another div item of the same php
As it is right now I have several problems:
- When the form is submitted, the results are not placed in the “submission_result” div area, and instead refreshes the page. I was hoping the form is still visible after submission.
- if one of the required fields is not filled, the default error message pops up and the box goes red but the form is still submitted, I was hoping the submission would be blocked. It loads the page again and place in in the “submission_result” div area (which is kind of what I want but only when the form is correctly filled).
- In order to stop the whole page refreshes, I tried using event.preventDefault function, which doesn’t solve all the issues … 🙁
I suppose I can avoid using the button tag but it has the nice “required fields” check, and arrange the data in $_POST automatically, which would save me coding those parts.
Here is my code
<head>
<script src="jquery-3.2.1.js"></script>
<script src="jquery-ui.js"></script>
</head>
<?php
echo "<div id='input_form'>";
if ( empty($_POST) )
{
echo "<h4>Submitting a new article:</h4>";
echo "<form action='test_sub.php' id='submission_form' method='post' enctype='multipart/form-data'>";
echo "<p> Title: </br><input type='text' id='title' name='title' value='test' required> </p>";
echo "<p> url: </br><input type='url' id='url' name='url' > </p>";
echo "</ul>";
echo "<p> content: </br><textarea rows='5' id='content' name='article_content' required>hello world</textarea></br>";
echo "<button class='sub_button' id='btn_sub_button' >Submit</button>";
}
else
{
echo "Input data";
echo count($_POST);
var_dump($_POST);
/*
* mysql insert ... etc
* catch exception ... etc
*/
}
echo "</div>";
echo "</br>";
echo "</br>";
echo "<div id='submission_result'>";
echo "Submission result 1</br>";
echo "Submission result 2</br>";
echo "Submission result 3</br>";
echo "</div>";
?>
<script>
$(document).ready(function()
{
$("#btn_sub_button").click(function(){
//event.preventDefault();
$('#submission_result').load("test_sub.php");
});
});
</script>
Many thanks.
2
Answers
You should try
According to above conversation, I reached to this –
So please replace you script with given below script.