Stopping Form to be submitted - javascript

I have a form which on submit should see if the text area has no text or the place holder text.
iif it does it shouldn't submit it. something like validation. I am not able to stop the form submission.
$(document).ready(function () {
var options = {
target: '.user-status',
// target element(s) to be updated with server response
beforeSubmit: showRequest,
// pre-submit callback
success: showResponse,
// post-submit callback
// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
};
$('#updateStatus').submit(function () {
$(this).ajaxSubmit(options);
return false; // prevent a new request
});
function showRequest(formData, jqForm, options) {
var textbox = $('#StatusMessageMessage').val();
if ((textbox == '') || (textbox == "What have you been eating ?")) {
alert(text);
return false;
} else {
$('#StatusMessageMessage').attr('disabled', true);
}
}
function showResponse(responseText, statusText, xhr, $form) {
$('#StatusMessageMessage').attr('disabled', false);
}
statusMEssagebox();
});
function statusMEssagebox() {
var textholder = $('#StatusMessageMessage').val();
$('#StatusMessageMessage').focus(function () {
if ($(this).val() == textholder) $(this).val("");
$(this).animate({
"height": "48px",
}, "fast");
$('.share').slideDown("fast");
$(this).TextAreaExpander(48, 75);
});
$('#StatusMessageMessage').blur(function () {
if ($(this).val() == "") {
$(this).val(textholder);
$('.share').slideUp("fast");
$(this).animate({
"height": "18px",
}, "fast");
}
});
}

I see that you are using the jquery form plugin to ajaxify your form. There's an example in the documentation illustrating how to achieve this in an elegant way. You don't need to subscribe for the .submit event of the form and manually submit it using .ajaxSubmmit. You could simply try this:
$(function() {
$('#updateStatus').ajaxForm({
beforeSubmit: function(formData, jqForm, options) {
var value = $('#StatusMessageMessage').val();
if (value == '' || value == 'What have you been eating ?') {
return false;
}
}
});
});

