jQuery consolidate code into one function - javascript

Is it possible to consolidate the two sections of code below. If you look at each section you will notice they are almost identical. I have another 3 or 4 sections of code which are also identical. I'm wondering if there's a neater way for me to use the same code?
$("#agencies").on("click", ".applyClick", function(event) {
event.stopPropagation();
event.preventDefault();
var target = $(this);
var currentParent = $(this).closest('tr');
var id = currentParent.attr('id');
var items = $("input,select,textarea", currentParent);
var strData = items.serialize() + '&id=' + id;
$.post("agencies.php", strData, function(data) {
var data = $.parseJSON(data);
if(data.redirect_location){
window.location = data.redirect_location;
}
else{
var type = data.type;
var result = $.map(data, function(val,index) {
if(index != 'type'){
var str = val;
}
return str;
}).join("<br>");
if(type == 'error'){
alert(result);
}
else{
$("div#messages").html('<div class="'+ type +'-message">' + result + '</div>').slideDown("slow");
closeRow('quit', target);
}
}
});
});
$("#builders").on("click", ".applyClick", function(event) {
event.stopPropagation();
event.preventDefault();
var target = $(this);
var currentParent = $(this).closest('tr');
var id = currentParent.attr('id');
var items = $("input,select,textarea", currentParent);
var strData = items.serialize() + '&id=' + id;
$.post("builders.php", strData, function(data) {
var data = $.parseJSON(data);
if(data.redirect_location){
window.location = data.redirect_location;
}
else{
var type = data.type;
var result = $.map(data, function(val,index) {
if(index != 'type'){
var str = val;
}
return str;
}).join("<br>");
if(type == 'error'){
alert(result);
}
else{
$("div#messages").html('<div class="'+ type +'-message">' + result + '</div>').slideDown("slow");
closeRow('quit', target);
}
}
});
});

