I have question regarding inserting and updating a MySQL database from a form which is loaded in a div via ajax. I have taken various examples from different websites to check if it was an error on my part but they all work when the page is loaded independently and insert or amended to the database. When the form is loaded into the div, the inputs are completed and submitted it then redirects to the home page as defined in the script file but no information is inserted into the database:
(ajax_url.length < 1) {
ajax_url = 'app/pages/home.php';
}
As I said the form works and inserts if I load the form page directly. For that reason I have also tried the following while giving the form an id of "dataforms" and the submit button an id of "sub":
$("#sub").click( function() {
$.post( $("#dataforms").attr("action"),
$("#dataforms :input").serializeArray(),
function(info){ $("#result").html(info);
});
clearInput();
});
$("#dataforms").submit( function() {
return false;
});
function clearInput() {
$("#dataforms :input").each( function() {
$(this).val('');
});
}
Is there something basic I am completely missing?
This is an example I was trying to get to work:
<?php
include_once('/config.php');
$task_name = $_POST['task_name'];
if(mysql_query("INSERT INTO task (task_name) VALUES('$task_name')"))
echo "Successfully Inserted";
else
echo "Insertion Failed";
?>
<span id="result"></span>
<form id="dataforms" action="" method="post">
<label id="first"> Task Name</label><br/>
<input type="text" name="task_name"><br/>
<button id="sub">Save</button>
</form>
I have also attempted to define the php in a separate file and call it on action and I end up with what looks like the post values not being carried across as I get an error showing $task_name is not defined.
The js script file is referenced in the footer and have no issues with datatables displaying and selecting data from the database so I guess it has something to do with how the form is being submitted and reloading. Do I need to treat form submissions differently when ajax is involved? I have used various insert and update scripts to test and all behave the same way.
First Page — can be .html or .php, doesn't matter:
<span id="result"></span>
<form id="dataforms" action="insert-task.php" method="post">
<label id="first"> Task Name</label><br/>
<input type="text" name="task_name"><br/>
<button id="sub">Save</button>
</form>
<script src="https://code.jquery.com/jquery-3.2.0.min.js"
integrity="sha256-JAW99MJVpJBGcbzEuXk4Az05s/XyDdBomFqNlM3ic+I="
crossorigin="anonymous"></script>
<script>
$("#sub").click( function() {
$.post(
$("#dataforms").attr("action"),
$("#dataforms :input").serializeArray(),
function(info){
$("#result").html(info);
});
clearInput();
});
$("#dataforms").submit( function() {
return false;
});
function clearInput() {
$("#dataforms :input").each( function() {
$(this).val('');
});
}
</script>
Second page — insert-task.php:
<?php
//include_once('/config.php');
$task_name = $_POST['task_name'];
//if(mysql_query("INSERT INTO task (task_name) VALUES('$task_name')"))
// echo $task_name; die;
if(true)
echo "Successfully Inserted";
else
echo "Insertion Failed";
?>
The two pages do work in tandem. Though there are a couple of things to note, please:
The database operations aren't yet a part of the executable code.
However, if // echo $task_name; die; was uncommented, then the <span> in the first page would be populated with whatever value was keyed in the input field, which would establish that the form data is relayed properly to the backend.
EDIT:
To deal with the required fields, following change is required in the first page:
Get rid of the click function for $("#sub")
Prevent the default submit action when dataforms is submitted
So, in effect, the updated code would look like follows:
<span id="result"></span>
<form id="dataforms" action="insert-task.php" method="post">
<label id="first"> Task Name</label><br/>
<input type="text" name="task_name" required><br/>
<button id="sub">Save</button>
</form>
<script src="https://code.jquery.com/jquery-3.2.0.min.js"
integrity="sha256-JAW99MJVpJBGcbzEuXk4Az05s/XyDdBomFqNlM3ic+I="
crossorigin="anonymous"></script>
<script>
$("#dataforms").submit( function(e) {
e.preventDefault();
$.post(
$("#dataforms").attr("action"),
$("#dataforms :input").serializeArray(),
function(info){
$("#result").html(info);
}
);
clearInput();
return false;
});
function clearInput() {
$("#dataforms :input").each( function() {
$(this).val('');
});
}
</script>
This would still show up Please fill out this field message if no data was entered in the input field and, at the same time, prevent the unexpected pop-up as a consequence of clearing the field after a successful submit.
Related
<?php
'<form method="post" action="postnotice.php");>
<p> <label for="idCode">ID Code (required): </label>
<input type="text" name="idCode" id="idCode"></p>
<p> <input type="submit" value="Post Notice"></p>
</form>'
?>
Alright, so that's part of my php form - very simple. For my second form (postnotice.php):
<?php
//Some other code containing the password..etc for the connection to the database.
$conn = #mysqli_connect($sql_host,$sql_user,$sql_pass,$sql_db);
if (!$conn) {
echo "<font color='red'>Database connection failure</font><br>";
}else{
//Code to verify my form data/add it to the database.
}
?>
I was wondering if you guys know of a simple way - I'm still quite new to php - that I could use to perhaps hide the form and replace it with a simple text "Attempting to connect to database" until the form hears back from the database and proceeds to the next page where I have other code to show the result of the query and verification of "idCode" validity. Or even database connection failure. I feel it wrong to leave a user sitting there unsure if his/her button click was successful while it tries to connect to the database, or waits for time out.
Thanks for any ideas in advance,
Luke.
Edit: To clarify what I'm after here was a php solution - without the use of ajax or javascript (I've seen methods using these already online, so I'm trying to look for additional routes)
what you need to do is give form a div and then simply submit the form through ajax and then hide the div and show the message after you get the data from server.
<div id = "form_div">
'<form method="post" id = "form" action="postnotice.php";>
<p> <label for="idCode">ID Code (required): </label>
<input type="text" name="idCode" id="idCode"></p>
<p> <input type="submit" value="Post Notice"></p>
</form>'
?>
</div>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'postnotice.php',
data: $('form').serialize(),
success: function (data) {
if(data == 'success'){
echo "success message";
//hide the div
$('#form_div').hide(); //or $('#form').hide();
}
}
});
e.preventDefault();
});
});
</script>
postnotice.php
$idCode = $_POST['idCode'];
// then do whatever you want to do, for example if you want to insert it into db
if(saveSuccessfulIntoDb){
echo 'success';
}
try using AJAX. this will allow you to wait for a response from the server and you can choose what you want to do based on the reponse you got.
http://www.w3schools.com/ajax/default.ASP
AJAX with jQuery:
https://api.jquery.com/jQuery.ajax/
I'm trying to get my announce box that has a X button on the top right, to be clicked and it remove the message, and update a mysql query field without refreshing the page
HTML
<form id="myForm" action="delanno.php" method="post">
<div class='announce-box'>
<div class='announce-message'>$show_message</div>
<div class='announce-delete'>
<a class='deleter'>
<button type='submit' id='sub' name='$show_id' style='height:35px; width:40px'>
<img src='../css/images/delete_25.png' width='25' height='25'>
</button>
</a>
</div>
</div>
</form>
php (delanno.php)
<?php
include("conn.php");
foreach($_POST as $name => $content) { // Most people refer to $key => $value
$something = "$name"; //ignore this, i did this for testing purposes
$query = mysql_query("UPDATE announce SET active='disabled' WHERE id='$something' ") or die(mysql_error());
}
?>
ajax // This is supposed to update the php field without refreshing or sending to another page
<script type="text/javascript">
$("#sub").click( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info){ $("#result").html(info);
});
});
$("#myForm").submit( function() {
return false;
});
</script>
more ajax // this is supposed to remove the announce div when the delete button is clicked.
<script>
$('.deleter').on('click', function(){
$(this).closest('.announce-box').remove();
})
</script>
if i remove
return false
it sends it to the php page and it obviously works. i'm not sure what to do from here
EDIT: The script doesn't work unless it's being sent to the php page
Javascript selecting DOM elements should be inside a ready function when the DOM is actually ready, e.g.
$(document).ready(function() {
// $('#some-id') .. etc
});
.
I just searched SO for a duplicate, I think it's out there but I didn't find it, so just posting as an answer and if someone else does, just flag it.
This site has been really helpful while writing this program. Unfortunately, I hit a snag at some point, and have boiled the problem down quite a bit since. At this point, I am looking at three files, a .html that contains a form, a .js that contains my event handlers, and a .php that receives my post variables and contains new content for the form.
I am getting the post data from the initial text input just fine. The new form content is set as I would expect. However, after this form content is set to a new input of type button with a class of button, the post method in my button class handler is not setting post data on login.php as I expect it to.
Here is my code:
Contents of interface.html page:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<form id="interface" action="login.php" method="post">
<input type="text" value="enter username here" name="user"/>
<button id="submit">submit</button>
</form>
<script src='events.js'></script>
</body>
</html>
Contents of events.js file:
$("#submit").click(function(){
$.post(
$("#interface").attr("action"),
$(":input").serialize(),
function(info){$("#interface").html(info);}
);
});
$(".button").click(function(){
var $this=$(this);
$.post(
$("#interface").attr("action"),
{data:$this.val()},
function(info){$("#interface").html(info);}
);
});
$("#interface").submit(function(){
return false;
});
Contents of login.php file:
<?php
if(isset($_POST['user'])){
echo '<input type="button" class="button" value="set data"/>';
}else if(isset($_POST['data'])){
echo 'data is set';
}
?>
You need to wait until the button exists to bind an event to it. Additionally, i'd switch from click to submit and drop the click event binding on .button completely.
//$("#submit").click(function () {
$("#interface").submit(function (e) {
e.preventDefault();
var $form = $(this), data = $form.serialize();
if ($form.find(".button").length && $form.find(".button").val() ) {
data = {data: $form.find(".button").val()};
}
$.post($form.attr("action"), data, function (info) {
$form.html(info);
});
});
//$("#interface").submit(function () {
// return false;
//});
Since the form is not being replaced, and the event is on the form, you no longer need to re-bind anything.
I have three things going on:
I am sending information with this form.
<form method="post" id="myForm" action="includes/functions.php">
<input type="hidden" name="group_id" value="$group_id" />
<input type="hidden" name="submit_join"/>
<button class="request" id="sub" name="submit_join">Join</button>
</form>
This jQuery script runs a PHP script.
$("#sub").click(function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(){ $("#sub").html("Applied").fadeIn().addClass("applied").removeClass("request");
});
});
$("#myForm").submit(function() {
return false;
});
This is what the PHP script does. (Not a prepared statement)
if (isset($_POST['submit_join'])) {
//User ID
$user_id = $_SESSION['user_id'];
$group_id = $_POST['group_id'];
$sql="INSERT INTO group_assoc (user_id, group_id, permission, dateTime) VALUES ('$user_id', '$group_id', 0, now())";
if (!mysqli_query($connection, $sql)) {
die('Error: ' . mysqli_error($connection));
}
}
-It works just fine when someone clicks the button once.
It triggers the jQuery script
The jQuery script triggers the PHP script
The PHP does its job
The jQuery removes the class "request" and puts a class "applied"
Problem:
When the same user clicks another button (meaning a duplicate of the button that they just clicked), the page ignores the jQuery script and does what it would normally do, refresh the page. This is the unwanted process.
Why several forms and therefore why several buttons? I am doing a PHP while loop for every group in the website and every form contains a button (Join) that allows you to join the group and change the value on the database using the jQuery script above.
Question: How can I rebind the jQuery script so that when another button (<button class="request" id="sub" name="submit_join">Join</button>) is clicked, it will not ignore the jQuery script?
The problem seems to be that you are working with duplicate IDs, try with classes instead of id
<form method="post" class="myForm" action="includes/functions.php">
<input type="hidden" name="group_id" value="$group_id" />
<input type="hidden" name="submit_join" />
<button class="request" class="sub" name="submit_join">Join</button>
</form>
and
$(document).on('submit', '.myForm', function () {
return false;
})
$(document).on('submit', '.sub', function () {
var $form = $(this).closest('form');
$.post($form.attr("action"),
$form.serializeArray(), function () {
$("#sub").html("Applied").fadeIn().addClass("applied").removeClass("request");
});
})
Its always a good idea to pass in the event to the event handler, and do a event.preventDefault() to avoid browser's default behaviour on the elements.
$("#myForm").submit(function(event) {
event.preventDefault();
});
As for the multiple forms, you can use one handler to handle form submits. $('#sub') will bind to only the first button on the page, use a class to attach to multiple buttons of the same type which will still be inefficient. Here is a sample :
$('.subbtn').click(function(e){
var $form = $(this).parents('form'),
subUrl = $form.attr('action');
e.preventDefault();
$.post(...) ;
})
This handler should take care of your requirement. You can however use a single handler attached to the common wrapper of the forms (worst case 'body') to improve efficiency.
Like what jagzviruz said, it's always best to use the submit event's event handler to prevent the page refresh. And also, make sure you don't have any duplicate element IDs.
My approach would be something like this: (untested)
HTML
<form method="post" class="myForm" action="includes/functions.php">
<input type="hidden" name="group_id" value="$group_id" />
<input type="hidden" name="submit_join"/>
<button class="request" class="submit" name="submit_join">Join</button>
JS
$(".myForm").each(function() {
var $form = $(this),
action = $form.attr('action'),
$submit = $form.find('.submit');
$form.submit(function(event) {
event.preventDefault();
return false;
});
$submit.click(function(event) {
event.preventDefault();
$.post(...);
});
});
It's pretty much the same solution as what jagzviruz proposed, but I prefer to do things like this inside an .each() for clarity.
I have a form using the form jQuery plug in to handel the posting of the data. In the example i am working with the data is psoted to another php file which reades a database and echos back a result which is displayed below the from.
The code works very well with one glitch. If you hit the enter button while the text filed is selected everything cleared including the result that has been written to the screen. Is it possible to disable to enter key and prevent it from doing this?
FORM:
<html>
<head>
</head>
<p>enter code here
<form name="form" action="" method="">
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name"/>
<input type="button" value="get" onclick="get();"/>
</form>
<div id="age"></div>
</p>
</body>
</html>
SCRIPT:
function get() {
$.post('data.php', {name: form.name.value},
function(output) {
$('#age').hide().html(output).fadeIn(1000);
});
}
}
Cheers.
You should consider using the jQuery Forms Plugin. It will save you from doing some of the dirty work, additionally it will intercept all ways of submitting the form - so instead of having to disable the RETURN key it will submit your form via AJAX.
If you don't want that, get rid of the button with the onclick event and replace it with a submit button and register your function as a onsubmit handöer:
$('form[name=form]').submit(function(e) {
e.preventDefault();
$.post('data.php', {name: form.name.value},
function(output) {
$('#age').hide().html(output).fadeIn(1000);
});
}
});
$(document).ready(function(){
$('form').submit(function(){
return false;
});
});
This will prevent the form from submitting, however the form will not work at all for users with javascript disabled.
A found some tuts and solved the issue.
I just put this in before my Jquery code to disable the enter button.
$(function () {
$('input').keypress(function (e) {
var code = null;
code = (e.keyCode ? e.keyCode : e.which);
return (code == 13) ? false : true;
});
});