You are using equality operator rather than comparison.
This:
if ((textbox = '') || (textbox = "What have you been eating ?")) {
Problem -----^
Should be:
if (textbox == '' || textbox == "What have you been eating ?") {
You may also want to see how the submit form via Ajax using jQuery:
http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/

Related

How could I stop a form submit in this case?

My intention is to check some conditions before submit is done or stop it and show an alert if the results of that condition are false. I need to ask a function localized in another PHP document using POST.
The next case I'm going to show, the alert is showed correctly when "result != 1", but when I test the opposite case "result == 1", the submit doesnt work:
$('body').on("submit","#idForm",function(event) {
event.preventDefault();
$.post( 'php_file_rute.php', {action:'functionName'})
.done(function(result) {
if (result == 1) {
if(functionNameInSameJSPage()){
return true;
}else{
return false;
}
} else {
alert('error');
return false;
}
});
});
I tried in another way, putting event.preventDefault behind every "Return false" but when "result != 1" it shows the alert but do the submit anyways. It happens in every condition (submit doesnt stop).
$('body').on("submit","#formProyecto",function(event) {
$.post( 'php_file_rute.php', {action:'functionName'})
.done(function(result) {
if (result == 1) {
if(functionNameInSameJSPage()){
return true;
}else{
return false;
event.preventDefault();
}
} else {
alert("error");
event.preventDefault();
return false;
}
});
});
As you can see, my goal is to stop the submit if "result != 1" and show an alert or do the submit if all conditions are ok.
Any idea?
Thanks.
The issue you have is that you cannot return anything from an asynchronous function - which your AJAX request is.
To solve this you need to use preventDefault() to stop the form submit event through jQuery, then raise another native submit event if the AJAX request returns a valid result. This second submit event will not be handled by jQuery and will submit the form as you require. Try this:
$(document).on("submit", "#idForm", function(e) {
e.preventDefault();
var form = this;
$.post('php_file_rute.php', {
action: 'functionName'
}).done(function(result) {
if (result === 1) {
if (functionNameInSameJSPage()) {
form.submit();
}
} else {
alert('error');
}
});
});
This is assuming that functionNameInSameJSPage() is not an async function. If it is then you'll need to use the callback pattern there too.
This is a bit of a tricky one but you can kind of get it to work by doing:
$('body').on("submit","#idForm",function(event) {
event.preventDefault();
$.post( 'php_file_rute.php', {action:'functionName'})
.done(function(result) {
if (result == 1) {
if(functionNameInSameJSPage()){
$('#idForm').trigger("submit.force"); //Trigger submit again but under a different name
}
} else {
alert('error');
}
});
});
$('body').on("submit.force","#idForm", function () { return true; }); //Passthrough
The idea is to retrigger the event but ensure you don't call the same handler.
There's a proof of concept at https://jsfiddle.net/2kbmcpa4/ (there's no actual ajax happening but the promise simulates that, note this example won't work in IE)
Steps to solve the issue :
On actual form submit just block the event and make the rest call.
Based on response again dynamically resubmit by setting the allowSubmit flag.
Because flag is set on second submit, it doesn't prevent the form from submission. Reset the allowSubmit flag.
(function() {
var allowSubmit = false;
$('body').on("submit", "#idForm", function(event) {
var that = this;
if (!allowSubmit) {
event.preventDefault();
$.post('php_file_rute.php', {
action: 'functionName'
}).done(function(result) {
if (result == 1) {
if (functionNameInSameJSPage()) {
allowSubmit = true; // set the flag so next submit will not go though this flow
that.submit(); // dynamically trigger submit
}
} else {
alert('error');
}
});
} else {
allowSubmit = false; // reset the flag
}
});
})();

How to reload a particular div in which input tag is there on press of enter

I have a search box at the top of page that makes an ajax call when a user hits the adjacent button. I am trying to update the input tag so that when a user hit the 'enter' key, the appropriate JavaScript takes place without reloading the page. without using form
$('#Searchbar').bind("enterkey", function (e) {
$("#Searchbar").load('Search(1);');
e.preventDefault();
});
$('#Searchbar').keyup(function (event) {
if (event.keyCode === 10 || event.keyCode === 13) {
$(this).trigger("enterKey");
event.preventDefault();
}
});
}
$('#Searchbar').on("enterkey", function(e) {
//
search('whatever your search string might be', function(result) {
// get the result and put in the resultcontainer
$('.resultContainer').html(result);
});
e.preventDefault();
});
$('#Searchbar').keyup(function(event) {
if (event.keyCode === 10 || event.keyCode === 13) {
$(this).trigger("enterKey");
event.preventDefault();
}
});
function search(data, callback) {
//Do an ajax call and call the callback on succes
//Check for proper syntax in jquery documentation
$.post({
'data': data,
'url': your search url,
success: function(result) {
callback(result);
}
});
}

How to continuously check the value of an input using jquery?

I have an input that is empty after page load, and if a user suddenly fill a value on it the value of the two inputs on the if condition should change to.
My problem is when I fill an input, the if condition result doesn't changed in real time.
script:
$(document).ready(function(){
var countTimerEmailName = setInterval(
function ()
{
emailName();
}, 500);
function emailName(){
if($('#emailCodeResult').val() != '' || $('#email').val() == ''){
clearInterval(countTimerEmailName);
}
$.ajax({
url:"view.php",
type:"GET",
data: { term : $('#email').val() },
dataType:"JSON",
success: function(result) {
}
});
};
});
Fire your function on change
$('#inputA, #inputB').change(function(){
if($('#inputA').val() != '' || $('#inputB').val() == '') {
alert("True");
}else{
alert("False");
}
})
You can use keyup like this:
$('#textboxID').on( 'keyup', function () {
//write your code here
});
For touch devices as rzr siad keyup won't occur.
You can write a function that is called every, say 1 sec or whatever, like this:
t1=window.setInterval(function(){foo()},1000);
function foo()
{
// write function definition here
}
or use blur as others suggested, if the you want to check value only after the user is done with that textbox and moves to next field.
var fieldcheck;
$(function() {
$("#input").focus(function() {
fieldcheck = setInterval(function() {
var innerValue = $("#input").val();
if (innerValue == "") {
// Your code
} else {
// Your code
}
}, 100);
});
$("#input").blur(function() {
clearInterval(fieldcheck);
});
});

Ajax Sending HTTP Request Twice?

I am making A ajax login form great progress so far thanks to A few users on stack flow so far.
Now when I check all the fields out if it responds to enter being pressed it is working fine except when I tab to the submit button it is submitting the data twice according to the Chrome networking tab.
I think it is executing the .click function aswill as the .keycode function.
How can i say in the code if keycode enter is false and I click the button execute the function or if its true don't execute the .click function.
$(document).ready(function () {
$('#field').keyup(function (e) {
if(e.keyCode == 13) {
//If enter is pressed vailidate the form
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: {
method: 'fetch'
},
success: function (data) {
$('.chat .messages').html(data);
}
});
};
});
$('#submit').click(function () {
alert('Do something here this is just a test');
});
});
just add preventDefault and return false to the keyup function like that:
$('#field').keyup(function (e) {
if(e.keyCode == 13) {
//If enter is pressed vailidate the form
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: {
method: 'fetch'
},
success: function (data) {
$('.chat .messages').html(data);
}
});
return false;
};
});
This will prevent the form from submitting when users press ENTER.

