capture submit event with dynamically added content with JavaScript - javascript

I am building a sort of page builder where the user can add blocks to the page and then save the layout. I have encountered a problem that I can't seem to figure out. I have a form that is dynamically added to the page with JavaScript containing a file input as so:
<form class="upload " action="" method="post">
<input id="" type="file" class="fill" name="upload">
<img src="/admin/img/default.png" alt="">
</form>
After adding the content I call the following function to add event listeners. $el corresponds to the file input.
function changeListen($el){
$el.addEventListener('change', function(){
$el.parentElement.submit();
});
$el.parentElement.addEventListener('submit', function(e){
e.preventDefault;
// call Ajax request...
});
}
I want to be able to update the database with an Ajax request when an image is selected, therefore I submit the form within the change event, so far so good, but for some reason the submit event is not taken into account and the page reloads. Any solutions or workaround appreciated, preferably not jQuery.

By using onsubmit event in HTML, you can call javascript function this way and do ajax calls.
Javascript sample
<script>
function doSomething() {
alert('Hello, World');
return false;
}
</script>
HTML Sample
<form onsubmit="return doSomething();">
<input type="submit" value="Submit" />
</form>
EDIT: return false in javascript so ? does not appear in URI after clicked

Related

What is the proper way to submit a form with JS and still post all form data successfully?

I'm working with an embedded app on our dev site and when I click the submit button inside the iframe, I am triggering a manual submission event on another form (not in an iframe) on that page. If I manually click the submit button for the form, my data posts and everything works correctly. However, I want to eliminate an extra user click and submit the external form automatically when a user submits the other form inside the iframe.
I've got everything working correctly on a base level. When a user clicks the submit button in the iframe, I am using JQuery to grab values from inside the iframe and set values in this external form. Using the jquery 'submit()' event, I am then able to submit that external form. The problem is, the page refreshes and the data doesn't go anywhere. If I remove the 'submit()' event and manually click the submit button, the form posts and in this case, adds a product with custom data to the product cart.
As a proof of concept, this is my 'iframed' HTML.
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Proof of Concept</h1>
<p>Total cost: $<span id="cust_price">222.22</span> plus shipping.</p>
<p>Quote number: <span id="quot_num">1546751962211</p>
<form method="POST" enctype="multipart/form-data" id="newQuoteForm">
<button type="submit" class="btn btn-primary" name="new-app-btn">Add to Cart</button>
</form>
</body>
<footer>
</footer>
</html>
Here is my on-page form that is OUTSIDE the iFrame.
<form method="POST" enctype="multipart/form-data" id="outer-quote-form" action="/checkout/">
<label class="quote_number">Quote Number:
<input type="text" id="quote_number" name="quote_number" value="">
</label>
<label class="custom_price">price:
<input type="text" id="custom_price" name="custom_price" value="">
</label>
<button type="submit" class="btn btn-primary" name="ws-add-to-cart">Add to Cart</button>
</form>
Then, I have JQuery working to grab the iframed values and puts them in the exterior form. Afterwards, it fires a 'submit()' event on that form.
<script>
jQuery('#newQuoteApp').load(function() {
var iFrameDOM = jQuery("iframe#newQuoteApp").contents();
jQuery('#newQuoteApp').contents().find('#newQuoteForm').submit(function() {
jQuery("input#custom_price").val(jQuery('#newQuoteApp').contents().find('#cust_price').text()); // updated
jQuery("input#quote_number").val(jQuery('#newQuoteApp').contents().find('#quot_num').text());
jQuery("#outer-quote-form").submit();
return true; //return false prevents submit
});
});
</script>
Except when the jquery submit() event fires, the form appears to submit and the page refreshes but no data is posting as it does when I manually submit the form. Is there an extra step here or a better way to fire the form submit with post data?
Edit: Adding the PHP function that isn't firing on jquery submit() for context.
if (isset($_POST['ws-add-to-cart'])) {
add_action( 'init', 'add_product_to_cart' );
function add_product_to_cart() {
global $woocommerce;
global $product;
$product_id = 138;
$woocommerce->cart->add_to_cart($product_id);
}
header("Location:https://www.devsite.com/checkout/");
}
The reason for the form not submitting because you are submitting the whole form without the submit button which is <button type="submit" class="btn btn-primary" name="ws-add-to-cart">Add to Cart</button> which you have declared in php to get a post request like this
if (isset($_POST['ws-add-to-cart'])) {...
When you call submit(); on the form via the get method, you see '/new-quote/?quote_number=1546751962211&custom_price=222.22'
but where's ws-add-to-cart, it's not submitting and that's the reason why php isn't getting your request
The fix will be to add .click() on the submit button instead of submitting the form
<script>
function enterVals($val){
var price = $val.price;
document.getElementById("quote_number").value = $val.num
document.getElementById("custom_price").value = $val.price
document.getElementsByName("ws-add-to-cart").click();
}
</script>
Or in your script in case you want to use jquery, this is the fix
<script>
jQuery('#newQuoteApp').load(function() {
var iFrameDOM = jQuery("iframe#newQuoteApp").contents();
jQuery('#newQuoteApp').contents().find('#newQuoteForm').submit(function() {
jQuery("input#custom_price").val(jQuery('#newQuoteApp').contents().find('#cust_price').text()); // updated
jQuery("input#quote_number").val(jQuery('#newQuoteApp').contents().find('#quot_num').text());
jQuery("button[name=ws-add-to-cart]").click();
return true; //return false prevents submit
});
});
</script>
This is definitely the answer and sorry for my stupidity, i didn't pay required attention before
try removing return true from your js code
if that doesn't work, try changing the <form method="POST" to <form method="GET" to debug the values in the url just for checking that the form actually fires up with values
Alternative method: Old school method
code for page OUTSIDE the Iframe
<script>
function enterVals($val){
var price = $val.price;
document.getElementById("quote_number").value = $val.num
document.getElementById("custom_price").value = $val.price
document.getElementById("outer-quote-form").submit();
}
</script>
code for the Iframe file
<script type="text/javascript">
$('#newQuoteForm').on('submit', function(event) {
var Page = window.parent;
var allVals = {
price:$('#cust_price').text(),
num:$('#quot_num').text()
}
Page.enterVals(allVals);
event.preventDefault();
});
</script>
Explanation
window.parent refers to the parent window where the iframe is loaded on, with reference to this we can trigger functions that are in the parent window so by this, we created a variable and added the information which is sent by the function enterVals() to the window
The enterVals() function just puts the values and submits the form without any jQuery.
What is the proper way to submit a form with JS?
This might not be the 'best' way to submit a form with js but is cross-browser which is good

submit a form without using a submit button

I am trying to submit this for without using a submit button. Here I have used javascript and once the form has submitted user should be directed to the B.php.
html code
<form id="jsform" action="B.php" method="POST" target="_blank">
<input type="hidden" value="test" name="title"/>
</form>
java-script code
<script type="text/javascript">
document.getElementById('jsform').submit();
</script>
These 2 code lines run separately but not running together. Any mistakes have I done.
In javascript you can do this:
window.onload=function() {
document.getElementById("jsform").submit(); // using ID
}
And with jQuery
$(function() {
$("#jsform").submit(); // using ID
});
I write my comment as an actual answer this time.
Drop target="_blank" and it should work just fine. Otherwise your browser might see it as a popup.
Also make sure your JS is run after your form.
Use form name to submit
document.myform.submit();

How would I go about changing the contents of a div after the user searches?

So I have this form:
<form method="post" action="index.php" id="searchform">
<input type="text" name="search" placeholder="Search...">
<input type="image" src="img/img1.png" alt="submit" onmouseover="hover(this);" onmouseout="unhover(this);" /></a>
</form>
When the user searches for something I want to change this div:
<div class = "mainText">
<h2>Today's Events: </h2>
</div>
To say this:
<div class = "mainText">
<h2>Results: </h2>
</div>
How can I do this?
EDIT: Is it possible to run this code from within a php if statement?
jquery .text() seems a better fit, so you can just change the text of the tag.
$(".mainText h2").text("Results:");
More on this here:
http://www.w3schools.com/jquery/html_text.asp
The action in your form is the destination of where your form ends up.
If you are looking to control the dom elements you need something like javascript or jquery to control the front end of your application.
You could use jquery to simply listen for when your user has clicked the button or submitted the form and parse the results (in this case, just switching html text). *Remove the the action destination otherwise the page will redirect to index.php
$('form').submit(function(){
$('.mainText').html('<h2>Results: </h2>');
return false;
});
Common usage is to put an ajax call in the submit function to retrieve some data from outside the page source. Hopefully that puts you on track :)