I will recomend to add attribute to your buttons like this
<input type="button" data-url="agencies" id="agencies" />
<input type="button" data-url="builders.php" id="builders" />
and same code like this
$("#agencies, #builders").on("click", ".applyClick", function(event) {
var url = $(this).attr('data-url');
....
$.post(url, strData, function(data) {
...
...
});

This question is in the margins of Code Review and SO.
The only difference between the two handlers appears to be the .post URL, and that appears to be derivable from the ID of the click target.
So do a little string handling to build the URL and attach your modified function as click handler to both elements :
$("#agencies, #builders").on("click", ".applyClick", function(event) {
...
$.post(this.id + '.php', strData, function(data) {
...
}

Related

making a ajax live load

can anyone know how can I make this as an ajax live load?
unfortunately, I have limited acknowledge about javascript/jquery/ajax
simply I want to load the search result on ajax live load
This is my javascript code to load the data but it will refresh the page
I want to not refresh the page and load the data on live load
<script type="text/javascript">
function get_url() {
var urlPrefix = 'https://example.com/home/courses?'
var urlSuffix = "";
var slectedCategory = "";
var selectedLevel = "";
var selectedIelts = "";
var selectedCountry = "";
var selectedPtype = "";
var selectedDtype = "";
var selectedLanguage = "";
var selectedRating = "";
//Get selected category
$('.categories:checked').each(function() {
selectedCategory = $(this).attr('value');
});
// Get selected countries
if($("#country-search-value-unique").val() != 'all'){
selectedCountry = $("#country-search-value-unique").val();
};
if($("#ielts-search-value-unique").val() != 'all'){
selectedIelts = $("#ielts-search-value-unique").val();
};
if($("#ptype-search-value-unique").val() != 'all'){
selectedPtype = $("#ptype-search-value-unique").val();
};
if($("#dtype-search-value-unique").val() != 'all'){
selectedDtype = $("#dtype-search-value-unique").val();
};
if($("#level-search-value-unique").val() != 'all'){
selectedLevel = $("#level-search-value-unique").val();
};
if($("#price-search-value-unique").val() != 'all'){
selectedPrice = $("#price-search-value-unique").val();
};
// Get selected difficulty Level
$('.languages:checked').each(function() {
selectedLanguage = $(this).attr('value');
});
// Get selected rating
$('.ratings:checked').each(function() {
selectedRating = $(this).attr('value');
});
urlSuffix = "category="+selectedCategory+"&&level="+selectedLevel+"&&ielts="+selectedIelts+"&&country="+selectedCountry+"&&ptype="+selectedPtype+"&&dtype="+selectedDtype+"&&language="+selectedLanguage+"&&rating="+selectedRating;
var url = urlPrefix+urlSuffix;
return url;
}
function filter() {
var url = get_url();
window.location.replace(url);
//console.log(url);
}
function toggleLayout(layout) {
$.ajax({
type : 'POST',
url : 'https://example.com/home/set_layout_to_session',
data : {layout : layout},
success : function(response){
location.reload();
}
});
}
function showToggle(elem, selector) {
$('.'+selector).slideToggle(20);
if($(elem).text() === "show_more")
{
$(elem).text('show_less');
}
else
{
$(elem).text('show_more');
}
}
$(document).on('click', '.catparent-label', function(e) {
$(this).next('ul').fadeIn(); $('li.has').removeClass('is-active'); $('ul.tree').addClass('has-selection'); $('ul.tree').find("label").removeClass('is-seleted'); $(this).closest('li').addClass('is-active'); $(this).addClass('is-seleted'); $('ul.tree').find("input[type='checkbox']"); $(this).closest('li').find(".catparent"); $('.BackListDisciplines').show(); StudyFilter(); e.stopPropagation()
}
); $(document).on('click', '.subcat-label', function(e) {
$('ul.tree').find("label").removeClass('is-seleted'); $('ul.tree').find("input[type='checkbox']").prop('checked', !1); $(this).addClass('is-seleted'); $(this).closest('li').find(".subcat"); StudyFilter(); e.stopPropagation()
}
); $(document).on('click', '.BackListDisciplines', function(e) {
$('li.has').removeClass('is-active'); $('ul.tree').find("label").removeClass('is-seleted'); $('ul.tree').removeClass('has-selection'); $('.tree ul').hide(); $('ul.tree').find("input[type='checkbox']"); $('.BackListDisciplines').hide(); StudyFilter()
}
);
</script>

If condition not working in server

If condition to equal two string values in javascript is not working in server, but its working in localhost. Given below is my code.
var res_id = $(this).attr('name');
var fld_id = $(this).attr('id');
var ans = $('#'+fld_id).attr('value');
//var mod_id = $('#mod_id').attr('value');
//alert(typeof(ans));
$.post("multiple_check_answer.php", { resid: res_id, answ: ans}, function(data){
//alert(typeof data);
if(ans==data)
{
//alert(data);
$('#span_'+res_id+'_'+ans).css({'color':'green', 'font-weight':'bold'});
}
else
{
$('#span_'+res_id+'_'+ans).css({'color':'red', 'font-weight':'bold'});
$('#span_'+res_id+'_'+data).css({'color':'green', 'font-weight':'bold'});
}
});
for ex. if ans and data values are A but its showing red color.
Here is the new code which is working fine. Changed data value to integer.
$("input[type=radio]").click(function(){
var res_id = $(this).attr('name');
var fld_id = $(this).attr('id');
var ans = $('#'+fld_id).attr('value');
//var mod_id = $('#mod_id').attr('value');
//alert(ans);
$.post("multiple_check_answer.php", { resid: res_id, answ: ans}, function(data){
//alert(data);
if(data==1)
{
//alert(data);
$('#span_'+res_id+'_'+ans).css({'color':'green', 'font-weight':'bold'});
//$('#dis_msg'+res_id).html('<strong style="color:green">Your Answer is Correct</strong>');
}
else
{
$('#span_'+res_id+'_'+ans).css({'color':'red', 'font-weight':'bold'});
$('#span_'+res_id+'_'+data).css({'color':'green', 'font-weight':'bold'});
//$('#dis_msg'+res_id).html('<strong style="color:red">Your Answer is In-Correct</strong>');
}
});
});

jquery click event for child div not working in plugin

I'm trying to add a click event on each row. On click I need to be able to grab the name (ex. Jeremy) and place in the top div, replacing the question marks. My click event only works on id="data" but not the child divs. I have my code here on codepen as well http://codepen.io/rrschweitzer/pen/GrRyLg?editors=0110. Any help is much appreciated!!
This is my html:
<div id="interview-test">
<div class="top-bars">
<div id="secret">???</div>
<button id="clear">Clear</button>
</div>
<div id="data"></div>
</div>
This is my Jquery:
(function($) {
$.fn.interviewTest = function() {
var self = this;
var testData = null;
var url = "https://private-f3b4b-interview2.apiary-mock.com/data";
// create rows
self.createRow = function(data) {
var theRow = $('<div>').addClass('rows')
.append($('<div>').addClass('image-container')
.append($('<img>').addClass('picture').attr('src', data.image)))
.append($('<div>').addClass('name').append($('<h1>').html(data.name)))
.append(self.getDate(data.timestamp))
return theRow;
}
self.getDate = function(date) {
var date = date.slice(0,-3)
var newdate = new Date(date * 1000)
var year = newdate.getFullYear();
var month = newdate.getMonth();
var day = newdate.getDay()
var formattedDate = month + '/' + day + '/' + year
return formattedDate;
}
// api call
$.ajax({
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ');
},
url: url,
success: function(data, status) {
var dataObject = data;
var i = 0;
var testData = [];
for(var key in dataObject) {
testData[i] = dataObject[key]
i++;
}
// console.log(testData);
self.createDataList(testData, i);
}
})
self.createDataList = function(data, size) {
var rows = $(self).find('#data');
if (size != 0) {
$.each(data, function(key, value) {
// console.log(value)
rows.append(self.createRow(value))
})
}
}
// event listeners
$(self).find('.rows').on('click', function(e) {
var current = $(e.currentTarget);
console.log(current);
// if(current)
})
}}(jQuery))$('#interview-test').interviewTest();
You need to add your event listeners after elements (rows) are created:
(function($) {
$.fn.interviewTest = function() {
var self = this;
var testData = null;
var url = "https://private-f3b4b-interview2.apiary-mock.com/data";
// create rows
self.createRow = function(data) {
var theRow = $('<div>').addClass('rows')
.append($('<div>').addClass('image-container')
.append($('<img>').addClass('picture').attr('src', data.image)))
.append($('<div>').addClass('name').append($('<h1>').html(data.name)))
.append(self.getDate(data.timestamp))
return theRow;
}
self.getDate = function(date) {
var date = date.slice(0,-3)
var newdate = new Date(date * 1000)
var year = newdate.getFullYear();
var month = newdate.getMonth();
var day = newdate.getDay()
var formattedDate = month + '/' + day + '/' + year
return formattedDate;
}
// api call
$.ajax({
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ');
},
url: url,
success: function(data, status) {
var dataObject = data;
var i = 0;
var testData = [];
for(var key in dataObject) {
testData[i] = dataObject[key]
i++;
}
// console.log(testData);
self.createDataList(testData, i);
}
})
self.createDataList = function(data, size) {
var rows = $(self).find('#data');
if (size != 0) {
$.each(data, function(key, value) {
// console.log(value)
rows.append(self.createRow(value))
});
self.addEventListeners()
}
}
self.addEventListeners() {
// event listeners
$(self).find('.rows').on('click', function(e) {
var current = $(e.currentTarget);
console.log(current);
// if(current)
})
}
}}(jQuery))$('#interview-test').interviewTest();
you can use event delegation for this to attach the event with the parent element which will fire for all the matching selector child elements.
$(self).on('click', ".rows",function(e) {
var current = $(this);
if(current)
{
var name = current.find(".name").text();
$("#secret").text(name);
}
})
code pen : http://codepen.io/anon/pen/EZxRwM?editors=0110
Your demo doesn't work however looking at your code you are trying to look for self.find('.rows') before the ajax has completed and the rows have been created
You either need to delegate the event or wait until rows are added in the ajax success

Javascript trim whitespace on click

I have an email form field. On click, it executes this javascript ...
$(document).on('click', '#add_delegate', function() {
RegistrationHelper.added_delegate = true;
// var button = $(event.target);
var button = $(this);
var uri = button.data('url');
if (typeof uri === 'undefined') {
return false;
}
var input = $('#email_search');
var data = {email:input.val()};
data.text().replace(/ /g,'');
var spinner = $('#delegate_add_spinner');
spinner.css({display:'inline-block'});
$.ajax({type:'POST', url: uri, data:data}).success(function(card) {
var html = $(card);
var data_id = html.attr('data-id');
var existing_elem = $('.mini_addresscard[data-id=' + data_id + ']');
if (existing_elem.length < 1) {
input.popover('hide');
// this is in a seperate timeout because IE8 is so damn stupid; it crashes if run directly
setTimeout(function () {
$('#address_cards').append(html);
var last_card = $('#address_cards div.mini_addresscard').last();
//last_card.get(0).innerHTML = card;
// html.attr("id", 'sdklfjaklsdjf');
last_card.css({display:'none'}).show('blind');
}, 10);
} else {
var background = existing_elem.css('background');
existing_elem.css({'background':'#FFFFAC'});
existing_elem.animate({
'background-color':'#EBEDF1'
}, {
complete: function() {
existing_elem.css({background:background});
}
});
// var border_color = existing_elem.css('border-color');
// existing_elem.css({'border-color':'#EFF038'});
// existing_elem.animate({'border-color':border_color});
}
}).complete(function(data) {
spinner.hide();
}).error(function(data) {
var input = $('#email_search');
input.popover("destroy");
var error = 'Please try again later'; //incase something crazy happens
if(data.status == "422"){
error = 'You cannot add yourself as a supervisor.';
}
if(data.status == "404" ){
error = 'Could not find anyone with that email address.';
}
add_popover(input, error);
input.popover('show');
});
return false;
});
My goal is to trim the whitespace before the AJAX request
So as you can see in the code above I added the line
data.text().replace(/ /g,'');
... but now it renders that button useless. In other words the button does nothing when clicked.
Since you're using jQuery, why not make use of .trim():
This:
var data = {email:input.val()};
data.text().replace(/ /g,'');
Becomes:
var data = {email:$.trim(input.val())};
The trim supposed to remove the spaces at beginning and end of the input:
var input = $('#email_search').val();
input = input.replace(/^\s+/, '').replace(/\s+$/, '');

Illegal invocation when using toArray

I don't have very much to my code but I seem to be getting Illegal invocation with my order variable - works fine and shows in console.log if I comment it out
$('body').on("click", "#brands_by_category_submit_btn", function (e) {
e.preventDefault();
var self = $(this);
var order = $(".order").toArray();
var id = $("#manID").data("id");
var brand_name = $("#brand_name").data("id");
var data = grabData(true);
if(data.length)
{
var data_array = {
id : id,
brand_name : brand_name,
cat_id : data,
order : order,
state : 1
};
var url = $("#brands_by_category_submit_btn").data("url");
//console.log(data_array);
ajaxCall(url, data_array);
alert("Categories Updated");
}
});
AjaxCall:
function ajaxCall(url, data_array, div_id, callback_fn) {
return $.ajax({
type:'POST',
url:url,
beforeSend: function(){
$("#" + div_id).html("<img src='http://www.#.co.nz/files/large/ajax-loader.gif' alt='Loading..' title='Loading..'/>");
},
data:data_array,
complete:function (data) {
$("#" + div_id).html(data.responseText);
if(callback_fn != null)
{
eval(callback_fn + '()');
}
}
});
}
Your problem is that you're converting an array of HTML elements into POST data which simply isn't possible. You should instead loop through your elements and grab their .text() property:
var self = $(this);
var order = []; //or "new Array()". Whatever you prefer for readability
$(".order").each(function() {
order.push($(this).text());
});
var id = $("#manID").data("id");
var brand_name = $("#brand_name").data("id");
var data = grabData(true);

Categories

Resources