I have a form with a submit button and it works fine, but I now have a user request to make the form get saved (posted to save action) if a link on the page is clicked and the form is "dirty".
I've got the logic in place by having an isDirty JavaScript variable, now I would like to post the form from the JavaScript function when it is dirty.
My form declaration is as follows:
<form id="formSmart" action="<%= ResolveUrl("~/SmartForm/Proceed") %>"
method="post" enctype="multipart/form-data">
and my JavaScript is:
function checkLink() {
if (isDirty) {
$("#formSmart").submit();
}
}
The proceed action doesn't get called, yet when I click the submit button on the form it works fine. What am I doing wrong in the JavaScript?
Note: The call to checkLink() works fine, the ultimate problem is that $("#formSmart").submit(); is not posting to the Proceed action.
You have the correct way of submitting the form based on what you have posted and the names match up.
Are you sure you are calling checkLink and is isDirty equal to true?
Put and alert('Test'); right before you submit and in the if scope.
EDIT: To hookup your event you need to do the following:
$('#yourLinkID').click(checkLink(); return false;);
Note the return false which will cause your link to not execute a navigate. If you want the link to navigate, you can just remove that part.
Sounds like the requirement is that 'a link on the page is clicked'.
Perhaps attach this event to all the <a> tags on the page.
$(document).ready(function() {
// all <a> tags get the checkLink attached to them
$("a").click(checkLink());
});
your problem is that the browser navigate before the page performs your submit.
the solution is suspending the navigation till you save the form.
The UGLY solution:
you could do it buy saving the clicked url at a hidden field,
returning false to stop the navigation,
and after submit check for a value there and if it exists do navigation
A better solution:
post the form via ajax and after the ajax call completes(no need to check for success or error) perform the navigation(to make it really easy just use ajaxForm ajaxForm plugin)
the only problem with this solution is if the link has target="_blank" because then you have to use window.open which might be blocked by popup blockers
you can play with a simple jsbin sample i prepared showing this
this example post some values to an older version of this page + navigate to google, open fiddler and see that it first post and then navigate.
If you went to the jsbin page stop reading here
here is the Html:
<form id="formSmart" action="http://jsbin.com/oletu4/edit" method="post">
<input type="text" name="someLie" />
<input type="text" name="someLie2" />
<input type="submit" value="submit" />
<a id="lnkNavOut" href="http://www.google.com">www.google.com</a>
here is the JS:
$(document).ready(function(){
$("#lnkNavOut").click(function(){
var jqFormSmart = $("#formSmart");
//check here if the form is dirty and needs to be saved
var jqClickedLink = $(this);
$.ajax({
url: jqFormSmart.attr("action"),
type: "POST",
data:jqFormSmart.serialize(),
complete:function(){
location = jqClickedLink.attr("href");
}
});
return false;//stop navigation
});
});
Related
I am working on a django project and I want to add a like button to the posts.
Just like a regular like button (https://i.stack.imgur.com/FJWH3.jpg)
this is my template:
<form action="{% url 'like' post.id %}" method="GET" name="liked" class="l-form">
{% csrf_token %}
<button style="display: inline;" class="like__btn">
<i class="like__icon fa fa-heart" style="display: inline;"></i>
</button>
</form>
<script>
$('.like__btn').on('click', function(){
$('.like__icon.fa-heart.fa').toggleClass("liked");
});
</script>
All I want to do this, when user clicks on a heart icon, it will submit the form. But also change the icon color to red. (liked class is basically, color:red)
When I click on the button it submits the form, increases the like count, but then it refreshes the page so my heart icon doesn't stay red.
If I add
type="button"
this time it doesn't refresh the page, change the color of the icon but doesn't submit the form.
I tried to do another button to submit the form and make it hidden but whenever the form is submitted it refreshes the page and goes back to the white heart.
Also tried to return false; in jquery but it doesn't submit the form again.
I am stuck for hours, so any advice would be great! I am not sure if I should do it in a different way or it would work this way.
As mentioned by #wmorrell, you need to submit an AJAX request. Here is a simplified example of how you can achieve that:
$(document).ready(function() {
var like_counter = 0;
$(".like__btn").click(function() {
like_counter++;
var reference = this;
var postpk = $(this).data('postpk');
var userpk = $(this).data('userpk');
$.ajax({
url: "//", #put your relevant url here
data: {like_counter: like_counter},
success: function(result) {
$(reference).addClass("liked");
},
})
});
})
And in your html you have something like:
Like
You want to do an AJAX request, so the "form" goes through the submit process, but there is no page load clearing out the current page state. This would involve setting a click handler on the button, which you already have. Then, in addition to setting the class on the button, use the JQuery $.ajax() family of functions to simulate a form submission.
When you submit a form using HTML it will refresh the page. One way around this is to submit the form using jQuery instead.
https://code.tutsplus.com/tutorials/submit-a-form-without-page-refresh-using-jquery--net-59
Keep in mind here that as soon as the user reloads or revisits the page, the heart will no longer be 'liked' and won't be shown as red.
I'm trying to use PureCSS forms in my web app and I can't figure out how to retain the nifty form validation while stopping the page reload.
I know I can stop the page reload using onsubmit="return false;"
Then I can use AJAX to post the form data using onClick="PostSettings();", where PostSettings() is my javascript function containing the AJAX request. I also have to include event.preventDefault(); at the top of that function to stop the reload.
Unfortunately these steps which stop the reload also stop the nice in-built PureCSS validation.
Is there a way to retain that without triggering the page reload or will I need to make my own validation in the javascript?
FYI, here's the html:
<button type="submit" class="pure-button pure-input-1-2 pure-button-primary"
id="save-simulation-button" onClick="PostSettings();"
onsubmit="return false;">
<i class="fa fa-save"></i> Submit Simulation Parameters
</button>
Use 'return false' instead of event.preventDefault() inside the 'PostSettings()' method.
Thanks for your replies Lucas and Vignesh -- they didn't quite solve the problem, but they got me thinking and I developed a solution:
In the html I had to add a return here: onClick="return PostSettings();"
Then in the javascript I return true or false depending on whether or not the form passes validation, which I have to check:
function PostSettings() {
//event.preventDefault(); <<- commented out per Vigneshs suggestion
var name = $("#simulation-name").val(); // jquery to get form values
var description = $("#description").val();
// Code to validate form: name and description cannot be blank
if (name === "" || description === "") {
console.log("name or description fields cannot be blank");
return true; // <<- returning true allows PureCSS validation to continue
}
// Code passed validation so post the data...
// POST code omitted for brevity
return false; // <<- returning false stops the page reload
}
So in summary, returning true allows the PureCSS form validation to take place as per normal (and there's no page reload because the form hasn't passed validation). And when the form passes validation I return false to stop the page reload -- this also stops any other default events of the PureCSS form, but that's okay because I manually checked if it validated in the javascript.
Hope this helps others who want to accomplish this in the future!
You only need a onsubmit="return MyValidFunction();" in the Form tag and nothing else in the "submit" button
When the form is not ok PureCSS make the validation with his message, When All is ok call your "MyValidFunction()" function
function MyFunction() {
/// your Ajax Code here
return false;
}
<form class="pure-form" onsubmit="return PostSettings();">
<input id="form_url" type="url" class="pure-input-1-3">
<button type="submit" class="pure-button pure-input-1-1">OK</button>
</form>
I had the same issue. Adding onsubmit="event.stopPropagation()" in the form tag prevents the refresh when the form is valid, and retains validation flags when it's invalid.
I`m trying to read the value from an input and fill it in one empty div.However , the value is being read but when I click the button submit , the value appears for like 0.2 seconds on the empty div , and then , disappears ... any suggestions why?
HTML :
<div id="vuvedenaSuma">
</div>
<form action="">
<input type="text" id="suma" required="required" placeholder="Въведи сума" name="Suma" />
<button id="submit">Submit!</button>
</form>
Javascript:
function valueRead(){
var vuvedenaSuma = document.getElementById('suma').value;
document.getElementById('vuvedenaSuma').innerHTML = vuvedenaSuma;
}
document.getElementById('submit').addEventListener('click',valueRead);
I want to make it withe eventListener , not onclick attribute on the button.
Your form is being submitted right after the execution of the function.
You can prevent the default event(form submission) to be called with event.preventDefault() like this:
function valueRead(e){
var vuvedenaSuma = document.getElementById('suma').value;
document.getElementById('vuvedenaSuma').innerHTML = vuvedenaSuma;
e.preventDefault();
}
https://jsfiddle.net/ez0qchyq/
Your event is firing, then the page is likely reloading because of the form firing. Try using
event.preventDefault()
and it will prevent the form from submitting.
Edit: Also, the comment below me is absolutely correct. Remember to pass the event into the function.
The default way that a form "submits" is to send a new page request to the server, using the given inputs as parameters. From there, a serverside language like PHP might save them. Often, this would churn out an "Operation successful!" page or similar.
In your case, your form's action is blank, meaning it will "submit" to the page it's on. Since your page is pretty basic, it will reload without any of the sent information appearing in it.
As John Kossa suggested, you could intercept this by adding an argument, let's say, "evt", to the parentheses of the valueRead function, and then calling evt.preventDefault().
When you click the button then you send the form and the page is automatically refreshed. To prevent this behavior try this solution
function valueRead(e){
e.preventDefault();
var vuvedenaSuma = document.getElementById('suma').value;
document.getElementById('vuvedenaSuma').innerHTML = vuvedenaSuma;
}
Also, you might want to use the event listener on submit:
document.getElementById('formName').addEventListener('submit', valueRead);
Basically mysimplewebform.php form submits when the toggle is clicked, as opposed to after the form is loaded, used by user and SUBMITTED via submit button at form. Obviously I need to have form operate functionally; user fills it out, and clicks submit. I simply used AJAX to bring in the form on the template page. Now everytime toggle button is clicked 'Form is submitted with empty values' and then appears in the toggle. Making it pretty useless at this point, I have been struggling with this forever. I think this is a matter of toggling the data: below --
$(document).ready(function() {
$('#toggle3').click(function(){
var tog = $('.toggle');
$.ajax({
type: 'POST',
url: '/mysimplewebform.php',
data: $(this).closest('form').serialize(), // This was a recent suggestion
success: function (fields){
tog.html(fields);
tog.slideToggle(1000);
}
});
});
});
Branched out from: How to send external form POST data through AJAX
Ok, so you want to display an html form when a user clicks a button? In that case you can use the simplified jquery load method:
$('#yourbutton').click(function(){
$('#somediv').load('/mysimplewebform.php');
});
I know this doesnt handle your toggle requirement, but i dont think that is where you are having issues.
Now onto the php. I dont know exactly what should be in mysimplewebform so heres an example
if(isset($_POST['fname'])){
//we have a post request, lets process it
echo 'hello'.$_POST['fname'];
}?>
<form action="absolute/path/to/mysimplewebform.php" method="post" id="mysimplewebform">
<input type="text" name="fname" placeholder="Enter Name">
<input type="submit" value="submit">
</form>
Notice the action is an absolute path to the file, because a relative path will be wrong if the form is loaded into another page via ajax.
Now when this form is submitted, the browser will be redirected to mysimplewebform.php.
I expect you want to stay on the same page, in which case you could submit the form via ajax:
$('#mysimplewebform').submit(function(ev){
ev.preventDefault();//stop normal redirecting submit
$.post( $(this).attr('action'), $(this).serialize(), function(data){
$('#somediv').html(data)
});
This replaces the whole form in the dom with the output, so the hello message would be displayed.
All of the above is an attempt to help you understand where you have been going wrong in your attempts. It is not the best solution to your overall problem - i would separate the html form and processing into seperate files for a start, but it should be familiar to you.
I'm having a problem with submitting a form and Javascript confirmation. Basically, the following Javascript is called when the "submit" button is pressed.
function confirmation() {
var answer = confirm("Are you sure you wish to edit?")
if (answer)
{
window.location = "#editform2";
}
}
However, when I hit the cancel instead of ok, the Javascript executes correctly, because I watch the address bar and it doesn't update to #editform2. The form, however, still submits. It seems to refresh the page. Here's the relevant parts from the form:
//Form is encoded in PHP
<form method=\"post\">
//Form is in here
<input type=\"submit\" value=\"Edit\" onclick=\"confirmation()\">
So the form doesn't know where it's going, it just refreshes the page, and the page happens to be the processor as well. So it's processing even though I clicked cancel and the Javascript should keep it on the same page. Besides moving the processing to a different page, what are my solutions?
It works like this because it's a sumbit button and the form is submitted in every case. Assign an id to the form and change the input type:
<form method="post" id="formid">
<input type="button" value="Edit" onclick="confirmation()">
and call this function on click:
function confirmation() {
var answer = confirm("Are you sure you wish to edit?")
if (answer)
{
document.getElementById("formid").submit();
}
}
Don't use the onclick event of the submit button, use the onsubmit event of your form:
document.forms[0].onsubmit = function () {
return confirm("Are you sure you wish to edit?");
}
You may want to add a id attribute to your form to identify it.
Keeping event binding on JavaScript code; not on inline attributes on your HTML, makes your code more maintanable and easy to debug.
try:
return answer;
at the end of the function and make sure the onclick method returns this. Like so:
<input type="submit" value="Edit" onclick="return confirmation()">
This would make the function return false and have the form not be posted.