How to stop page reload using async function javascript - javascript

I am working with javascript and right now i am using "async function",Problem is
whenever i click on "complete listing"(button) then page is refreshing,I just want page should not reload after click,How can i stop this,Here is my current code
async function completeListing(elm){
alert("Hello world");
}
<input type="submit" id="nft_forms" name="listing" class="btn btn-primary" value="Complete listing" onclick="completeListing(this)" >

You set the input to submit:
<input type="submit" ...
so submitting the form (i.e. sending it to the server and reloading the page) is what a click should do.
If you don't want that, you have several options:
Use a <button type="button">, which will not trigger the submit. This is the preferred solution if you never want to submit through that button.
Stop the click event from reaching the form by calling event.stopPropagation() in the handler. This is the preferred solution if submission might be cancelled due to a condition specific to the button.
Set a handler on the form that stops submission with event.preventDefault(), which is preferred if submission depends on overall conditions (like validation), no matter what triggered it.

Related

Angular 2: Form submission canceled because the form is not connected

I have a modal that contains a form, when the modal is destroyed I get the following error in the console:
Form submission canceled because the form is not connected
The modal is added to a <modal-placeholder> element which is a direct child to <app-root>, my top level element.
What's the correct way to removing a form from the DOM and getting rid of this error in Angular 2? I currently use componentRef.destroy();
There might be other reasons this occurs but in my case I had a button that was interpreted by the browser as a submit button and hence the form was submitted when the button was clicked causing the error. Adding type="button" fixed the issue. Full element:
<button type="button" (click)="submitForm()">
In the form tag you should write the following:
<form #myForm="ngForm" (ngSubmit)="onSubmit()">
and inside the form you should have submit button:
<button type="submit"></button>
And most importantly, if you have any other buttons in your form you should add type="button" to them. Leaving the default type attribute
(which I think is submit) will cause the warning message.
<button type="button"></button>
So I actually just ran into the exact same problem today except without a modal involved. In my form, I have two buttons. One that submits the form and one that, when clicked, routes back to the previous page.
<button class="btn btn-default" routerLink="/events">Cancel</button>
<button type="submit" class="btn btn-primary">Submit</button>
Clicking on the first button with the routerLink does exactly what its supposed to, but also apparently tries to submit the form as well, and then has to abandon form submission because the page that the form was on is unmounted from the DOM during submission.
This appears to be the exact same thing that is happening to you, except with a modal instead of the entire page.
The problem becomes fixed if you directly specify the type of the second button to be something other than submit.
<button type="button "class="btn btn-default" routerLink="/events">Cancel</button>
So if you are closing the modal via a 'Cancel' button or something of the sort, specifying that button's type, as shown above, should solve your issue.
In the form element you need to define submit method (ngSubmit), something like:
<form id="currency-edit" (ngSubmit)="onSubmit(f.value)" #f="ngForm">
and on the submit button you omit click method, because your form is now connected to the submit method:
<button class="btn btn-success" type="submit">Save</button> The button should be of submit type.
In the code behind component you implement "onSubmit" method, for example something like this:
onSubmit(value: ICurrency) {
...
}
This method is receiving an value object with values from the form fields.
In case that submitting the Form is being accompanied by the component's destroying, the Form submitting fails in race condition with the detaching of the Form from the DOM. Say, we have
submitForm() {
if (this.myForm.invalid) {
return;
}
this.saveData(); // processing Form data
this.abandonForm(); // change route, close modal, partial template ngIf-destroying etc
}
If saveData is async (for example it saves the data via API call) then we may wait for the result:
submitForm() {
this.saveDataAsync().subscribe(
() => this.abandonForm(),
(err) => this.processError(err) // may include abandonForm() call
);
}
If you need to abandon the Form immediately, a zero-delay approach also should work. This guarantees the DOM detachment to be in the next event loop after the Form submission has been called:
submitForm() {
this.saveData();
setTimeout(() => this.abandonForm());
}
This should work regardless of the button type.
I had this problem recently and event.preventDefault() worked for me.
Add it to your click event method.
<button type="submit" (click)="submitForm($event)" mat-raised-button>Save</button>
And:
submitForm(event: Event) {
event.preventDefault();
// ...
}
I resolved the issue by adding the attribute type = "button".
<button type="button" onClick={props.formHandler}>Cancel</button>
I see this in Angular 6, even with no submit buttons at all.
happens when there are multiple forms in the same template.
not sure if there's a solution / what the solution is.
i had this warning, i changed button type "submit" to "button" problem solved.
If you still want to maintain the functionality of the button to be of type "submit", then you should not be using the click event on that button. Instead you should use the ngSubmit event on the form.
Example:
<form (ngSubmit)="destroyComponent()">
<button type="submit">submit</button>
</form>
Maybe you are routing to some other page on your form submission. Use programmatic route navigation, as in the example that follows, rather than passing routerlink into the template:
router.navigate(['/your/router/path'])

