Alright, so I have a basic form on my page:
<form action='' id='formId' method='POST'>
<table>
<tr>
<td>
<input type='text' name='Chat' autocomplete='off'>
</td>
<td>
<input type='submit' name='Go'>
</td>
</tr>
</table>
</form>
and the javascript is:
<script type='text/javascript'>
$( "#formId" ).submit(function( event ) {
event.preventDefault();
<?php
$Chat = mysql_real_escape_string(strip_tags($_POST['Chat']));
$Go = mysql_real_escape_string($_POST['Go']);
if ($Go) {
if ($Chat) {
mysql_query("INSERT INTO `Chat` (`Chat`)
VALUES('$Chat')");
}
}
?>
});
</script>
I just need it to stop from refreshing when someone submits. I've read a few different posts on here with the same problem, but none seemed to work for me.
$('#formId').submit(function () {
/do your stuff
return false;
});
Returning false will prevent page reloading.
You need to separate the php code to your script. PHP is executed server side, js/jquery is executed client side. Try this code if it will help you.
<?php
if(isset($_POST['Go'])){
$Chat = mysql_real_escape_string(strip_tags($_POST['Chat']));
$Go = mysql_real_escape_string($_POST['Go']);
if ($Go) {
if ($Chat) {
mysql_query("INSERT INTO `Chat` (`Chat`)
VALUES('$Chat')");
}
}
}
?>
<form action='' id='formId' method='POST'>
<table>
<tr>
<td>
<input type='text' name='Chat' autocomplete='off'>
</td>
<td>
<input type='submit' name='Go'>
</td>
</tr>
</table>
</form>
<script type='text/javascript'>
$( "#formId" ).submit(function( event ) {
event.preventDefault();
});
</script>
REVISED: 06/15/2015 10:16AM GMT+8 You need use AJAX to send data. First, Add an id to the text field then create a php file for getting the data from the URL and insert the chat to DB. Try this code:
<form action='' id='formId' method='POST'>
<table>
<tr>
<td>
<input type='text' id='chat' name='Chat' autocomplete='off'>
</td>
<td>
<input type='submit' name='Go'>
</td>
</tr>
</table>
</form>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type='text/javascript'>
$( "#formId" ).submit(function( event ) {
event.preventDefault();
$.ajax({
type: "POST",
url: "insert_chat.php?",
data: "Chat="+$('input#chat').val(),
dataType: "json",
success: function(data){
}
});
});
</script>
insert_chat.php
<?php
$Chat = mysql_real_escape_string(strip_tags($_GET['Chat']));
$Go = mysql_real_escape_string($_GET['Go']);
if ($Go) {
if ($Chat) {
mysql_query("INSERT INTO `Chat` (`Chat`)
VALUES('$Chat')");
}
}
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.