Can't cancel default action on ajax form submit - php

I have a form and a piece of javascript code to create AJAX forms. The weird thing is when i submit my form in Internet Explorer the only thing that displays is [object Object]. The form works fine in Google Chrome. Here is my code:
Form header:
<form id="page-details-form" class="ajax-form" name="page-details-form" method="POST" action="/pages/save/1">
Javascript listener:
<script>
$(function(){
$(document).on("submit",".ajax-form",function(e){
if (window.event) {
window.event.returnValue = false;
}
e.preventDefault ? e.preventDefault() : e.returnValue = false;
$('.form-message').remove();
if($('#onSubmitJsEval').html() && $('#onSubmitJsEval').html().length > 0)
{
eval($('#onSubmitJsEval').html());
}
var submitBtnValue = $('#submitBtn').html();
var formId = $(this).attr('id');
var postData = $(this).serializeArray();
$('#submitBtn') .html('<img src="images/ajax-loader.gif" />');
$('p.has-error') .remove();
$('div.has-error') .removeClass('has-error');
$.post($(this).attr('action'), postData, function(jsonResponse)
{
var jsonObject = jQuery.parseJSON(jsonResponse);
if(jsonObject.success == true)
{
$('<div class="<?=MESSAGE_SUCCESS_CLASS?>"><?=MESSAGE_SUCCESS_PREFIX?>'+jsonObject.message+'</div>' ).insertBefore( "#" + formId + " h2" );
if(jsonObject.insertedId > 0)
{
var stringPath = window.location.pathname.substr(window.location.pathname.length - 1);
document.location.href = window.location.pathname + ((stringPath != "/") ? "/" : "") + jsonObject.insertedId;
}
}
else
{
$('<div class="<?=MESSAGE_ERROR_CLASS?>"><?=MESSAGE_ERROR_PREFIX?>'+jsonObject.message+'</div>' ).insertBefore( "#" + formId + " h2" );
$.each(jsonObject.errors, function(index, value){
$('[name='+index+']').parent().addClass('has-error');
$('[name='+index+']').after('<p class="has-error help-block">'+value+'</p>');
})
}
$('#submitBtn').html(submitBtnValue);
});
});
});
</script>
I tried several options besides the current option:
if (e.preventDefault) e.preventDefault();
e.returnValue = false
e.returnValue = false after e.preventDefault
Does anyone have a idea? If i need to publish more code please let me know. I can post all the code if you want.
Many thanks!

You will need a combination of e.preventDefault() and return false, with handling code inbetween.
$(document).on("submit", ".ajax-form", function(e) {
e.preventDefault();
//Do your stuff here
return false;
});

Related

Submit form after click

Having Following form validation through jQuery:
$("#Login").submit(function( event ) {
var url = 'ajax/';
var data = {};
$("input").each(function() {
data[$(this).attr('name')] = $(this).val();
});
$.post(url,data,function( resp ) {
$("#formLoginErrorMessage").children().remove();
if(resp === " ")
{
console.log("Empty");
return; // The form should submit
} else if (typeof resp === "object") {
console.log(resp);
} else{
$("#formLoginErrorMessage").addClass("alert-danger");
$("#formLoginErrorMessage").append("<li>" + resp + "</li>");
console.log(resp);
}
},'json');
event.preventDefault();
});
This script is checking some errors and when resp is empty form should submit. But return from if where resp is checked doesn't seem to make form submit.
You can call the submit() method in the if condition
$("#Login").submit(function (event) {
var form = this;
var url = 'ajax/';
var data = {};
$('input').each(function () {
data[$(this).attr('name')] = $(this).val();
});
$.post(url, data, function (resp) {
$("#formLoginErrorMessage").children().remove();
if (resp === " ") {
form.submit();
console.log("Empty");
return; // The form should submit
} else if (typeof resp === "object") {
console.log(resp);
} else {
$("#formLoginErrorMessage").addClass("alert-danger");
$("#formLoginErrorMessage").append("<li>" + resp + "</li>");
console.log(resp);
}
}, 'json');
event.preventDefault();
});
What you seem to be confused about are closures
$( "#Login" ).submit(function( event ) {
// main submit handling function starts here
...
$.post(url,data,function(resp){
// inner response handling function starts here
if(resp === " "){
console.log("Empty");
return; //This returns to jQuery internals somewhere inside $.post
} ...
},'json');
// stops form from submitting
event.preventDefault();
});
I added a couple of comments to help you get a better visual of the scope.
First thing first, you should never rely on client-side validation. It can be overtaken without exceptions. If for some reason you insist on having it this way you can use some outer scope variable to determine whether validation has passed or not, but then you have to use $form.submit() instead of return to actually submit the form.

