I'm working with a mysql database and a webpage that i'm trying to make comunicate with it.
Here's my situation:
i have the listmat.php
file that echoes all the records in the table Material
and it works.
Now i manage to show the output of the listmat.php
file inside a specific div
witouth refreshing the hole page with the following code:
<script>
$(document).ready(function(){
$("#matbutton").click(function(){
$("#matins").load('listmat.php');
});
});
</script>
Where matbutton
is the id of the submit button in the form and matins
is the id of the div
where i show the output of listmat.php
Here's my form:
<form id="formmatins" method="post" action="listmat.php">
<p>Name:<input type="text" Name="Mat" id="Material"></p>
<center><input type="submit" value="Insert/Remove" id="matbutton"></center>`
</form>
What i'd like to do is to use the matbutton
to also insert the value of the textbox in the table that listmat.php
echoes all his records. So that everytime i click a record is inserted and in the div is shown the new table
The problem is that if i insert the button in the form with the method post , by clicking it redirects to the output changing page but if i put it out the echoes work but i cannot pass obviously the value of the textbox to the listmat.php
file to be the argument of the insert because the button is not interested by the method post.
I looked around and looks like the solution is using some articulated structure in jquery/ajax but i really don't know how to fix. Any help would be really appreciated
UPDATE
<script>
$(function () {
$('#formmatins').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'listmat.php',
data: $('#formmatins').serialize(),
success: function () {
$("#matins").load('listmat.php');
alert('form was submitted');
}
});
});
});
</script>
And again it switch page
UPDATE
<?php
$user = "**";
$pass = "**";
$db = "**";
$host = "localhost";
$con = mysqli_connect($host,$user,$pass,$db);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$m = $_POST['Mat']; //the text box in the form
$ins = $con->query("INSERT INTO mattemp (Material) VALUES ('$m')");
$query = $con->query("SELECT Material FROM mattemp");
while ($row = $query->fetch_assoc()) {
echo $row['Material']."<br>";
}
?>
It print the table updated everytime but still in a new page...what am i doing wrong?
SOLVED BY MYSELF
Thanks to all have tried to help me. The solution that gave me -1 on the post was not correct and here the solution of my code , in case someone would encounter the same problem
`<script>
$(function () {
$('#matbutton').on('click', function(event){
event.preventDefault();
$.ajax({
type: 'post',
url: 'listmat.php',
data: $('#formmatins').serialize(),
success: function (data) {
$("#matins").load('listmat.php');}
});
});
});
</script>`