How to modify submitted file client-side in JavaScript/jQuery

I want to modify the file submitted by user on the client side, before it reaches my server. To modify it I want to use Flash applet that would communicate with JavaScript.
<form action="" method="post" enctype="multipart/form-data">
<input type="file" id="id_file">
<input type="submit" value="Submit">
</form>
Is it possible to do it? If yes, I would appreciate any tips how should it be done :)
Should I convert it to string? Or maybe JS comes with some functions to make such operations easier?
$( "form" ).change(function(x) {
//pass file input to Flash applet
x.preventDefault();
flashApplet.proceed($('#id_file').value);
});
function callback(modified_file) {
// Flash applet has modified the file
// Now submit the form with a new, modified file
$('#id_file').value = modified_file;
trigger_submit();
}
The file can be either a video, an audio or an image.
Don't use a submit button, instead use a normal button disguised to look like a submit button, and then you can check when the button is clicked, do your stuff, then submit the form via javascript by using
document.getElementById("myform").submit();
I would replace your current html with:
<form action="" method="post" enctype="multipart/form-data" id="myform">
<input type="file">
<button id="submit">Submit</button>
</form>
And then js:
document.getElementById('submit').onclick = function() {
//do your flash stuff
}​;
function callback(){
//here we submit the form
document.getElementById("myform").submit();
// because the file itself has been modified, this is all we need to do.
}
Basically, use a false submit button, to do what you want first.

Can an onsubmit event insert an image into the page before the page submits?

Can an onsubmit event insert an image into the page before the page submits/transfers control to the next page?
I am using classic asp.
Of course. The function resolves before the form is submitted.
(Although… while an img element may be inserted into the page, it might not load before the browser has gone to the next one, and even if it does, the user might not have time to see it clearly)
Yes . You can insert the HTML code (through javascript):
<img src="imgsrc">
But it takes a little time for loading the image. The form send the user to another page in new window or in the same window? Why would you want to insert an image in the current window if the page will be replaced with the new one?
Yes you can do this. It would be easier (for me to write) if you used jquery:
html:
<form id="myForm" action="">
<input type="text" id="someId" />
<input type="submit" id="submit" value="submit" />
</form>
and then JavaScript would be:
$(document).ready(function() {
$("#myForm").submit(function() {
$(this).append('<img src="someImage.jpg" alt="" />');
});
});
http://jsfiddle.net/rYUbQ/
But like others have said it might not be loaded and displayed before the form submits so you might want to instead look in to preloading the image and then just setting it to visible before the page submits.

Categories

Resources