Thickbox not getting values of textbox using Jquery

I used thickbox components in Joomla. I am submitting form using jQuery ajax but jQuery not getting values after click on submit buttons. I used
and created script.js file containing :
jQuery(document).ready(function(){
jQuery('.wp_btn').click(function() {
var id = $j(this).attr('id');
var url = $j(this).attr('value');
if (document.cookie.indexOf('visited=true') == -1) {
var fifteenDays = 1000*60*60*24*15;
var expires = new Date((new Date()).valueOf() + fifteenDays);
document.cookie = "visited=true;expires=" + expires.toUTCString();
jQuery("#dwnlnk").val(url);
TB_show('', '/#TB_inline?KeepThis=true&id=9876asdvfrty54321&height=250&width=350&inlineId=mypopup&caption=Subscription', '');
}else{
window.location = url;
}
});
//
jQuery(document).on('submit', '#subscription',function(){
return false;
});
jQuery(document).on('click', '#btnSubmit',function(){
var url = jQuery('#dwnlnk').val();
var txtname = $j('input[name=txtname]').val();
var txtemail = $j('input[name=txtemail]').val();
jQuery.ajax({
type: 'POST',
url: 'whitepapers/',
data: jQuery('#frmsubscription').serialize(),
success: function(data) {
alert(data);
//if(data == 'true') {
window.location = url;
//}
}
});
});//end click
});
I already tried document.getElementById('txtname').value but its not getting value of textbox. When I entered static value then its getting value.
You have to use jQuery or $ to select an element.
Try this
var txtname = jQuery('input[name="txtname"]').val();
var txtemail = jQuery('input[name="txtemail"]').val();
OR
var txtname = $('input[name="txtname"]').val();
var txtemail = $('input[name="txtemail"]').val();

Form Validation, problems with passing of argument and page redirection

So I'm creating this form validator with PHP and jQuery.
The PHP code will check through the form and then return an array with fields that contain errors. Example: {"email":1,"password":1}
But now I have concerns regarding if no errors were to be found. The problem here is that I've included "return false" in the end of the code to prevent page redirection. I've read that this is bad code practice but not found another way that works as intended.
The second problem is how to pass the o-array into the $('input').each function. Right now it will say that all forms are valid since nothing was passed. If I use $.post instead of $.ajax this scope problem doesn't appear for some reason.
jQuery:
$(function() {
$('#register').submit(function() {
var url = $(this).attr('action');
var data = $(this).serialize();
$.ajax({
type: 'GET',
url: url,
data: data,
success: function(o) {
console.log(o);
$('input').each(function() {
var msgId = o[$(this).attr('name')];
console.log(o[$(this).attr('name')]);
if (msgId > 0) {
$('#listError').css('visibility', 'visible');
$('#listError').append('<li>' + $(this).nextAll('span.msg').eq(msgId - 1).text() + '</li>');
$(this).addClass('invalid');
} else if (msgId != 0) {
$(this).addClass('valid');
}
$('#listError').append('</ul>');
})
}
}, 'json');
return false;
});
});
Fist, why are you submitting a form when you really don't want to?! Use a button instead and make the AJAX request from its click handler.
$('#registerButton').click(function() {
var form = $('#register')
var data = form.serialize();
$.ajax(...);
});
"The second problem is how to pass the o-array into the $('input').each"
What is the problem here? If you have an each() inside a success callback, you can use the data parameter that is passed to the callback (or o in your case) in that each().
Try this
$(function() {
$('#submit_button_id').click(function() {
var url = $(this).attr('action');
var data = $(this).serialize();
var ret = true;
$.ajax({
type: 'GET',
url: url,
async: false,
data: data,
success: function(o) {
console.log(o);
$('input').each(function() {
var msgId = o[$(this).attr('name')];
console.log(o[$(this).attr('name')]);
if (msgId > 0)
ret = false;
$('#listError').css('visibility', 'visible');
$('#listError').append('<li>' + $(this).nextAll('span.msg').eq(msgId - 1).text() + '</li>');
$(this).addClass('invalid');
} else if (msgId != 0) {
$(this).addClass('valid');
}
$('#listError').append('</ul>');
})
}
}, 'json');
if(ret==true){
$('#register').submit();
}
});
});

