I have this basic HTML page and there is a form to upload data to a MySQL database.
There is also a JavaScript that passes data to the process.php file. Into this file, I have an INSERT query. I use this script because I do not want to reload the page on submit.
Now I have 2 problems:
1) When I send data to the MySQL table (clicking on submit button), the first time 1 data = 1 record inserted and this is correct. If I insert a new data into the input form field, I have 1 data = 2 records equal. The third time, 3 records and so on...
But if I print what is passed by POST with print_r($_POST), I have always one data Array ( [comune] => foo ).
I also tried to use unset() without success.
2) When I click for the first time on submit button, there's no action, I have to click twice.
This is the HTML page with the JS script:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta charset="utf-8" />
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".formValidation").validate({
debug: false,
rules: {
name: "required",
email: {
required: true,
email: true
}
},
messages: {
name: "Please let us know who you are.",
email: "A valid email will help us get in touch with you.",
},
submitHandler: function(form) {
// do other stuff for a valid form
$('.formValidation').on('submit', function () {
$.post('process.php', $(this).serialize(), function(data){
$('#results').html(data);
});
})
}
});
});
</script>
</head>
<body>
<div class="row">
<div class="col-xs-12">
<form id="myform2" class="formValidation" name="myform2" action="" method="post"></form>
<div class="col-xs-12 col-sm-4">
<div class="widget-box">
<div class="widget-body">
<div class="widget-main">
<div>
<label for="form-field-select-1">form</label>
</div>
<hr>
<div class="widget-body">
<div class="widget-main">
<div>
<input type="text" name="comune" id="comune" value="" placeholder="Add something" form="myform2">
<input type="submit" name="submit" value="Submit" class="btn btn-sm btn-success" form="myform2">
<p id="result"></p>
<div id="results"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</body>
</html>
and the process.php
foreach( $_POST as $key => $value ) {
$sql = "INSERT INTO tbl_".$key."(nome_".$key.") VALUES ('$value')";
$result = dbQuery($sql);
unset($key);
unset($value);
}
You have too many submit handlers.
Just do the ajax in the submitHandler callback option of the plugin.
Internally it is already doing the on('submit') so the first time you click it...the handler you wrote to do the ajax is created but isn't sending yet
The next time it will actually send the form twice and add another submit handler. A third click would send 3 times and add another submit handler and so on
submitHandler: function(form) { // fires only when valid
$.post('process.php', $(form).serialize(), function(data) {
$('#results').html(data);
});
}
your submit handlers are stacking one by one.. and each time requests to the php files increases, causing inserting more than once in database.
Use
submitHandler: function (form) {
$.post('process.php', $(this).serialize(), function (data) {
$('#results').html(data);
});
return false;
}
Hope this helps
Related
I'm using a modal from the Kube CSS & JS framework (6.5.2) with a form inside it. When I hit enter, the modal closes without submitting the form.
Edit: this doesn't happen when focused on password or search inputs - changing the type from 'text' to 'password' fixes the issue.
<!DOCTYPE html>
<html>
<head>
<title>Basic Template</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Kube CSS -->
<link rel="stylesheet" href="dist/css/kube.css">
</head>
<body>
<h1>Hello, world!</h1>
<div id='ui-modal-test' class='modal-box hide'>
<div class='modal' style='width:95%'>
<span class='close'></span>
<div class='modal-header'>Modal Form Test</div>
<div class='modal-body'>
<form id="ui-modal-form">
<input type="text" name="field1">
<input type="text" name="field2">
<input type="text" name="field3">
<button>Apply</button>
</form>
</div>
</div>
</div>
<button data-component="modal" data-target="#ui-modal-test">Open</button>
<!-- Kube JS + jQuery are used for some functionality, but are not required for the basic setup -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="dist/js/kube.js"></script>
</body>
</html>
JS:
$('#ui-modal-form').on('submit', function(event){
event.preventDefault(); // modal still closes before submitting form
var field1 = $(this).find('input[name=field1]').val().toLowerCase();
var field2 = $(this).find('input[name=field2]').val();
var field3 = $(this).find('input[name=field3]').val();
$.post('/post.php', {
field1: field1,
field2: field2,
field3: field3,
}, function(response){
var response = JSON.parse(response);
});
});
I'd like the form to submit when the user hits enter on any of the inputs, without closing the modal box.
I had no idea about Kube, but I tried what you said, that was an issue. Then I opened the kube.js file in dist folder to check out the modal.
I found this specific function to be the cause at line number 2167 -
handleEnter: function(e)
{
if (e.which === 13)
{
e.preventDefault();
this.close(false);
}
}
13 is the code for Enter key event. It's by default in kube, I guess. Maybe you can override this, I think there are some functions in it to disable events. If I change the parameter like this this.close(true), it works well.
Hope this gives you the cause of why this is happening.
Kube seems nice :)
<form onSubmit={event => event.preventDefault()}>
<input type="text" name="field1">
<input type="text" name="field2">
<input type="text" name="field3">
<button>Apply</button>
</form>
you can also refer if still not work:
submit isn't required, so in your case I would recommended moving your logic over to beforeSubmit and always return false as this is triggered before the modal closes. Currently, there's no way to manually close the modal, other than triggering the event modal:destroy. This is an example:
var Modal = Backbone.Modal.extend({
template: _.template($('#modal-template').html()),
submitEl: 'button',
beforeSubmit: function() {
// show your awesome loader here
this.model.save(this.model.attributes, success: function() {
this.trigger('modal:destroy');
});
return false;
}
});
Your modal doesn't submit if it doesn't succeed and beforeSubmit is only triggered onEnter and onClick of the button.
$('input[type=text]').keypress(function (e) {
if (e.which == 13) {
e.stopPropagation();
$('form').submit();
}
});
I was recently doing a PHP web-app, which turns out needs AJAX to display temporary and permanent results without reloading the page or redirecting to another page. Just simply update.
So I have a form on my index, where it collects search terms:
<form action="search.php" method="post">
<label for="fname" id="label">Enter search terms:</label>
<br>
<input type="text" id="fname" name="search"><br>
<input type="submit" id="submit">
Then I have it take it to my PHP script, which then processes the search terms and in theory should display them on the same page just in the other paragraph with something like this which is permanent:
echo 'Selected search terms: '. $terms. ".<br>
Search terms found: ".$termc."." ;
While my PHP script is working, I display a permanent "Loading..." and when it finishes it should display "Done." replacing the "Loading..." text.
Would anyone know how I could implement this with AJAX? How could I talk to PHP?
use the below code to help display data with out refresh the page.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>New User Registration</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>
<div id="newUserHld">
<form name="serarch_frm" method="post" id="serarch_frm">
<label for="fname" id="label">Enter search terms:</label>
<br>
<input type="text" id="fname" name="search"><br>
<input type="submit" id="submit" onclick="formSubmit(); return false;" >
</form>
</div>
<div id="success">
</div>
</body>
<script>
function formSubmit(){
$.ajax({
type:'POST',
url:'search.php',
data:$('#serarch_frm').serialize(),
success:function(response){
$('#success').html(response);
}
});
return false;
}
</script>
</html>
create the search.php file and put this code.
<?php
echo 'Selected search terms:'.$_POST['search'];
exit;
?>
you need to write js code something like this
(function($){
$(document).ready(function(){
$("form").submit(function(e){
$( ".result" ).html( "Loading.." );
e.preventDefault();
// ajax call to your php file
$.post( "file.php", function( data ) {
$( ".result" ).html( data );
});
});
});
})(jQuery);
Please follow below step.
1) You can put form tag like this <form onsubmit="submitFormData()">
2) Create javascript function.
3) function submitFormData(){ var form_data ='search='+$('#fname').val();$("#loading").show(); $.ajax({url: "yourphpfile.php",type: "POST",data: form_data,success: function (res){$("#loading").hide();});}
There are two inputs in my form. The first input can be validated before an ajax function. The second input can't be validated. The second input comes from a page using ajax and the submit button also comes from the page using ajax. I need to validate the second input which comes from the page using ajax. Also the submit button which comes from the page is not working. Please help me.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#form").submit(function(){
if ($('#Name1').val().length<3) {
alert ("please enter your first names");
$('#Name1').focus();
return false;
}
$.ajax({
url: "result.php",
method: "GET" // Either get or post
}).done(function(response) {
var splitted = response.split("|"); // RESULT
$("#Div1").html(splitted[0]); // The first name
$("#Div2").html(splitted[1]); // The first name
});
return (false);
if ($('#Name2').val().length<3) {
alert ("please enter your second names");
$('#Name2').focus();
return false;
}
});
});
</script>
</head>
<body>
<form id="form" action="Page.php">
<div style="float:left;">
<b>Name1:</b>
</div>
<input id="Name1" type="text">
<br><br><br><br>
<div style="clear:both;">
<div style="float:left;">
<b>Name2:</b>
</div>
<div id="Div1" style="float:left;">
</div>
<br><br><br>
<div style="clear:both;">
<div id="Div2">
<button>First Event</button>
</div>
</div>
</div>
</form>
</body>
</html>
This is result.php
<input type="text" id="Name2">
i need to validate this input. | <button>Second Event</button>
There's a few ways you can do this, however because I am on my phone I can't give you a detailed example.
What I recommend for you to look into is sending the AJAX request as JSON data to your PHP file, you can then validate the JSON data within the PHP file and return a response to the front end accordingly.
Within the PHP file you can return any value as a response, meaning that if you echo "success" or "true", you can see whether the data is what you are looking to receive from the user.
I would highly recommend doing as much validation possible in the back end. It is a good habit to get in to as anything can be manipulated on the front end of a website.
This code works well. i have solved myself.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#form").submit(function(){
if ($('#Name1').val().length<3) {
alert ("please enter your first names");
$('#Name1').focus();
return false;
}
if ($('#hidden').val().length<3) {
$.ajax({
url: "result.php",
method: "GET" // Either get or post
}).done(function(response) {
var splitted = response.split("|"); // RESULT
$("#Div1").html(splitted[0]); // The first name
$("#Div2").html(splitted[1]); // The first name
});
//alert ("please verify");
return false;
}
if ($('#Name2').val().length<3) {
alert ("please enter your second names");
$('#Name2').focus();
return false;
}
});
});
</script>
</head>
<body>
<form id="form" action="Page.php">
<div style="float:left;">
<b>Name1:</b>
</div>
<input id="Name1" type="text">
<br><br><br><br>
<div style="clear:both;">
<div style="float:left;">
<b>Name2:</b>
</div>
<div id="Div1" style="float:left;">
<input id="hidden" type="hidden">
</div>
<br><br><br>
<div style="clear:both;">
<div id="Div2">
<button>First Event</button>
</div>
</div>
</div>
</form>
</body>
</html>
result.php
<input type="hidden" id="hidden" value="something"> <input type="text" id="Name2"> | <input id="button" type="submit" value="Second Event">
I have a HTML form. On submission the form POST values to page.php. The view then navigates to page.php and displays a success message. I want to prevent the user from navigating to page.php, and display <div id="first">
In other words, what i want to do is a reset. (Displaying <div id="first"> after user clicks the Done button)
<form action="page.php" method="post">
<div id="first" class="m span3">
THIS DIV CONTAINS FEW TEXT BOXES
</div>
<div id="second" class="m2 span3">
THIS DIV CONTAINS FEW TEXT BOXES AND COMBOBOXES
</div>
<div id="last" class="m3 span3">
THIS DIV CONTAINS FEW TEXT BOXES
</div>
</form>
Once the user clicks the DOne button the following function gets fired
function onComplete() {
$('form').submit();
alert("clicked");
}
if you want to post data to main.php without redirecting the page I recommend you to use Ajax. this is a simple code but can give you an idea to build your application :
<html>
<head>
<script type="javascript" src="jquery.js"></script>
<script type="text/javascript">
function complete() {
$.ajax({
type : "post",
data : "text="+$("#"+textbox_1).value,
url : "page.php",
success : function(response){
alert("Done!");
}
});
}
</script>
</head>
<body>
<form action="page.php" method="post">
<input type="text" id="textbox_1">
<button onclick="complete()">submit</button>
</form>
</body>
</html>
and use $_POST['text'] in page.php
$('form').submit(function (e) {
e.preventDefault();
$('first').show();
}
Try something like this.
you can ad a value to the url and use that one value to call the div.
eg:
<form action="page.php?action=formSent" method="post">
// form data
</form>
then use some php to get the action call and use it to show the div:
<?php
if(isset($_GET['action']) && $_GET['action'] == "formSent" ){
<div id="first">
div content
</div>
}
?>
you can place the php code above of the form
What's the easiest way to clear this form after refresh. The way I have tried will clear the form but not submit to the database. Could someone else explain to me the best way to do this.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($){
$("#newsletterform").validate({
debug: false,
rules: {
name: "required",
email: {
required: true,
email: true
}
},
messages: {
name: "Please let us know who you are.",
email: "A valid email will help us get in touch with you.",
},
submitHandler: function(form) {
// do other stuff for a valid form
$.post('newsletter.php', $("#newsletterform").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
</script>
</head>
<div id="content">
<div id="newsletter-signup">
<h1>Sign up for News, Updates, and Offers!</h1>
<form id="newsletterform" action="" method="post">
<fieldset>
<ul>
<li>
<label for="name">Name:</label>
<input type="text" name="name" />
</li>
<li>
<label for="email">Email:</label>
<input type="text" name="email" />
</li>
<div id="results"><div>
<li>
<input type="submit" value="submit" name="signup" onclick="" />
</li>
</ul>
</fieldset>
</form>
</div>
</div>
</html>
You can add this to the callback from $.post
$( '#newsletterform' ).each(function(){
this.reset();
});
You can't just call $( '#newsletterform' ).reset() because .reset() is a form object and not a jquery object, or something to that effect. You can read more about it here about half way down the page.
You can reset your form with:
$("#myform")[0].reset();
Better way to reset your form with jQuery is Simply trigger a reset event on your form.
$("#btn1").click(function () {
$("form").trigger("reset");
});
try this in your post methods callback function
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
for more info read this
Propably this would do it for you.
$('input').val('').removeAttr('checked').removeAttr('selected');
A quick reset of the form fields is possible with this jQuery reset function.
$(selector)[0].reset();
Just add this to your Action file in some div or td, so that it comes with incoming XML object
<script type="text/javascript">
$("#formname").resetForm();
</script>
Where "formname" is the id of form you want to edit