submit form and check for complete without submit button - javascript

I need to submit a form and check for its completion without using the submit button.
I managed to submit it trough document.getElementById('logoForm').submit();, but now I need to call a function if the form was successfully submitted.
My form:
<form name="logoForm" id="logoForm" method="POST" target="frame" enctype="multipart/form-data" action="includes/uplLogo.php">
Submit function:
$("#file1").change(function() {
document.getElementById('logoForm').submit();
//setTimeout(reloadImg, 2000) this was how i called the next function but its not safe at all
alert('submited');
});
The function I want to be called on a successful submit:
function reloadImg(){
var exists = document.getElementById('AppId').value;
$.post("includes/step_img.php", {id: exists}, function(data){
document.getElementById('imgDiv').innerHTML=data;
});
}

You need to submit the form using AJAX, otherwise you will have a page reload, rendering all your JS void.
This is how you could do it with jQuery
//bind to submit
$("#logoForm").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
reloadImg();
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
alert("ERROR");
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#logoForm").submit(); //Submit the FORM

ok i got it working!!
$("document").ready(function(){
$("#file1").change(function() {
//bind to submit
$("#logoForm").submit(function(e)
{
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data: new FormData( this ),
processData: false,
contentType: false,
success:function(data, textStatus, jqXHR)
{
reloadImg();
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
alert("ERROR");
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#logoForm").submit(); //Submit the FORM
});
});
function reloadImg(){
var exists = document.getElementById('AppId').value;
$.post("includes/step_img.php", {id: exists}, function(data){
document.getElementById('imgDiv').innerHTML=data;
});
}
but once i click the file input i have to reload the page to make it work again... any ideas how to work around this?

As Regent said: "Amazing mix of pure JavaScript and jQuery"
if you will be using jquery first of all you will need to include the jquery library, I don't know if you did that.
Also, if you are working with jquery try to use all that jquery provide you to write less code.
Seeing your code I am assuming that you have a form with a input type file into. And when a file is loaded to the field, you want to submit the form. Also the form is targetted to a frame, so I am assuming that you have an iframe element there too.
To know if the form was successfully submitted you can use an ajax request but in this case your are sending files with the form, so you can not use an ajax request.
You can return a javascript code in your response that will be executed from into the iframe so, you can access to the parent element to do that you want
I have modified a little bit your code to integrate jQuery at all.
<html>
<head>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/latest/jquery.js"></script>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function () {
jQuery("#file1").change(function() {
jQuery('#logoForm').submit();
});
});
</script>
</head>
<body>
<form name="logoForm" id="logoForm" method="POST" target="frame" enctype="multipart/form-data" action="includes/uplLogo.php">
<input type="file" name="file1" id="file1" />
</form>
<iframe name="frame"></iframe>
</body>
</html>
Then in your includes/uplLogo.php you need to return the javascript code to execute a similar of reloadImg()
So, in your includes/uplLogo.php you could have:
<?php
...
Your code here
...
if($all_is_ok) { ?>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/latest/jquery.js"></script>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function () {
var id = jQuery('#AppId', window.parent.document).val();
jQuery.post("includes/step_img.php", {id: id}, function(data) {
jQuery('#imgDiv', window.parent.document).html(data);
});
});
</script>
<?php } ?>
I have not tested it because I just wrote it but I think that works.