What button event should I use to confirm a html form?

Using Javascript, no framework, what button event should I use to confirm form when I wish not redirect? I expect to use either left mouse button or keyboard to confirm the form.
I used this element:
<button type="button" value="1">Save</button>
Using type="submit" with "submit" event is no solution for me because this creates redirection (values the from are lost). So I use type "button".
When I use
document.getElementById("advanced_form").addEventListener("click", saveOptions);
This even "click" is used with mouse. But there is possibility that the user will use keyboard instead mouse to submit form. So I suspect the form would not react to keyboard confirm action. I did not find any event related to button being pressed. So how to solve this problem?
You could still use ´type="submit"´ in combination with ´e.preventDefault();´ to aviod the redirect.
I hope this helped, good luck.
From your clarifying comment:
What happened is when I clicked the button the values which were in the form disapeared and so I understood it that the form was reloaded without any values.
Submitting a form...submits the form. What you get back as a result depends entirely on what the server sends back.
But the values should not disappear, the behaviour which I need is like in a normal Browser Window (WINAPI)
That is normal.
...the page will not clear the values. If I'd want to close the form, I'd close the tab (html page).
That isn't normal. Normal is for the form to go away and be replaced by the result of submitting it.
But you can do that with the submit event, just use event.preventDefault() within the submit event to prevent the form submission:
document.getElementById("the-form").addEventListener("submit", function(event) {
event.preventDefault(); // Prevents the form from being submitted
});
That event will reliably fire whether the user used the mouse, keyboard, or assistive technology to submit the form. The click event on a submit button will not reliably fire when the form is submitted with the keyboard or assistive technology.
You can use submit button, but you need to handle submit action. Try this (with jquery):
<input class="submit_button" type="submit" value="Save" />
<script>
function submit_form(e)
{
if (check_form_submit()) {
// check your data here
$(this).submit();
return;
}
e.preventDefault();
}
$(function() {
$('.submit_button').parents('form').submit(submit_form);
});
</script>
You should still use the submit input type but you need to prevent the default action so that the page doesn't reload.
If you are using jQuery this snippet should help.
$('#my-form').submit(function(ev) {
ev.preventDefault(); // to stop the form from submitting
// Your code here
this.submit(); // If you want to submit at the end
});

Clicking submit button using javascript and Firefox

