Ajax - multiple validation - php

I have set up some ajax code to validate multiple fields inside a form using php. The code works like a charm, but I wanna minimize the javascript used.
As you can see at the code below, Im getting the getElements('input') ... that validates all input fields and then getElements('textarea') that validates... ya u know! ;o) Textarea is the last line in the code below and the javascript after that is the same as inpt
I'm validating the input, textarea, selection list, checkbox, etc. in my controller using php, but the code after getting the elements is the EXACT SAME.
So I was thinking that I might could make a switch case or if else with javascript to loop the elements and only write the duplicated javascript once....
Could that be done?
window.addEvent('domready', function(){
$('container').getElements('input').addEvent('keyup', function(e){
//stop the input-tag event
e = new Event(e).stop();
//identify which item was activated
var querystring = this.title;
var value = this.value;
var myXHR = new XHR({
method: 'get',
onSuccess: function(e){
var myString = myXHR.response.text;
var myStringArray = myString.split("###RAWR###");
$(myStringArray[1]).innerHTML = '<em class="checking"> </em>';
setTimeout( ajax , 3500 );
function ajax(){
$(myStringArray[1]).innerHTML = '<em class="'+myStringArray[2]+'">'+myStringArray[0]+'</em>';
}
}
});
myXHR.send('index2.php?option=com_component&task=validate&value='+value, querystring);
});
$('container').getElements('textarea').addEvent('keyup', function(e){

You can put the tagnames in an array loop it and call a function with your validation.
window.addEvent('domready', function(){
var tagNames = ["input", "textarea", "select"];
for (var i = 0; i < tagNames.length; i++)
{
validate(tagNames[i]);
}
});
function validate(tag)
{
$('container').getElements(tag).addEvent('keyup', function(e){
//stop the input-tag event
e = new Event(e).stop();
//identify which item was activated
var querystring = this.title;
var value = this.value;
var myXHR = new XHR({
method: 'get',
onSuccess: function(e){
var myString = myXHR.response.text;
var myStringArray = myString.split("###RAWR###");
$(myStringArray[1]).innerHTML = '<em class="checking"> </em>';
setTimeout( ajax , 3500 );
function ajax(){
$(myStringArray[1]).innerHTML = '<em class="'+myStringArray[2]+'">'+myStringArray[0]+'</em>';
}
}
});
myXHR.send('index2.php?option=com_component&task=validate&value='+value, querystring);
});
}

Related

Hide data in url when using window.open in jquery

i was performed onclick to download pdf in below there is my jQuery code
$("#mlt_voucher").on("click", function () {
var checkedId = [];
var deduction = $('#dynamicmodel-deduction_type').val();
// alert(deduction);
$.each($("input:checkbox[class=chkItem]:checked"), function(){
checkedId.push($(this).attr("id"));
});
window.open('$deductiondown?checkedId='+checkedId+'&deduction='+deduction, '_blank');
});
there is the url look like
http://localhost/fads/admin/master-beneficiary/deductiondown?checkedId=29155,29152&deduction=1
i want hide my data in that url what can i do for that ?
and also i don't want to use that code in below
$("#mlt_voucher").on("click", function () {
var checkedId = [];
var deduction = $('#dynamicmodel-deduction_type').val();
alert(deduction);
$.each($("input:checkbox[class=chkItem]:checked"), function(){
checkedId.push($(this).attr("id"));
});
$.post(
'$deductiondown',
{ checkedId:checkedId,deduction:deduction},
// function(response){
// // console.log(response);
// location.reload();
// }
);
});

External filter form with Datatable

I have a form that I want to send all fields to serverside using Datatables and filter the data.
I found how to send individual parameters using:
url: './demo2/contents/orden/get.php',
type: 'POST',
data: function(d) {
d.comercial = $("#comercial").val();
}
but how can I send the complete form, I assume it can be done using something similar:
url: './demo2/contents/orden/get.php',
type: 'POST',
data: function(d) {
var frm_data = $('#searchFrom').serializeArray();
$.each(frm_data, function(key, val) {
d[val.name] = val.value;
});
}
To get the parameters in get.php I am using
$comercial = $_REQUEST["comercial"];
If anybody needs help with this. I found the solution. You can get the forms post values using the same datatable get file without have to post again.. I wasnt aware of this.
here is the code:
$('#kt_search').on('click', function(e) {
e.preventDefault();
var frm_data = $('#searchFrom').serializeArray();
console.log(frm_data);
$.each(frm_data, function(key, val) {
myData[val.name] = val.value;
});
table.table().draw();
});
If you need to send an array because you have a field with multiple selection, you can use the following. Hope it helps somebody.
$('#kt_search').on('click', function(e) {
e.preventDefault();
var frm_data = $('#searchFrom').serializeArray();
//POST VALUES ARE SENT USING SAME GET FILE NO NEED TO POST AGAIN
var multiple = {};
var i = 0;
$.each(frm_data, function(key, val) {
var str = val.name;
//CHECK IF FIELD NAME FINISHES WITH MULTIPLE
if (str.match("_multiple")){
if (typeof multiple[str] == "undefined") {
multiple[str] = new Array();
i = 0;
}
multiple[str][i] = val.value;
i++;
myData[val.name] = multiple[str];
}else{
myData[val.name] = val.value;
}
});
table.table().draw();
});

ajax request page redirecting

I am loading a form named staff_view.php in main.php through ajax. It's loading fine but when I submit form to staff_post.php it's redirecting to it instead of showing in console, before I add the code for loading form using ajax it was posting fine but after it's redirecting.
Here is my code
$(document).ready(function() {
$('.content_load').load('staff_view.php');
$('ul#nav li a').click(function() {
var page = $(this).attr('href');
$('.content_load').load(page);
$('form.ajax').on('submit', function() {
var that = $(this);
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
});
});
clearAll();
return false;
});
});
function clearAll(){
$("form :input").each(function(){
$(this).val("");
});
}
Because it's a form, and because you wish to submit via AJAX instead of the usual "redirect-to-page" method that forms automatically use, you must suppress the default action.
Change this:
$('form.ajax').on('submit', function(){
var that = $(this);
etc.
to this:
$('form.ajax').on('submit', function(e){ // <=== note the (e)
e.preventDefault(); // <=== e used again here
var that = $(this);
etc.
You need to prevent default action when you click anchor tag, and that is redirects you to the link in your href attribute
$('ul#nav li a').click(function(e){
e.preventDefault();
var page = $(this).attr('href');
$('.content_load').load(page);
// code...
This is what cause your redirection
I could be wrong, but it looks like you might have a race condition to load the page and attach the submit listener. The page might load after the $('form.ajax') bit is executed.
$('.content_load').load(page); // Race condition?
$('form.ajax').on('submit', function() {
One fix would be to move the following code into a completion callback:
$('.content_load').load(page, function() {
$('form.ajax').on('submit', function(e) {
e.preventDefault();
// ...
});
Also, add the e.preventDefault(); to prevent the form from actually submitting.

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();

Other jquery functions NOT working after successful ajax function

EDIT
JQUERY-AJAX REQUEST CODE:
<script type="text/javascript">
$(document).ready(function(){
$(".form").submit( function(e) {
e.preventDefault();
var form = $(this);
var div_add_comment = $(form).parent();
var div_comments = $(div_add_comment).parent();
$.ajax({
type: "POST",
data: $(form).serialize(),
url: "includes/comment.php",
success: function(msg){
$(div_comments).html(msg);
}
});
return false;
});
});
</script>
JQUERY SHOW ALL - COLLAPSE COMMENTS CODE
<script type="text/javascript">
$(document).ready(function(){
$('.see_all').click(function(){
var thisItem = $(this);
thisItem.parent().find('#comment2').slideDown('fast');
thisItem.parent().find('.collapse').css('display','inline-block');
thisItem.css('display','none');
return false;
});
$('.collapse').click(function(){
var thisItem = $(this);
thisItem.parent().find('#comment2').slideUp('fast');
thisItem.css('display','none');
thisItem.parent().find('.see_all').css('display','inline-block');
return false;
})
})
</script>
JQUERY REMOVE DEFAULT VALUE TEXT UPON FOCUS - TEXTAREA
<script type="text/javascript">
$(document).ready(function(){
var Input = $('textarea[name=comment]');
var default_value = Input.val();
$(Input).focus(function() {
if($(this).val() == default_value)
{
$(this).val("");
}
}).blur(function(){
if($(this).val().length == 0)
{
$(this).val(default_value);
}
});
})
</script>
Please let me know if you need anything else, I have the damndest of time copying code and formatting it in these posts.
END EDIT
I am having a weird little problem. I have created a jquery-ajax function to transfer data from a comments section of my page. The page has an instance of this form under each user post. So this page will have X amount of posts with X amount of comments for each posts, like a social network. My ajax request sends, recieves and displays the data perfectly BUT I have two other jquery functions called on elements inside that no longer work after the ajax function returns the html. All the other ones not acted upon by the ajax function STILL WORK. I have the checked and rechecked the response html from the ajax function and it is identical to the html of a standard post-comment instance.
Please let me know what you would like to see or if you have questions.
Thanks, your help is always appreciated!
Be sure to bind the jQuery functions in such a way that the element doesn't have to exist.
$('ul').on('click', 'li', function(){ /* do something */ });
This will execute on LIs that have been added after the binding of the function.
In your case you would want to bind to the parent of the comments section and target the elements that have the click behavior.
$('.comments')
.on('click', '.see_all', function(){...})
.on('click', '.collapse', function(){...})
.on('focus', 'textarea[name=comment]', function(){...})
.on('blur', 'textarea[name=comment]', function(){...})
Try removing the $() from form.
You have this:
var form = $(this);
var div_add_comment = $(form).parent();
var div_comments = $(div_add_comment).parent();
It should be this:
var form = $(this),
div_add_comment = form.parent(),
div_comments = $(div_add_comment).parent();
Since you declared var form = $(this); you don't need to wrap form...how you have it now is the equivalent of $((form))
Not sure if this will fix your problem, but jQuery may be getting hung up on this since you are spawning children from $(this).

Categories