Try to comment this line: e.unbind();
Try also to add a log just after the input file changes, and verify if you can see the log in the js console:
...
$("#file1").change(function() {
console.log('input file changed');
//bind to submit
...

for those who will need this in the future the problem was:
$("#file1").change(function()
i just changed that to:
function changed()
and add it to input on onchange method!

Related

specifying javascript function from button form

I'm using Ajax to display a comments widget on my site and am trying to upgrade from Recaptcha v2 to Recaptcha v3. So far it's gone well, comments successfully post, but instead of displaying the "thanks for submitting" modal, it just redirects to the form submission URL with the success data. This is not ideal.
The main change I made was to change the button code in my comment_form.html to this:
<button class="button g-recaptcha" id="comment-form-submit"
data-sitekey="{{ site.reCaptcha.siteKey }}"
data-callback='onSubmit'
data-action='submit'>
Submit
</button>
</form>
<script>
function onSubmit(token) {
document.getElementById("new-comment").submit();
}
</script>
(and added the id="new-comment" to the top of the form)
previously i had
<button class="button" id="comment-form-submit">Submit</button>
the relevant javascript code is:
(function ($) {
var $comments = $('.js-comments');
$('.js-form').submit(function () {
var form = this;
$("#comment-form-submit").html(
'<svg class="icon spin"><use xlink:href="#icon-loading"></use></svg> Sending...'
);
$(form).addClass('disabled');
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
contentType: 'application/x-www-form-urlencoded',
success: function (data) {
showModal('Comment submitted', 'Thanks! Your comment is pending. It will appear when approved.');
$("#comment-form-submit")
.html("Submit");
$(form)[0].reset();
$(form).removeClass('disabled');
grecaptcha.reset();
},
error: function (err) {
console.log(err);
var ecode = (err.responseJSON || {}).errorCode || "unknown";
showModal('Error', 'An error occured.<br>[' + ecode + ']');
$("#comment-form-submit").html("Submit")
$(form).removeClass('disabled');
grecaptcha.reset();
}
});
return false;
});
I'm pretty sure it's like a one line change to make the Ajax process the reply, but I'm totally out of my depth with javascript, so any thoughts are greatly appreciated.
--
Edit: The other example I saw calls the onSubmit function from their callback but since I'm using this weird main.js I don't know how to reference $('.js-form').submit(function (event) { from onSubmit
The default browser behaviour after submitting a form is to redirect on success, try preventing this by calling preventDefault on the event, eg:
$('.js-form').submit(function (event) {
event.preventDefault();
// the rest of your code
});

When and when doesn't success: value executes in jQuery Ajax method? (Header location not changed)

I'm submitting a form using jQuery Ajax.
The data is submitted successfully but there's a little problem. When I add the commented statements in this code, the success: function(){} doesn't run (location is not changed).
Q. 1 When I remove those statements, it runs. I don't understand this logic. When does it actually executes and how does checking for xy affects this?
Here's my Ajax code:
$(document).ready(function(){
$("#button").click(function(){
**//FOLLOWING TWO LINES MAKES SUCCESS NOT RUN**
//var **xy**= $("#digits").val();
//if(xy!=""){
$.ajax({
url: "submitform.php",
type: "POST",
data: $('#signupform').serialize(),
success: function(result){
$(location).attr('href', 'login2.php');
},
error: function(){
alert(error);
}
});
// }
});
});
Here's concerned input tag:
<form id="signupform" name="form1" method="post" enctype="multipart/form-data">
<input id="digits" type="text" name="phone" maxlength="10" placeholder="Enter your phone no." required />
......
Q.2 When I write event.preventDefault(); to stop the default action of submit button, the required atrributes of input fields don't work. Why is it so? Can it be solved?
To Question 2:
If you call preventDefault for the event of the click on the submit button, then the default behaviour (initiating the submit) is prevented, so the input fields are not checked.
You have to listen on the submit event of the form instead and prevent the default behaviour of this, because the submit event is send after the input elements are checked and before the form is submitted.
$(document).ready(function() {
$("#signupform").on('submit', function(e) {
e.preventDefault();
//FOLLOWING TWO LINES MAKES SUCCESS NOT RUN**
//var **xy**= $("#digits").val();
//if(xy!=""){
$.ajax({
url: "submitform.php",
type: "POST",
data: $('#signupform').serialize(),
success: function(result) {
$(location).attr('href', 'login2.php');
},
error: function() {
alert(error);
}
});
// }
});
});
When you use jquery ajax there is two types of result:
400 - OK status which be capture by the success function
402 or 500 are internal errors and those will be capture by the error function.
Now, in your error function youre trying to print an error variable that does not exist.
Also, when you use preventDefault you have pass variable that handles de event too cancel.

JavaScript/Ajax - How to run one PHP script before posting form to another one

I am almost at my wit's end trying to figure out why my code is not working.
Here is what I am trying to do:
1) Accept several variables in a form (myform).
2) Using an onsubmit, I want to use pass one or more of those variables to a script (process_info).
3) After process_info has executed, the form should be posted to the form's action URL ('save_info.php').
As you can see in the code below, I have tried several things:
Test 1: This simple alert is shown and the form is submitted to save_info.php.
Test 2: I copied and modified this jQuery script from another page on this site. No matter what I do, the script does not run. I know this because no alert message is shown.
Test 3: After removing the jQuery(document).ready statement from Test 2, the senddata function runs. Although it runs the process_info script, the form does not get posted to save_info.
<html>
<head>
<title>Form Test</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javaScript">
/* Test 1: this works - form is submitted to the action URL
function senddata() { alert('here'); }
*/
/* Test 2: this does not run (no alert shown) - form is submitted to the action URL */
jQuery(document).ready(function() {
function senddata() {
var formdata = jQuery("#myform").serialize();
var decoded = decodeURIComponent(formdata);
strip = decoded.replace(/[\[\]]/g, "_");
// alert(strip);
jQuery.ajax({
type: "POST",
url: 'process_info.php',
data: strip,
success: function(){ alert('success'); },
error: function(){ alert('failure'); },
complete: function(){
jQuery("#myform").submit(); //submit the form after ajax completes
}
});
return false; //stop the form from initially submitting
}
});
/* Test 3: this runs and the AJAX URL is executed, "success" is displayed - form is NOT submitted to the action URL
function senddata() {
var formdata = jQuery("#myform").serialize();
var decoded = decodeURIComponent(formdata);
strip = decoded.replace(/[\[\]]/g, "_");
// alert(strip);
jQuery.ajax({
type: "POST",
url: 'process_info.php',
data: strip,
success: function(){ alert('success'); },
error: function(){ alert('failure'); },
complete: function(){
jQuery("#myform").submit(); //submit the form after ajax completes
}
});
return false; //stop the form from initially submitting
}
*/
</script>
</head>
<body>
<form name="myform" id="myform" onsubmit="return senddata()" action="save_info.php" method="post" enctype="multipart/form-data">
<input type="text" name="id" />
<input type="text" name="last" />
<input type="submit" value="send" />
</form>
</body>
</html>
I assume that what I am trying to do is actually possible. What am I doing wrong?
ok, I have edited your code in a way that it works and I'll explain a few changes after the code.
<html>
<head>
<title>Form Test</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javaScript">
/* Test 2: this does not run (no alert shown) - form is submitted to the action URL */
jQuery(document).ready(function(){
$("#myform").submit(function(event){
event.preventDefault();
var formdata = jQuery("#myform").serialize();
var decoded = decodeURIComponent(formdata);
strip = decoded.replace(/[\[\]]/g, "_");
// alert(strip);
jQuery.ajax({
type: "POST",
url: 'process_info.php',
data: strip,
success: function(){ alert('success'); },
error: function(){ alert('failure'); },
complete: function(){
jQuery("#myform")[0].submit(); //submit the form after ajax completes
}
});
return false; //stop the form from initially submitting
});
});
</script>
</head>
<body>
<form name="myform" id="myform" action="save_info.php" method="post" enctype="multipart/form-data">
<input type="text" name="id" />
<input type="text" name="last" />
<input type="submit" value="send" />
</form>
</body>
</html>
So, first I have removed onsubmit from the <form> element in the html
Then changed the function the same as you did in your comment.
The last trick is that if I wanted to use jQuery("#myform").submit(); in the complete section of the ajax it would add another listener for the form submit event and would call the function again and again and again.
So I had to access the HTML form element directly and call the submit for it, that's the trick as you can see jQuery("#myform")[0].submit();

Unable to submit form with ajax without reloading parent

I am building a web application that will create a div on the page, use ajax to load a form into that div, and then have the form submitted without the parent page refreshing. I've read many examples on this site and others of how to do this, yet I'm puzzled why my proof-of-concept test is not working for me.
What successfully happens is that the parent page is creating the new div and is loading the form into the div. However, upon submitting the form, the parent page reloads. Using "Live HTTP Headers" in Opera, I can see that submitting the form is causing a GET rather than a POST, even though my Javascript is attempting to POST.
Can anyone help me understand why this is happening? Any help is very much appreciated.
Here is the code to the parent HTML page:
<html>
<head>
<script src=\"jquery-1.11.1.min.js\"></script>
<script src=\"jquery.min.js\"></script>
<script type=\"text/javascript\">
var num=1;
console.log('starting the code');
$(document).ready(function() {
console.log('document is ready');
$('#form1').submit(function(event) { // catch the form's submit event
console.log('form is going through submit');
$.ajax({ // create an AJAX call...
url: 'add_user.php', // the file to call
type: 'POST', // GET or POST
data: $('#form1').serialize(), // get the form data
success: function(data) { // on success..
$('#assign1').html(data); // update the DIV
},
error: function(xhr, status, e) {
console.log('status');
console.log('e');
}
});
event.preventDefault(); // cancel original event to prevent form submitting
});
});
function addToBox(divID) {
console.log('adding new assign to box');
var myNewDiv = document.createElement(\"div\");
myNewDivID = 'assign'+num;
myNewDiv.setAttribute('id', myNewDivID);
myNewDivID = '#'+myNewDivID;
var myBox = document.getElementById(divID);
myBox.appendChild(myNewDiv);
$.ajax({
type: 'GET',
url: 'add_user.php?id=1',
success: function(data) {
$(myNewDivID).html(data);
},
error: function(xhr, status, e) {
console.log('status');
console.log('e');
}
});
num+=1;
}
</script>
</head>
<body>
<div>
<div id=\"box1\"></div>
<img src=\"/icons/add.png\" alt=\"Create new box\" />
</div>
<div>
<div id=\"box2\"></div>
<img src=\"/icons/add.png\" alt=\"Create new box\" />
</div>
</body>
</html>
Here is the code to the PHP page (named add_user.php) with the form.
<?php
$n=0;
$id=$_GET['id'];
if ($_SERVER['REQUEST_METHOD']=="POST") {
echo "got the form!";
} else {
echo "<form id=\"form{$id}\"><select name=\"quantity\">\n";
for ($n=1;$n<=5;$n++) {
echo "<option value=\"answer{$n}\">option {$n}</option>\n";
}
echo "</select>\n<input type=\"submit\" /></form>";
}
?>
Thanks to the comment by A. Wolff, I replaced $('#form1').submit(function(event) { with $(document).on('submit','#form1', function(event){ and it worked.
Thanks A. Wolff!

Prevent redirection when form is submitted programmatically

I've got a form on the html page which gets submitted by javascript in some cases. The problem is that browser window change its location to the action URL specified for this form. Is there any way to prevent it of working this way?
Use a javascript library to submit the form via Ajax (xhr) or submit to iframe
Full Jquery example:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#yourForm').submit(captureSubmit)
})
function captureSubmit(event) {
var frm = $(event.originalTarget);
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function(results) {
// do stuff
alert(results);
},
error: function(result) {
// handle the error
alert(result.status + ' ' + result.statusText);
}
});
return false;
}
</script>
<form id="yourForm" action="foo.html" method="POST">
Name: <input type="text" name="name">
<button type="submit">Submit</button>
</form>
[EDIT] made example more complete.
Post it with Ajax
You can either:
Submit with AJAX
Submit to an iframe

Categories

Resources