Is it possible to delete iframe after upload - javascript

I currently use an iframe in an AJAX upload form, my question is once the file has uploaded to the iframe it appends the data to a div, so would i be safe to say i can remove the iframe once the load has completed?
my js is
$("#formsubmit").click(function (event) {
event.preventDefault();
var iframe = $('<iframe name="postiframe" id="postiframe" style="display: none" />');
$("body").append(iframe);
var form = $('#theuploadform');
form.attr("action", "uploader.php");
form.attr("method", "post");
form.attr("enctype", "multipart/form-data");
form.attr("encoding", "multipart/form-data");
form.attr("target", "postiframe");
form.attr("file", $('#userfile').val());
form.submit();
$("#postiframe").load(function () {
iframeContents = $("#postiframe")[0].contentWindow.document.body.innerHTML;
$("#textarea").html(iframeContents);
$("#postiframe").remove(); // i thought this would do it but it doesn't
});
return false;
});
Also even though i have event.preventDefault(); if i remove the return false at the bottom it still submits the form (refreshes to new page).
my html is:
<div id="uploadform">
<form id="theuploadform" action="">
<input id="userfile" name="userfile" size="50" type="file" />
<input id="formsubmit" type="submit" value="Send File" />
</form>
</div>
<div id="textarea"></div>
So to summarize my questions:
Is it possible to delete the iframe after an upload once it has copied to the "textarea"
if so the $("#postiframe").remove doesn't work
does anyone know why when i remove return false, it reloads the page instead of using the event.preventDefault(); at the beginning
Thank you in advance.

Your <iframe> is being appended to the window document through JavaScript after page load, use:
$(document).find('#postiframe').remove();
That'll transverse through the DOM and find your newly appointed <iframe>, and then remove it dynamically from the DOM as hoped.
Try <input type="button" /> to treat the form instead of <input type="submit" />, if you still want to handle the <input type="submit" /> form submission still, try:
$('#theuploadform').submit(function(event){
event.preventDefault();
});
function instead, that'll allow jQuery to prevent the default behaviour of the entire form and all it's child elements.

Related

Make the click-button code not disappear instantly? [duplicate]

I have a button (<input type="submit">). When it is clicked the page reloads. Since I have some jQuery hide() functions that are called on page load, this causes these elements to be hidden again. How do I make the button do nothing, so I can still add some action that occurs when the button is clicked but not reload the page.
There is no need to use JS or jQuery.
to stop the page to reload, just specify the button type as 'button'.
If you don't specify the button type, the browser will automatically set it to 'reset' or 'submit' which causes the page to reload.
<button type='button'>submit</button>
Use either the <button> element or use an <input type="button"/>.
In HTML:
<form onsubmit="return false">
</form>
in order to avoid refresh at all "buttons", even with onclick assigned.
You could add a click handler on the button with jQuery and do return false.
$("input[type='submit']").click(function() { return false; });
or
$("form").submit(function() { return false; });
In HTML:
<input type="submit" onclick="return false">
With jQuery, some similar variant, already mentioned.
You can use a form that includes a submit button. Then use jQuery to prevent the default behavior of a form:
$(document).ready(function($) {
$(document).on('submit', '#submit-form', function(event) {
event.preventDefault();
alert('page did not reload');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form id='submit-form'>
<button type='submit'>submit</button>
</form>
You could also use JavaScript for that:
let input = document.querySelector("input");
input.addEventListener("submit", (event) => {
event.preventDefault();
})
As stated in one of the comments (burried) above, this can be fixed by not placing the button tag inside the form tag. When the button is outside the form, the page does not refresh itself.
I can't comment yet, so I'm posting this as an answer.
Best way to avoid reload is how #user2868288 said: using the onsubmit on the form tag.
From all the other possibilities mentioned here, it's the only way which allows the new HTML5 browser data input validation to be triggered (<button> won't do it nor the jQuery/JS handlers) and allows your jQuery/AJAX dynamic info to be appended on the page.
For example:
<form id="frmData" onsubmit="return false">
<input type="email" id="txtEmail" name="input_email" required="" placeholder="Enter a valid e-mail" spellcheck="false"/>
<input type="tel" id="txtTel" name="input_tel" required="" placeholder="Enter your telephone number" spellcheck="false"/>
<input type="submit" id="btnSubmit" value="Send Info"/>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#btnSubmit').click(function() {
var tel = $("#txtTel").val();
var email = $("#txtEmail").val();
$.post("scripts/contact.php", {
tel1: tel,
email1: email
})
.done(function(data) {
$('#lblEstatus').append(data); // Appends status
if (data == "Received") {
$("#btnSubmit").attr('disabled', 'disabled'); // Disable doubleclickers.
}
})
.fail(function(xhr, textStatus, errorThrown) {
$('#lblEstatus').append("Error. Try later.");
});
});
});
</script>
Use event.preventDefault() in the first line of your event function.
Buttons must be of the type button and contain type="submit" in the button html.

capture submit event with dynamically added content with 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

Send form to mail via PHP, without page refresh and fields cleared

