I have question regarding form submit. I have this simple form on processFabrication.php to submit all the variables then process it to the database in another page called processExceededQty.php
Co, in processFabrication.php, I have
echo "<form action='processExceededQty.php' method='post'>";
When I click submit it goes to the processExceededQty.php.
What I am aiming to do is,
When user click submit, display confirmation yes/no with popup
After user click yes with the confirmation window, stay in processFabrication.php but methods in processExceededQty.php is still executed.
When user click no on the popup, go back and don't do form action
Any help would be greatly appreciated.
Something like this in your javascript:
function doSubmit(){
if (confirm('Are you sure you want to submit?')) {
// yes
return true;
} else {
// Do nothing!
return false
}
}
add the onsubmit to your form in html:
<form action='processExceededQty.php' method='post' onsubmit='doSumit()'>
Addition to #N0M3 answer.
Include below script in your <head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
and slight change in your function
function doSubmit(){
if (confirm('Are you sure you want to submit?')) {
// yes
$(this).submit(function(e){
e.preventDefault();
});
jQuery.ajax({
url : 'processExceededQty.php',
data : {'username':username}, // where first 'username' is your field name, and second one is your field's value
method: 'post',
success: function(data) {
// data is variable which has return data from `processExceededQty.php`
// do whatever you want with data
}
});
} else {
// Do nothing!
return false;
}
}
Use function on the "onsubmit" of the form like below,
<form action='processExceededQty.php' method='post' onsubmit='reutrn show_pop_up()'>
And on script you ca write following
<script>
function show_pop_up()
{
// show pop up
if(op_up_return =="Yes")
return true;
else
return false;
}
</script>
Hope this will help.
Related
I have to tried JavaScript.But it performs one form action only.Please explain how to an one button using two forms in same page.
I have to use the below code:
function my()
{
document.schedule.action = "firstaction";
document.schedule.target = "_blank";
document.schedule.submit();
return true;
}
function my1()
{
document.consultant.action = "secondaction";
document.consultant.target = "_blank";
document.consultant.submit();
return true;
}
Parallax form submissions are not possible
Because form submission means loading new page, so browse close all exiting connections like your previous form submission.
solution
Use ajax
function my()
{
$.ajax({
url:document.schedule.action,
type:'post',
data:$(document.schedule).serialize()
});
return true;
}
submit() would submit the form the normal way, thus reloading the page before the other/second form could be submitted. To do what you want use Ajax
A jQuery Ajax example:
$("#form1").submit(function(e){
e.preventDefault();
$.post("functions.php", {key1:"value1", key2:"value2"}, function(data){
//submit the second form here using the same $.post method
});
});
Ajax is the solution.
You can do something like this:
<form class="myform">
<!-- form 1 fields -->
</form>
<form class="myform">
<!-- form 2 fields -->
</form>
And using JQuery
$('.myform').sumit(function(e)) {
e.preventDefault();
// FORM VALIDATION
// Form 1 function
$.ajax({
url: "action1",
}).success(function() {
// DO SOMETHING
});
// Form 2 function
$.ajax({
url: "action2",
}).success(function() {
// DO SOMETHING
});
}
Btw in my opinion you don't need anymore two forms but just one.
I have a simple page that takes a form and makes a jsonp ajax request and formats the response and displays it on the page, this is all fine, but I wanted to add it so that if the form was populated (via php $_GET variables) then the form would auto-submit on page load but what happens instead is that the page constantly refreshes despite the submit function returning false.
Submit Button (just to show it doesn't have an id like submit or anything)
<button type="submit" id="check" class="btn btn-success">Check</button>
jQuery
$(document).ready(function() {
$('#my_form').on('submit', function() {
var valid = 1;
$('#my_form .required').each(function() {
if ($(this).val() == '') {
$(this).parents('.form-group').addClass('has-error');
valid = 0;
} else {
$(this).parents('.form-group').removeClass('has-error');
}
});
if (valid === 1) {
$.ajax({
url: '/some_url',
data: $('#my_form').serialize(),
type: 'GET',
cache: false,
dataType: 'jsonp',
success: function(data) {
var html = 'do something with data';
$('#results').html(html);
},
error: function() {
$('#results').html('An error occurred, please try again');
}
});
} else {
$('#results').html('Please fill in all required fields');
}
return false;
});
});
The part I added just after the $(document).ready(function(){ and before the submit was:
if ($('#input_1').val() != '' || $('#input_2').val() != '') {
// $('#check').trigger('click');
$('#my_form').submit();
}
Both those lines have the same effect but I am doing the same in another project and it works fine, as far as I can see, the only difference is the jQuery version, I'm using 1.11 for this page.
Update
Apologies, I seem to have answered my own question, I thought that since the programmatic submit was the first thing in $(document).ready(function(){ then maybe it was the case that the actual submit function wasn't being reached before the event was triggered so I simply moved that block after the submitfunction and it now works fine.
url: ''
it seems like you are sending your ajax request to nothing.
just an additional: if you want to submit your form through jquery without using AJAX, try
$("#myForm").submit();
it will send your form to the action attribute of the form, then redirect the page there.
I have 3 files
register.php
reg.js
reg.php
When I hit the submit button in register.php (looks like this)
<div id="phpcontenthere"></div>
<form action="reg.php" method="post" id="myForm">
<input type='submit' id='submit' value='Sth'>
</form>
<script type="text/javascript" src="reg.js"></script>
It shows the error messages of reg.php but in another window.
I want those error messages to be shown inside the register.php.
And the reg.js looks like this:
$("#submit").click( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info) {
$("#phpcontenthere").empty();
$("#phpcontenthere").html(info);
});
$("myForm").submit( function () {
return false;
});
});
Maybe this solution i want to create is not good, or it's good but i missed something I don't know, but I would be really happy if anyone could help me,
Thanks in advance!
Tibor
I'll teach you the logic, with sample code as I don't want to spoon-feed you.
Firstly, create an array called 'errors':
$errors = array();
Then while you have your checks, just inflate your array.
if(something) {
$errors[] = "Error description";
}
Then once all your errors are inflated, you check for the length, and if it is greater than 0 errors, then return the array.
if(count($errors) > 0) {
return $errors;
}
And then, you can display the array with the for loop.
$c = count($errors);
for($i=0; $i < $c; $i++) {
echo $errors[$i];
}
You have a few problems.
First, $("myform") should be $("#myform") -- you forgot the # so it wasn't matching the ID.
Second, you shouldn't define a handler for submit inside the click handler; event handlers should almost always be defined at the toplevel.
You should just put return false in the click handler. Or better, put all that code in the form's submit handler (clicking on the submit button submits the form).
$("#myForm").submit( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info) {
$("#phpcontenthere").html(info);
});
});
return false;
});
It's also not necessary to call .empty() before calling .html(), since the latter completely replaces what's there.
From what I see, you are still submitting the form (the piece of code that returns false when trying to submit is inside the click listener). Maybe that's why it is ignoring the return false, and indeed submitting the form (instead of posting it with ajax)
So you should try a javascript code like this:
$("#submit").click( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info) {
$("#phpcontenthere").empty();
$("#phpcontenthere").html(info);
}
);
});
$("#myForm").submit( function () {
return false;
});
Okay, so I am trying to use ajax. I've tried several ways of doing this but nothing is working for me. I believe the main problem I have is that ajax won't add to my database, the rest is managable for me.
Here is the relevant ajax-code:
$(document).ready(function(){
console.log($("going to attach submit to:","form[name='threadForm']"));
$("form[name='threadForm']").on("submit",function(e){
e.preventDefault();
var message = $("#message").val();
//assumming validate_post returns true of false(y)
if(!validatepost(message)){
console.log("invalid, do not post");
return;
}
console.log("submitting threadForm");
update_post(message);
});
});
function update_post(message){
var dataString = "message=" + message;
alert(dataString);
$.ajax({
url: 'post_process.php',
async: true,
data: dataString ,
type: 'post',
success: function() {
posts();
}
});
}
function posts(){
console.log("getting url:",sessionStorage.page);
$.get(sessionStorage.page,function(data){
$("#threads").html(data);
});
}
function validatepost(text){
$(document).ready(function(){
var y = $.trim(text);
if (y==null || y=="") {
alert("String is empty");
return false;
} else {
return true;
}
});
}
Here is the post_process.php:
<?php
// Contains sessionStart and the db-connection
require_once "include/bootstrap.php";
$message = $con->real_escape_string($_POST["message"]);
if (validateEmpty($message)){
send();
}
function send(){
global $con, $message;
$con->create_post($_SESSION['username'], $_SESSION['category'], $_SESSION("subject"), $message);
}
//header("Location: index.php");
?>
And lastly, here is the html-form:
<div id="post_div">
<form name="threadForm" method="POST" action="">
<label for="message">Meddelande</label><br>
<textarea id="message" name="message" id="message" maxlength="500">
</textarea><br>
<input type="submit" value="Skicka!" name="post_btn" id="post_btn"><br>
</form>
create_post is a function I've written, it and everything else worked fine until I introduced ajax.
As it is now, none of the console.log:S are getting reached.
Ajax works when jumping between pages on the website but the code above literally does nothing right now. And also, it works if I put post_process.php as the form action and don't comment out the header in post_process-php.
I apologize for forgetting some info. I am tired and just want this to work.
I would first test the update_post by removing the button.submit.onclick and making the form.onsubmit=return update_post. If that is successful place the validate_post in the update_post as a condition, if( !validate_post(this) ){ return false;}
If it's not successful then the problem is in the php.
You also call posts() to do what looks like what $.get would do. You could simply call $.get in the ajax return. I'm not clear what you are trying to accomplish in the "posts" function.
First you can just submit the form to PHP and see if PHP does what it's supposed to do. If so then try to submit using JavaScript:
$("form[name='threadForm']").on("submit",function(e){
e.preventDefault();
//assumming validate_post returns true of false(y)
if(!validate_post()){
console.log("invalid, do not post");
return;
}
console.log("submitting threadForm");
update_post();
});
Press F12 in Chrome or firefox with the firebug plugin installed and see if there are any errors. The POST should show in the console as well so you can inspect what's posted. Note that console.log causes an error in IE when you don't have the console opened (press F12 to open), you should remove the logs if you want to support IE.
Your function posts could use jQuery as well as it makes the code shorter:
function posts(){
console.log("getting url:",sessionStorage.page);
$.get(sessionStorage.page,function(data){
$("#threads").html(data);
});
}
UPDATE
Can you console log if the form is found when you attach the event listener to it?
console.log($("going to attach submit to:","form[name='threadForm']"));
$("form[name='threadForm']").on("submit",function(e){
....
Then set the action of the form to google.com or something to see if the form gets submitted (it should not if the code works). Then check out the console to see the xhr request and see if there are any errors in the request/responses.
Looking at your code it seems you got the post ajax request wrong.
function update_post(message){
console.log(message);
$.ajax({
url: 'post_process.php',
async: true,
//data could be a string but I guess it has to
// be a valid POST or GET string (escape message)
// easier to just let jQuery handle this one
data: {message:message} ,
type: 'post',
success: function() {
posts();
}
});
UPDATE
Something is wrong with your binding to the submit event. Here is an example how it can be done:
<!DOCTYPE html>
<html>
<head>
<script src="the jquery library"></script>
</head>
<body>
<form name="threadForm" method="POST" action="http://www.google.com">
<label for="message">Meddelande</label><br>
<textarea id="message" name="message" id="message" maxlength="500">
</textarea><br>
<input type="submit" value="Skicka!" name="post_btn" id="post_btn"><br>
</form>
<script>
$("form[name='threadForm']").on("submit",function(e){
e.preventDefault();
console.log("message is:",$("#message").val());
});
</script>
</body>
</html>
Even with message having 2 id properties (you should remove one) it works fine, the form is not submitted. Maybe your html is invalid or you are not attaching the event handler but looking at your updated question I think you got how to use document.ready wrong, in my example I don't need to use document.ready because the script accesses the form after the html is loaded, if the script was before the html code that defines the form you should use document ready.
I attempted to ask this question last week without a resolution. I am still unable to get this to work. What I would like to do is submit data entered through a WYSIWYG javascript editor to a JQuery script I have that will first tell the user if they are trying to submit an empty textbox The last thing I need it to do is tell the user if their data was entered successfully or not.
I am having a problem inside the JQuery script as nothing is being executed when I click the save button.
This editor uses javascript submit() that is tied to a small save icon on the editor. When the user presses the button on the editor, it fires the function I have in the form tag. That's about as far as I was able to get.
I think there is an issue with the form tag attributes because when I click anywhere on the editor, the editor jumps down off the bottom of the screen. I believe it has something to do with the onclick event I have in the form tag.
The first part of the JQuery script is supposed to handle form validation for the textarea. If that's going to be really difficult to get working, I'd be willing to let it go and just handle everything server side but I just need to get the data POSTed to the JQuery script so that I can send it to my php script.
Thanks for the help guys.
<form name="rpt" class="rpt" id="rpt" action="" onclick="doSave(); return false;">
function doSave()
{
$(function()
{
$('.error').hide();
$(".rpt").click(function()
{
$('.error').hide();
var textArea = $('#report');
if (textArea.val() == "")
{
textArea.show();
textArea.focus();
return false;
}
else
{
return true;
}
var dataString = '&report='+ report;
alert (dataString);return false;
$.ajax({
type: "POST",
url: "body.php?action=customer",
data: dataString,
dataType: 'json',
success: function(data){
$('#cust input[type=text]').val('');
var div = $('<div>').attr('id', 'message').html(data.message);
if(data.success == 0) {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-error');
} else {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-success');
}
$('body').append(div);
}
});
return false;
});
});
}
There are a few things you need to change. Firstly this:
<form name="rpt" class="rpt" id="rpt" action="" onclick="doSave(); return false;">
isn't the jQuery way. Plus its not the click() event you want. Do this:
<form name="rpt" class="rpt" id="rpt" action="">
<script type="text/javascript">
$(function() {
$("#rpt").submit(do_save);
});
</script>
The construction:
$(function() {
..
});
means "when the document is ready, execute this code". It is shorthand for and exactly equivalent to the slightly longer:
$(document).ready(function() {
..
});
This code:
$("#rpt").submit(doSave);
means "find the element with id 'rpt' and attach an event handler to it such that when the 'submit' event is executed on it, call the do_save() function".
And change doSave() to:
function doSave() {
$('.error').hide();
$(".rpt").click(function() {
$('.error').hide();
var textArea = $('#report');
if (textArea.val() == "") {
textArea.show();
textArea.focus();
return false;
} else {
return true;
}
var dataString = '&report='+ report;
alert (dataString);return false;
$.ajax({
type: "POST",
url: "body.php?action=customer",
data: dataString,
dataType: 'json',
success: function(data){
$('#cust input[type=text]').val('');
var div = $('<div>').attr('id', 'message').html(data.message);
if (data.success == 0) {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-error');
} else {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-success');
}
$('body').append(div);
}
});
});
return false;
}
Note: return false is in the correct place now so it actually prevents the form submitting back to the server. action="" just means the form will submit back to its current location so you have to prevent that.
function X() {
$(function() {
//... things you want to do at startup
});
};
Doesn't do what you want. Nothing is ever executed, because you never tell it to be executed.
You might want to try something like:
<script type="text/javascript">
jQuery(function($) {
//... things you want to do at startup
});
</script>
Also, you want the onsubmit event of the form. You can use
$('#theform').submit(function() {
//... perform the ajax save
});
In addition, you may want to look into the Form plugin.