Send only one Ajax post request with keydown() - jQuery

So here is my situation:
I have a bunch of DOM elements in a class ".editable" with the contentEditable attribute attached to them.
For each element I instantiate an Ajax POST with keydown(), but before the ajax request is sent, I check to see if the keydown() gives me a TAB or an ENTER key, and if so then the ajax POST succeeds.
The issue I am having right now is that if the TAB key or the ENTER key is held down, I am ending up sending multiple Ajax POSTs. How would I go about stopping this?
NOTE: I don't want to detach the event with .off() because I want those events to still exist after the ajax POST is done.
Any help or recommendations would be much appreciated!
(function($, window, document) {
/* Namespace */
$.fn.SaveEditable = function() {
var settings = {
context: null,
position: null,
content: "(empty)",
element: "(empty)",
data_id: "(empty)"
};
var s, keyCode;
function init(e, options) {
s = $.extend({}, settings, options);
keyCode = e.keyCode || e.which;
//If Enter or Tab key is pressed
if(keyCode == 9 || keyCode == 13) {
e.preventDefault();
s.context.blur();
sendAjax();
}
} //End init
function sendAjax() {
$.ajax({
url: 'save.php',
type: 'POST',
data: { user_id: <?=$user_id;?>, sort_id: <?=$currentSort;?>, element: s.element, data_id: s.data_id, content: s.content },
success: function (data) {
if(data) {
var obj = jQuery.parseJSON(data);
//Do something with obj
}
$(".ajax-status")
.addClass("success")
.html("Updated content successfully");
},
error: function() {
$(".ajax-status")
.addClass("error")
.html("An error has occurred. Please try again.");
}
});
} //End sendAjax
/* Initilize */
return this.each(function(i, domEl) {
$(this).on({
keydown: function(e) {
init(e, {
context: $(this),
position: i,
content: $(this).text(),
element: $(this).data('element'),
data_id: $(this).data('id')
});
}
});
});
};
})(jQuery, window, document);
Then it is called like so:
$('.editable').SaveEditable();
Here's an example of preventing an XHR request if it's still pending
$(function(){
var xhr;
$("#my-input").keydown(function(){
if (!xhr || xhr.readyState === 4) {
xhr = $.ajax({...});
}
});
});
Hm, how about using keyup event?
As said in jQuery docs:
The keyup event is sent to an element when the user releases a key on
the keyboard.
UPDATE: In order to fix element focus you can leave keydown event with:
keydown: function(e) {
e.preventDefault();
if ((e.keyCode || e.which) == 9) {
return false;
}
}
function init(e, options) {
var check = true;
s = $.extend({}, settings, options);
keyCode = e.keyCode || e.which;
//If Enter or Tab key is pressed
if(keyCode == 9 || keyCode == 13) {
e.preventDefault();
s.context.blur();
if(check)
sendAjax();
check = false;
}
} //END init
On key up set check back to true.

Categories