I have a form on my website, which sends the information to my email via PHP code. It all works like a charm, though when I submit the form it refreshes/reloads the page.
Is there a way to make it so that when the user clicks the submit button that the page won't refresh and the fields will be cleared as well?
I've been finding many posts by people with the same problem here on SO, though it's not all working for me.
What I already tried: using an iFrame. The page then didn't refresh, and the fields wouldn't get cleared.
What's the best thing for me to do?
HTML:
<form class="contact-form" action="form.php" method="post">
<div class="row">
<div class="col-md-6">
<input type="text" name="name" placeholder="Naam" class="form-control" required>
<input type="email" name="email" placeholder="E-mail" class="form-control" required>
<input type="text" name="subject" placeholder="Onderwerp" class="form-control" required>
</div>
<div class="col-md-6">
<textarea type="text" name="message" placeholder="Bericht..." id="message" rows="25" cols="10" class="form-control" required></textarea>
<button type="submit" name="submit" class="btn btn-default submit-btn form_submit">VERSTUUR BERICHT</button>
</div>
</div>
</form>
PHP:
if (isset($_POST["submit"])) {if (isset($_POST["submit"])) {
$nam = $_POST["name"];
$ema = $_POST["email"];
$sub = $_POST["subject"];
$mes = $_POST["message"];
$your_email = "testertje777#gmail.com";
$subject = $sub;
$email_body = $mes;
if (isset($_REQUEST['message'])) {
mail ($your_email, $subject, $email_body, "From: $nam <$ema>");
header ("Location: bomatec.be");
exit();
}
}
Is there a way to make it so that when the user clicks the submit button that the page won't refresh and the fields will be cleared as well?
There are multiple ways this can be achieved:
iframe
Like you mentioned, an <iframe> can be used as the target of the form. Ensure that the iframe has a name attribute defined, then use that value as the target value of the form.
<iframe name="ifr"></iframe>
<form class="contact-form" method="post" action="form.php" target="ifr">
In order to have the form fields cleared with the form is submitted, use a JavaScript handler, like the one below. The <script> tag would be added to the <body> tag (though it could go in the <head> tag but that could slow down page load). When the DOM is ready, it will add a handler for form submission (using document.addEventListener()). When the handler is called, the form fields will be cleared via the call to HTMLFormElement.reset().
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
document.forms[0].addEventListener('submit', function(event) {
event.target.reset();
});
});
</script>
Note that this code presumes there is only one form on the page. If there happen to be multiple then add an id attribute (e.g. <form id="maiForm">) and use that id attribute when accessing the form in JS (e.g. instead of document.forms[0] use document.getElementById('mailForm')).
See a demonstration of this technique in this phpfiddle.
AJAX (Javascript with XMLHttpRequest)
This is another technique similar to the iframe approach but instead it uses the Add a script tag like the one below to the <body> tag. It uses document.addEventListener() to wait for the DOM to be ready and then add an event handler for the form submission. That event handler will do the following:
Prevent the default form submission with Event.preventDefault()
Serialize the form data by instantiating an instance of FormData
Send an asynchronous request using XMLHttpRequest.send() (i.e. AJAX) to the PHP page with the form data from the previous step as the POST data.
Resets the form using HTMLFormElement.reset()
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
document.forms[0].addEventListener('submit', function(event) {
event.preventDefault();
var formData = new FormData(document.forms[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'form.php', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) { //request is done
//request is finished - update DOM accordingly
}
}
xhr.send(formData);
document.forms[0].reset();
});
});
</script>
See it demonstrated in this phpfiddle. Notice that form.php has been replaced by <?php echo $_SERVER['PHP_SELF'];?> because there can only be one page in that fiddle environment. Also the function mail() is disabled there so the lines containing that function have been commented out (and the l replaced by a 1 since the code won't run otherwise).
You can do it by AJAX function, for example via JQuery:
$(".contact-form").submit(function() {
return $.ajax({
type: "POST",
url: "form.php",
data: $(this).serialize()
}).done(function() {
alert("Thanks for your message!"),
$("form.contact-form").each(function() {
this.reset();
});
})
});
Also you can remove action="form.php" from you HTML code.
Please check jsfiddle for full example.

Prevent form from refreshing the page

Hey I am trying to use a form to submit data via JavaScript but it keeps refreshing the page when I don't want it to.
My form is like this:
<form name="myForm" method="post">
<input type="text" name="name"/>
<input type="submit" name="add" value="Add Resource" onclick="insert(); return false;"/>
</form>
My JS function has:
function insert(e){
e.preventDefault();
var name = document.myForm.name;
console.log(name);
}
I was told prevent default is how you stop the default action of the form but it still happens for me. How do I fix it ?
You're not passing in e though. Instead, it would be better to bind to the form with JavaScript rather than using an attribute:
document.querySelector('[name=myForm]').addEventListener('submit', function (e) {
e.preventDefault();
});
You could also bind to the click event of the submit input

Problems with response of the form after upload file

when i receive a response from the server without that is not handle by AJAX i have a problem to catch the data, normally the data goes to the target but that only happens in Chrome, the other browsers open a new tab and insert the response in the new tab, my question is how i can avoid that? i wanna insert on the target, the code below is the code of the page and the javascript that trigger the submit.
Here is the code of the form.
<div>
<form id='uploadFrm' action='/'enctype='multipart/form-data' method='POST' target='frame_trgt'>
<input id='1_inp' name='upfile' type='file' />
<input id='pathFile' type='input' name='path' />
<input id='uploadFile' type='submit' /><br />
</form>
<iframe id='frame_trgt' name='frame_trgt' />
</div>
Here is the code of the JavaScript that handle the upload file.
$('[name=upfile]').change(function(event){
$("#pathFile").attr('value', getData('carpet'));
$("#uploadFile").trigger('click');
});
i believe you just need to close your iframe tag
<iframe id='frame_trgt' name='frame_trgt'></iframe>

Categories

Resources