I guess I have never tried to do this before ... I have a button on a page.
<input type="submit" id="btn" value="Submit">
And a javascript function that includes:
function clickit()
{
alert(document.getElementById('btn').value);
document.getElementById('btn').click();
}
Using Firefox, the button is not clicked - i.e. the form is not submitted. The alert shows, but the form does not get submitted. Why won't Firefox click a button?
Use a div or anything besides a INPUT element if you want to bind the click event to it. If <INPUT> is inside a form body, you might run into weird issues.
If you just need to submit a form with a button I would recommend that you just use a <div> element with a click handler rather than an input. It will give you a little more flexibility. If you do that then you should be able to just select your form and use the submit() API to submit the form.
If you really can't modify the code enough to do this and are having trouble selecting and submitting here is how you will need to do that using both jQuery and DOM.
The jQuery Way:
$("my selector").trigger("click")
You may run into issues around focus if you're running in PhantomJS or you've got a window like a test runner that is not in focus. In this case you can use:
$(<my selector>).triggerHandler(<my event>)
The DOM API way
This will just trigger the event (the equivalent of the first example)
// Create the event
var event = new CustomEvent("name-of-event", { "detail": "Example of an event" });
// Dispatch/Trigger/Fire the event
document.dispatchEvent(event);
You can also simulate a click with the actual DOM method
var button = document.getElementById('my-button');
button.click();
Why won't Firefox click a button?
I seem to recall that early versions of Firefox didn't allow calling of listeners that way for security reasons. However, I think those reasons have been addressed in other ways and now you should be able to call the click handler directly. The following submits the form in Firefox 34:
<form onsubmit="alert('submitted!!')">
<input name="foo" value="foo">
<input type="submit" id="aa">
</form>
<br>
<button onclick="document.getElementById('aa').click();">Click the submit button</button>
The form's submit listener is called and the form is submitted, so calling the submit button's click method is doing what it's supposed to.
This method doesn't work for all listeners though, click is a special case, see W3C DOM Level 3 Events Specification, §3.5 Activation triggers and behavior.

Did button actually click?

I have some javascript that ends up programatically clicking on a button:
document.getElementById("myButton").click();
This in turn results in the form being submitted using a function call:
<form onsubmit="submit_this_form(this);return false;" action="" method="POST">
It seems that a good percentage of the time either the actual button click is not going through or the form is not being submitted. I think the button click is going through and I know the code is being called because I have a counter embedded and I can see it is executing.
My question is...is there an event or a way to verify that the form actually posted? By the way, I don't have control of the HTML code so I can't change the tag content.
<form onsubmit="submit_this_form(this);return false;" action="" method="POST">
return false after submit_this_form() essentially stops the form from actually submitting. I believe if you change it to:
<form onsubmit="submit_this_form(this);" action="" method="POST">
It should work as you want.
Using return false after an event handler will essentially 'hijack' the default functionality. Basically, whatever your event handler function script does replaces the default behavior, which in this case, is submitting the form data to the server.
I don't think you can verify that form is actually where submitted.
But you can submit it by hand via XMLHTTPRequest and check for server responce.
This way you will be sure thet form is submitted. And you can have an event (your custom event) that says about form submission if you need to...
BTW do not forget to prevent forms default submit if you go AJAX way.
Check jquery.form plugin to make a fast rollout of AJAX form submission and look is it what you want or not.
Good luck!

How to tell onBlur not to hide the submit button when clicked?

My blur event hides the submit button; but doing that seems to cancel the submit event. I only want to hide when the submit itself wasn't clicked. How can I determine if the focus was lost due to the submit, or due to just wandering off elsewhere?
<form action="" method="post">
<textarea id="message" name="message"></textarea>
<input type="submit" id="share" value="Share">
</form>
...
$('textarea').blur(function(){
$('#share').hide()
})
$('textarea').focus(function(){
$('#share').show()
})
Setting a timeout to allow the submit event to fire before coming back to the blur seems a bit hacky to me. Can't we do better than that? Can I tell the blur not to block other events? or search the dom for a pending submit event? or ... ?
Solution
for today is based on the ticked answer, but simpler. Use jquery's "fadeOut" routine to
delay the hidden status of the submit button until after the submit event has fired, and
make the user feel like their submission is being handled
.
$('textarea').blur(function(){
$('#share').fadeOut()
})
$('textarea').focus(function(){
$('#share').fadeIn()
})
It's indirect, and not really what I was looking for, but it seems clear that direct manipulation of the event queue - such as writing onBlur to say "if they did not click submit then hide the submit button" - is perhaps not technically possible.
This is one option, though a bit hacky using jQuery .queue() and .clearQueue() to set an animation queue and instantly clear it before anything happens:
$(function() {
$("#message").blur(function() {
$("#share").delay(100).fadeOut();
});
$("#share").click(function() {
$(this).clearQueue();
});
});
Note: Requires jQuery 1.4+
If you hide the Submit button, the submit will cancel.
Try making it completely transparent instead.
EDIT: For example:
$('#share').css({ opacity: 0, position: 'absolute' });

Categories

Resources