how to disable submit button on click and re-enable on the response in jquery forms plugin

i want to be able to make the submit button in jquery form plugin disabled and then when the response is retrieved, it should become enable. i am trying thru the code below but as soon as in the onlick event i disabled the button it somehow stops the submission. although i am able to change the class of the button.
what am i doing wrong?
code is like this:
function timing(){
d=Math.round(new Date().getTime() / 1000);
$('input[name=timedate]').val(d);
var btn1 = $('#post_global');
btn1.val('posting');
btn1.removeClass('t_s').addClass('t_sDisabled');
btn1.prop('disabled',true);
}
(function() {
$('form').ajaxForm({
dataType: 'json',
beforeSubmit: validate,
success: processResponse
});
})();
function processResponse(data) {
document.getElementById('upfile').value = "";
document.getElementById('fileinfo').innerHTML = "";
document.getElementById('txt1').value="post anything...";
var status = $('#status');
if(data.errors == ""){
status.hide().html(data.htmlResponse).fadeIn(1000);
} else{
alert(data.errors);
}
var btn2 = $('#post_global');
btn2.val('post');
btn2.removeClass('t_sDisabled').addClass('t_s');
btn2.prop('disabled',false);
}
This is the answer that I think you're looking for. If you want more, just comment what you want below:
$("#btn2").click(function() {
$('#btn2').attr("disabled", true);
//Do the request here
$('#btn2').attr("disabled", false);}
Possibly this?
function timing(){
d=Math.round(new Date().getTime() / 1000);
$('input[name=timedate]').val(d);
var btn1 = $('#post_global');
btn1.val('posting');
$('#btn2').attr("disabled", true);
}
(function() {
$('form').ajaxForm({
dataType: 'json',
beforeSubmit: validate,
success: processResponse
});
})();
function processResponse(data) {
document.getElementById('upfile').value = "";
document.getElementById('fileinfo').innerHTML = "";
document.getElementById('txt1').value="post anything...";
var status = $('#status');
if(data.errors == ""){
status.hide().html(data.htmlResponse).fadeIn(1000);
} else{
alert(data.errors);
}
var btn2 = $('#post_global');
btn2.val('post');
$('#btn2').attr("disabled", false);
}

Jquery set enter key textarea in My Code

I have an Jquery submit textarea, now I want to set textarea submit without button submit. Just using enter key.
<textarea id="ctextarea"></textarea>
Here it's the JS :
$('.comment_button').live("click",function()
{
var ID = $(this).attr("id");
var uid = $("#uid").val();
var comment= $("#ctextarea"+ID).val();
var dataString = 'comment='+ comment + '&msg_id=' + ID + '&uid=' + uid;
if(comment=='')
{
$('#ctextarea').html("").fadeIn('slow');
$("#ctextarea"+ID).focus();
}
else if (!$.trim($("#ctextarea"+ID).val()))
{
$("#ctextarea"+ID).focus();
}
else
{
$.ajax({
type: "POST",
url: "comment_ajax.php",
data: dataString,
cache: false,
success: function(html){
$("#commentload"+ID).append(html);
$("#ctextarea"+ID).val('');
$("#ctextarea"+ID).focus();
}
});
}
return false;
});
I already search the tutorials and found, but I confused where can I put the code in My JS code.
Someone can give the idea ?
Thanks for helps.
$('#ctextarea').on('keyup', function(e){
if(e.which == 13 || e.keyCode == 13){
//enter key pressed..
}
});
You can subscribe to a keydown/keyup event and submit the form inside the event handler:
var KEY_ENTER = 13;
$('#ctextarea').keyup(function (event) {
if (event.keyCode === KEY_ENTER) {
$('form').submit();
// Or perform any necessary ajax calls here
}
});

Categories