message to be displayed for incomplete forms in php - javascript

I have a form where in user will enter all of its data to contact us . Now if user fills half of the form and lives in middle I want to ask him whether he really want to live this page .Is it possible? my form submission is done using ajax post method

You are looking for the beforeunload event (https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload). Here is a quick example:
window.onbeforeunload = function(){return "Are you sure?";};
It would probably be ideal to detect partial user input and only add the event listener when some input has been entered. You will also want to remove the dialog when input is completed, or the forum is submitted.

you can place validation function prior to ajax call and consider validation's return value to conclude either submit the form or display message using Confirm() function of javascript. onclick of "yes" on confirmation box you can fire ajax call, below is example of confirmation box in javascript.
if (confirm('Are you sure you want to leave this page?')) {
// leave the page
} else {
// do nothing
}

Related

Disabling a submit button while still allowing a PHP script to run when the form is submitted

I have a simple acceptance form that has a single button that the user clicks.
On form submit, I have a php script that makes a command line call to a python script that adds records to my database.
All works great besides one thing:
I don't want the user to be able to click the button more than once.
If I disable the button using javascript, my if (isset($_POST['submit'])) statement doesn't evaluate to true and then my php doesn't run
If I call a javascript function within the php script, the user still has an opportunity to click the button multiple times before the php script calls the function to disable the button. This allows them to make multiple records in my db.
My idea was to have my python script, which is the one adding records, first check if a record with the same information already exists in the db and only create a new one if not. My concern is that if the user clicks the submit button multiple times, it could be that multiple php will execute multiple calls and the second one will check if a record is already created before the first call creates a new record.
In other words, maybe the php calls will work at the same time (asyncronously?) and checking the database won't cover for another call creating a record at the same time. Is this a valid concern?
Are there other ideas of how I could disable or hide my button but still have my php script run?
Thank you.
For future viewers, the workaround I ended up using is based on what Teemu said in the comments below.
Before adding a new record from the form submission to the db, I checked if a record already existed with that information. If not, I added a record, if so the button click did nothing. As Teemu mentioned, this check would be necessary anyway to cover for multiple submissions that could be posted even without the button on the page.
This is what I call a "workaround" and not an answer because the user can still click the submit button multiple times but only the first click has an effect.
The button then hides itself after the php has finished running.
All you need is that the disabled is set after the submission is sent. You can achieve that using a setTimeout with zero delay:
$('.myForm').submit(function () {
setTimeout(() => {
$(this).find('[type=submit]').prop('disabled', true)
}, 0)
})
Then, the following will happen:
Form submission event is fired because user clicked the button or pressed Enter
Browser is calling your submit handler
You are "arming" your timeout
Browser is submitting the form to the server (with the submit button's value)
Your timeout fires immediately afterwards, disabling the button
Note that I used a submit handler on the form instead of a click handler on the button because the form may be submitted by pressing Enter while focus is on a form field too, not only by clicking the button. Yet due to how form submission works, disabling the button will also prevent submission by Enter.
I recently had a similar situation where I was getting a double-click 'bounce' sometimes. Here's two ways I dealt with it:
1) Simply disable the button, send the AJAX data to PHP and restore the button on success
$("#save_button").click(function (e) {
e.preventDefault();
$(this).attr("disabled", true);
var settings = $('form').serialize();
console.log("settings are ", settings);
$.post("data/ajax.php", settings, function (data) {
data = JSON.parse(data);
console.log("data back from save is ", data);
$("#save_button").removeAttr("disabled");
})
});
2) create a 'nobounce' function (it does basically the same thing, but on a timer. It is a bit simpler to use as it only requires setting the class 'nobounce' on any button you want to disable, though as it is on a timer, it isn't as accurate to enable the button when the post is done.
$('.nobounce').click(function () {
$(this).attr("disabled", true);
setTimeout(function () {
$('.nobounce').removeAttr("disabled");
}, 3000);
});
These are both jquery methods - keeping the form on the page. From your description it seems maybe you are doing a form submit through PHP (please, if this isn't the answer you need, put up some code you are using so this can be more clear!). If you are submitting through PHP, then some of the comments to the original question are extremely valid.
Hope this helps - again, if not, put up some code and you can get much more direct help.

Yii and Javascript form submission

I'm using Yii as a PHP framework for my site. Additionally, my site uses some js/jquery like, say, a jQuery UI Dialog widget (except for those dialogs, the rest of the code is pure normal html form components and jQuery code for the event handlers).
In the Yii side, I use CForms to build my forms from specifications file.
When I test if the form was submitted, I must do it for a certain button. This is not only forced, but I also take advantage of it.
if ($myCFormInstance->submitted('approve')) {
//process approval code
} else if ($myCFormInstance->submitted('reject')) {
//process rejection code
}
The actual problem I have is a bit conceptual one, since -fortunately- I know what's going on with my code and -again, fortunately- know the problem root:
Somewhere in My code I intercept the submit button's click event:
$(function(){
$(".critical-action").click(function(e){
var form = $(this).closest("form");
e.preventDefault();
e.stopImmediatePropagation();
confirmDialog("¿Continuar?", "#critical-action-dialog", function(){
form.submit();
});
});
});
Say the .critical-action classed elements are always a submit button in a form.
The intention of the code: cancel the form submission, and perform it only if the user -in the dialog- clicks the "Yes, Continue" (i.e. confirming the action) button.
This code works as expected, and have no problems at a javascript level BUT -and here goes my issue- when doing form.submit(), the button is not sent as part of the form. This is obvious: I'm sending the form without specifying any button. In the case of Approve and Reject, which have two buttons, the example explains itself: if the form.submit() call could send their buttons ¿which of them should send?.
Question: So, since form.submit() doesn't send any button, but I actually need buttons ¿how can I send the form "with the corresponding button" -i.e. a button I choose to specify, which should correspond to this in the click handler function context- automatically via javascript? The button NEEDS to be identified by Yii in order to process the form (specially with the Approve and Reject case).
If you added a hidden input to the form, you can modify the input value with jQuery before you submit the form, like this:
$("#inputID").val('approve');
If you want to set the value to the value of the clicked button via $(this).val(), be aware of the issue that could result in an IE browser, explain here. The second answer (by postpostmodern) has a solution to this issue.

Catching & re-calling event in custom confirmation box in javascript

I'm building a custom confirmation popup which comes when ever user want to navigate from page without saving any detail. & I'm not able to find a right way to do this ?
Basically I have decided to put a function on window.beforeunload = func(e) event and use
e.preventDefault(); this syntax to prevent the redirect , actually the occurrence of event e. Now is there any way to re-fire the same event(It could be page redirect/ submit), If use clicks on the 'Ok' button.
You cannot use event.preventDefault() in window.onbeforeunload. You can only return dialogue for the onbeforeunload() function to give to the user.
https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload

Keeping a user from clicking 'submit', before the form is valid

I have a web form that uses a lot of JavaScript and ajax to determine if each field is valid. It gives warning messages on the fly to help the user know when there's a problem. I even use the "disable" feature on my submit button until everything is up to snuff. But here's the problem: All the event handling happens using the onblur feature. but when the last field is filled out, the validation doesn't happen till the user clicks away from that field. but why would they? there's nothing left to do on the page but click submit, which they can't do until they click somewhere else, anywhere else, first (to set off the validation event). I'm trying to find a way around this. There has to be a way where they don't have to make that extra click. it just doesn't seem professional. Is there a standard way around this? Can the validation event be triggered each time the user types an individual letter?
The form node has an onsubmit event that will fire when the user tries to submit the form. You can use this to validate all of the form fields and decide whether to let the user submit the form. The general implementation is this:
<form onsubmit="return validateForm()">
...
</form>
And in your JavaScript function, you have to return true if the user can continue submitting the form, or false to cancel the user's request before the form is submitted.
(In Psuedo-code):
function validateForm(){
if(formIsOkay){
return true;
}else{
return false;
}
}
You can validate each field using onkeyup, and withhold your user notification to the onblur method so it doesn't get annoying. If all fields are valid at the onkeyup, enable the submit button.
Given the limitations of {onChange, onKeyup, blur, etc} when it comes to handling copy/pasted or other edge cases I would probably add a timer to poll every 500ms or so and enable/disable the submit button:
window.setInterval(checkEnableSubmit, 500);
function checkEnableSubmit(){
if(validateForm()){
// enable submit button
}
}
function validateForm(){
if(formIsOkay){
return true;
}
return false;
}
I'd still call validateForm() on the button click to avoid users invalidating data and submitting before the timer is called. Server side validation is a given but I'd like to avoid the bad submit if possible.

JavaScript work before submitting ASP.NET MVC form

I have an ASP.NET MVC view with a Beginform, that specifies an action and controller to hit on submit. But on submit I want to call a service using jQuery to get some data and then submit those data with the form.
Currently I have a submit button on the form where the onclick event of the button calls the JavaScript method. Depending of what result I get from the method I want the form to be submitted to the specified action.
Now I can't get this to work. Is it the right way to do this or should I instead make a post using jQuery? I think it would be nice to use what I have already specified as action/controller in the form.
I think the best way is to use event 'submit' on form, because users can want to submit form by pressing Enter in some fields. Guess, it is possible to change some input values during this event,
jQuery('form#myform').submit(function(e){
//....
if (somevar == false)
{
// stop submitting form
e.preventDefault();
}
else
{
jQuery('input#hiddeninput').val('somevalue');
}
})
The solution is add on submit event to form tag
onsubmit="return onSubmitClick(this);"
function onSubmitClick(item) {
console.log(item);
return false;
}
it's work well. GL ! HF !
I think it would be better to perform the task of querying an external web service in a controller action. This way you would always submit the form to the same controller action which will query the service and based on the results would either render a view or redirect to some other action.

Categories