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+$/, '');
Related
I am trying to port a C++ program to WASM using emscripten.
The compilation process has been mastered, but so far with the presentation, which is bad ... I have
problem:
Uncaught ReferenceError: request is not defined
request.onload = function() {
Here is my script:
<script type='text/javascript'>
request.onload = function() {
var bytes = request.response;
fetch('hello.wasm').then(response =>
response.arrayBuffer()
).then(bytes =>
WebAssembly.instantiate(bytes, importObject)
).then(results => {
// Do something with the results!
console.log(results);
});
};
var statusElement = document.getElementById('status');
var progressElement = document.getElementById('progress');
var spinnerElement = document.getElementById('spinner');
var Module = {
preRun: [],
postRun: [],
print: (function() {
var element = document.getElementById('output');
if (element) element.value = ''; // clear browser cache
return function(text) {
if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
// These replacements are necessary if you render to raw HTML
//text = text.replace(/&/g, "&");
//text = text.replace(/</g, "<");
//text = text.replace(/>/g, ">");
//text = text.replace('\n', '<br>', 'g');
console.log(text);
if (element) {
element.value += text + "\n";
element.scrollTop = element.scrollHeight; // focus on bottom
}
};
})(),
canvas: (function() {
var canvas = document.getElementById('canvas');
// As a default initial behavior, pop up an alert when webgl context is lost. To make your
// application robust, you may want to override this behavior before shipping!
// See http://www.khronos.org/registry/webgl/specs/latest/1.0/#5.15.2
canvas.addEventListener("webglcontextlost", function(e) { alert('WebGL context lost. You will need to reload the page.'); e.preventDefault(); }, false);
return canvas;
})(),
setStatus: function(text) {
if (!Module.setStatus.last) Module.setStatus.last = { time: Date.now(), text: '' };
if (text === Module.setStatus.last.text) return;
var m = text.match(/([^(]+)\((\d+(\.\d+)?)\/(\d+)\)/);
var now = Date.now();
if (m && now - Module.setStatus.last.time < 30) return; // if this is a progress update, skip it if too soon
Module.setStatus.last.time = now;
Module.setStatus.last.text = text;
if (m) {
text = m[1];
progressElement.value = parseInt(m[2])*100;
progressElement.max = parseInt(m[4])*100;
progressElement.hidden = false;
spinnerElement.hidden = false;
} else {
progressElement.value = null;
progressElement.max = null;
progressElement.hidden = true;
if (!text) spinnerElement.style.display = 'none';
}
statusElement.innerHTML = text;
},
totalDependencies: 0,
monitorRunDependencies: function(left) {
this.totalDependencies = Math.max(this.totalDependencies, left);
Module.setStatus(left ? 'Preparing... (' + (this.totalDependencies-left) + '/' + this.totalDependencies + ')' : 'All downloads complete.');
}
};
Module.setStatus('Downloading...');
window.onerror = function(event) {
// TODO: do not warn on ok events like simulating an infinite loop or exitStatus
Module.setStatus('Exception thrown, see JavaScript console');
spinnerElement.style.display = 'none';
Module.setStatus = function(text) {
if (text) Module.printErr('[post-exception status] ' + text);
};
};
</script>
(updated: right code) here is my source of testing site:
https://www.dropbox.com/sh/elgdplx8xmvp51g/AAC-M0oCrA0_rgWZfrRvMt8na?dl=0 look at hello.html
Unfortunately request is not a "standard variable of connection" and is not special in any way. What you probably want is window.onload which is a global event handler available on the window object.
window is a special variable and does have the onload event handler available.
Take a look at the documentation for onload
<script type='text/javascript'>
window.onload = function() {
var bytes = request.response;
fetch('hello.wasm').then(response =>
response.arrayBuffer()
).then(bytes =>
WebAssembly.instantiate(bytes, importObject)
).then(results => {
// Do something with the results!
console.log(results);
});
};
// Rest of your code ...
Finally a have successfuly build the program and my script now looking just only.
<script src=./a.out.js>
I have update files on my dropbox-link to test project folder for more info. https://www.dropbox.com/sh/elgdplx8xmvp51g/AAC-M0oCrA0_rgWZfrRvMt8na?dl=0
In two words it separate script for two parts in the ending of html page
1st is
<script type='text/javascript'>
var statusElement = document.getElementById('status');
var progressElement = document.getElementById('progress');
var spinnerElement = document.getElementById('spinner');
var Module = {
preRun: [],
postRun: [],
print: (function() {
var element = document.getElementById('output');
if (element) element.value = ''; // clear browser cache
return function(text) {
if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
// These replacements are necessary if you render to raw HTML
//text = text.replace(/&/g, "&");
//text = text.replace(/</g, "<");
//text = text.replace(/>/g, ">");
//text = text.replace('\n', '<br>', 'g');
console.log(text);
if (element) {
element.value += text + "\n";
element.scrollTop = element.scrollHeight; // focus on bottom
}
};
})(),
printErr: function(text) {
if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
if (0) { // XXX disabled for safety typeof dump == 'function') {
dump(text + '\n'); // fast, straight to the real console
} else {
console.error(text);
}
},
canvas: (function() {
var canvas = document.getElementById('canvas');
// As a default initial behavior, pop up an alert when webgl context is lost. To make your
// application robust, you may want to override this behavior before shipping!
// See http://www.khronos.org/registry/webgl/specs/latest/1.0/#5.15.2
canvas.addEventListener("webglcontextlost", function(e) { alert('WebGL context lost. You will need to reload the page.'); e.preventDefault(); }, false);
return canvas;
})(),
setStatus: function(text) {
if (!Module.setStatus.last) Module.setStatus.last = { time: Date.now(), text: '' };
if (text === Module.setStatus.text) return;
var m = text.match(/([^(]+)\((\d+(\.\d+)?)\/(\d+)\)/);
var now = Date.now();
if (m && now - Date.now() < 30) return; // if this is a progress update, skip it if too soon
if (m) {
text = m[1];
progressElement.value = parseInt(m[2])*100;
progressElement.max = parseInt(m[4])*100;
progressElement.hidden = false;
spinnerElement.hidden = false;
} else {
progressElement.value = null;
progressElement.max = null;
progressElement.hidden = true;
if (!text) spinnerElement.style.display = 'none';
}
statusElement.innerHTML = text;
},
totalDependencies: 0,
monitorRunDependencies: function(left) {
this.totalDependencies = Math.max(this.totalDependencies, left);
Module.setStatus(left ? 'Preparing... (' + (this.totalDependencies-left) + '/' + this.totalDependencies + ')' : 'All downloads complete.');
}
};
Module.setStatus('Downloading...');
window.onerror = function(event) {
// TODO: do not warn on ok events like simulating an infinite loop or exitStatus
Module.setStatus('Exception thrown, see JavaScript console');
spinnerElement.style.display = 'none';
Module.setStatus = function(text) {
if (text) Module.printErr('[post-exception status] ' + text);
};
};
</script>
and the second one is just
<script src=./a.out.js>
full of text you cant see on link to dropbox? its a lot of code to post here
and 3rd this is that i have copy from emscripter git repo html document that it must generate (but in my way not) and also put it to drop box link, to not to spam here.
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>
I am using JQuery History.js plugin to enable History API in HTML5 browsers and emulate in HTML4 browsers. I am using Ajaxify script to implement this plugin. I changed this script a little as shown:
var History, $, document;
function PrepareVariables() {
History = window.History,
$ = window.jQuery,
document = window.document;
}
function InitHistory() {
// Prepare Variables
var
/* Application Specific Variables */
//contentSelector = '#content,article:first,.article:first,.post:first',
contentSelector = '#navcontent';
$content = $(contentSelector), //.filter(':first'),
//contentNode = $content.get(0),
$menu = $('#menu,#nav,nav:first,.nav:first').filter(':first'),
activeClass = 'active selected current youarehere',
activeSelector = '.active,.selected,.current,.youarehere',
menuChildrenSelector = '> li,> ul > li',
completedEventName = 'statechangecomplete',
/* Application Generic Variables */
$window = $(window),
$body = $(document.body),
rootUrl = History.getRootUrl(),
scrollOptions = {
duration: 800,
easing: 'swing'
};
// Ensure Content
if ($content.length === 0) {
$content = $body;
}
// Internal Helper
$.expr[':'].internal = function (obj, index, meta, stack) {
// Prepare
var
$this = $(obj),
url = $this.attr('href') || '',
isInternalLink;
// Check link
isInternalLink = url.substring(0, rootUrl.length) === rootUrl || url.indexOf(':') === -1;
// Ignore or Keep
return isInternalLink;
};
// HTML Helper
var documentHtml = function (html) {
// Prepare
var result = String(html)
.replace(/<\!DOCTYPE[^>]*>/i, '')
.replace(/<(html|head|body|title|meta|script)([\s\>])/gi, '<div class="document-$1"$2')
.replace(/<\/(html|head|body|title|meta|script)\>/gi, '</div>');
// Return
return $.trim(result);
};
// Ajaxify Helper
$.fn.ajaxify = function () {
// Prepare
var $this = $(this);
// Ajaxify
//$this.find('a:internal:not(.no-ajaxy)').click(function (event) {
$this.find("a[data-isnav='0']").click(function (event) {
// Prepare
var
$this = $(this),
url = $this.attr('href'),
title = ($this.attr('title') || null);
// Continue as normal for cmd clicks etc
if (event.which == 2 || event.metaKey) {
return true;
}
// Ajaxify this link
History.pushState(null, title, url);
event.preventDefault();
return false;
});
// Chain
return $this;
};
// Ajaxify our Internal Links
$body.ajaxify();
// Hook into State Changes
$window.bind('statechange', function () {
// Prepare Variables
var
State = History.getState(),
url = State.url,
relativeUrl = url.replace(rootUrl, '');
// Start Fade Out
// Animating to opacity to 0 still keeps the element's height intact
// Which prevents that annoying pop bang issue when loading in new content
$content.animate({
opacity: 0
}, 800);
// Ajax Request the Traditional Page
callAjax("GetContent", {
URL: url /*typeOfHeader: contentType, argsdata: argdata*/
},
false,
function () {
var ops = $('#ops');
if (ops != null) ops.html('');
ShowProgress('');
//var now = (new Date()).getTime(); //Caching
//if (headerCache.exist(url)) {
// tDiff = now - headerCacheTime;
// if (tDiff < 3000) {
// setContentData(headerCache.get(url));
// return true;
// }
//}
},
function (d) {
//headerCache.set(url, d, null);
//cacheName = url;
HideProgress();
setContentData(d);
}, null);
// end ajax
}); // end onStateChange
}
(function (window, undefined) {
// Prepare our Variables
PrepareVariables();
// Check to see if History.js is enabled for our Browser
if (!History.enabled) {
return false;
}
// Wait for Document
$(function () {
InitHistory();
});
// end onDomLoad
})(window); // end closure
function UpdateHistory() {
var title = (document.title.trim().length > 0 ? document.title : null);
var url = window.location.href.replace(/^.*\/\/[^\/]+/, '');
var History = window.History;
History.replaceState(null, title, url);
$('a[data-isnav="0"').click(function () {
// Prepare
var
$this = $(this),
url = $this.attr('href'),
title = ($this.attr('title') || null);
// Continue as normal for cmd clicks etc
if (event.which == 2 || event.metaKey) {
return true;
}
// Ajaxify this link
History.pushState(null, title, url);
event.preventDefault();
return false;
});
}
function setContentData(d) {
var data = d.data;
// Fetch the scripts
//$scripts = $dataContent.find('.document-script');
//if ($scripts.length) {
// $scripts.detach();
//}
// Fetch the content
contentHtml = data;
if (!contentHtml) {
document.location.href = url;
return false;
}
// Update the menu
//$menuChildren = $menu.find(menuChildrenSelector);
//$menuChildren.filter(activeSelector).removeClass(activeClass);
//$menuChildren = $menuChildren.has('a[href^="' + relativeUrl + '"],a[href^="/' + relativeUrl + '"],a[href^="' + url + '"]');
//if ($menuChildren.length === 1) { $menuChildren.addClass(activeClass); }
// Update the content
$content.stop(true, true);
$content.html(contentHtml).ajaxify().css('opacity', 100).show(); /* you could fade in here if you'd like */
//Intialize other content
initContent();
// Update the title
//document.title = $data.find('.document-title:first').text();
//try {
// document.getElementsByTagName('title')[0].innerHTML = document.title.replace('<', '<').replace('>', '>').replace(' & ', ' & ');
//}
//catch (Exception) { }
// Add the scripts
//$scripts.each(function () {
// var $script = $(this), scriptText = $script.text(), scriptNode = document.createElement('script');
// if ($script.attr('src')) {
// if (!$script[0].async) { scriptNode.async = false; }
// scriptNode.src = $script.attr('src');
// }
// scriptNode.appendChild(document.createTextNode(scriptText));
// contentNode.appendChild(scriptNode);
//});
// Complete the change
if ($body.ScrollTo || false) {
$body.ScrollTo(scrollOptions);
} /* http://balupton.com/projects/jquery-scrollto */
$window.trigger(completedEventName);
// Inform Google Analytics of the change
if (typeof window._gaq !== 'undefined') {
window._gaq.push(['_trackPageview', relativeUrl]);
}
// Inform ReInvigorate of a state change
if (typeof window.reinvigorate !== 'undefined' && typeof window.reinvigorate.ajax_track !== 'undefined') {
reinvigorate.ajax_track(url);
// ^ we use the full url here as that is what reinvigorate supports
}
}
It is working fine and the content added on page using Ajax is added to previous state using UpdateHistory() function. On some pages the state is updated successfully but on one page it is not updating the content when the page is accessed for the second time. I searched SO for all the similar questions but unable to get any solution. First I thought the problem is with Internet Explorer but then I tried it on Firefox but it didn't work. Please tell me what can be the reason?
UPDATE
It's working for URLs like:
http://localhost:13956/AppStore/App/2012/Install
But not for:
http://localhost:13956/AppStore
It's look like first page is not saved. Try to call UpdateHistory() or History.pushState(null, title, url) inside InitHistory().
I am using indexdb as it supports all browser. I have successfully added data and got data from indexdb but I want to use where clause condition. Like I have Product Name, Pathogen, Disease,Route so I want to get data where Product Name let's say is Ali and Disease is Skin. They way I have got from different sites what it does it show all the record with starting and end the value provided in the two input fields.
Here is my code which I am using.
<!doctype html>
<html>
<head>
</head>
<body>
<script>
var db;
function indexedDBOk() {
return "indexedDB" in window;
}
document.addEventListener("DOMContentLoaded", function() {
//No support? Go in the corner and pout.
if(!indexedDBOk) return;
var openRequest = indexedDB.open("products",1);
//var openRequest = indexedDB.open("idarticle_people5",1);
openRequest.onupgradeneeded = function(e) {
var thisDB = e.target.result;
if(!thisDB.objectStoreNames.contains("products")) {
var os = thisDB.createObjectStore("products", {autoIncrement:true});
//I want to get by name later
os.createIndex("name", "name", {unique:false});
//I want email to be unique
os.createIndex("pathogen", "pathogen", {unique:false});
os.createIndex("disease", "disease", {unique:false});
os.createIndex("route", "route", {unique:false});
}
}
openRequest.onsuccess = function(e) {
db = e.target.result;
//Listen for add clicks
document.querySelector("#addButton").addEventListener("click", addPerson, false);
//Listen for get clicks
document.querySelector("#getButton").addEventListener("click", getPerson, false);
}
openRequest.onerror = function(e) {
//Do something for the error
}
},false);
function addPerson(e) {
var name = document.querySelector("#name").value;
var pathogen = document.querySelector("#pathogen").value;
var disease = document.querySelector("#disease").value;
var route = document.querySelector("#route").value;
console.log("About to add "+name+"/"+pathogen);
//Get a transaction
//default for OS list is all, default for type is read
var transaction = db.transaction(["products"],"readwrite");
//Ask for the objectStore
var store = transaction.objectStore("products");
//Define a person
var person = {
name:name,
pathogen:pathogen,
disease:disease,
route:route
}
//Perform the add
var request = store.add(person);
request.onerror = function(e) {
alert("Sorry, that email address already exists.");
console.log("Error",e.target.error.name);
console.dir(e.target);
//some type of error handler
}
request.onsuccess = function(e) {
console.log("Woot! Did it");
}
}
function getPerson(e) {
var name = document.querySelector("#nameSearch").value;
var endname = document.querySelector("#diseaseSearch").value;
if(name == "" && endname == "") return;
var transaction = db.transaction(["products"],"readonly");
var store = transaction.objectStore("products");
var index = store.index("name");
//Make the range depending on what type we are doing
var range;
if(name != "" && endname != "") {
range = IDBKeyRange.bound(name, endname);
} else if(name == "") {
range = IDBKeyRange.upperBound(endname);
} else {
range = IDBKeyRange.lowerBound(name);
}
var s = "";
index.openCursor(range).onsuccess = function(e) {
var cursor = e.target.result;
if(cursor) {
s += "<h2>Key "+cursor.key+"</h2><p>";
for(var field in cursor.value) {
s+= field+"="+cursor.value[field]+"<br/>";
}
s+="</p>";
cursor.continue();
}
document.querySelector("#status").innerHTML = s;
}
}
</script>
<input type="text" id="name" placeholder="Name"><br/>
<input type="text" id="pathogen" placeholder="Pathogen"><br/>
<input type="text" id="disease" placeholder="Disease"><br/>
<input type="text" id="route" placeholder="Route"><br/>
<button id="addButton">Add Data</button>
<p/>
<input type="text" id="nameSearch" placeholder="Name"><br/>
<input type="text" id="diseaseSearch" placeholder="Disease"><br/>
<button id="getButton">Get By Name</button>
<p/>
<div id="status"></div>
</body>
</html>
You can try the following procedure with three parameters:
databaseid
tableid - storage name
callback - function, which returns array of selected data
cond - conditional function. returns true for ok records, and false for others.
Here is the code:
function selectFromTable (databaseid, tableid, cb, cond) {
var request = window.indexedDB.open(databaseid);
request.onsuccess = function(event) {
var res = [];
var ixdb = event.target.result;
var tx = ixdb.transaction([tableid]);
var store = tx.objectStore(tableid);
var cur = store.openCursor();
cur.onblocked = function(event) {
}
cur.onerror = function(event) {
}
cur.onsuccess = function(event) {
var cursor = event.target.result;
if(cursor) {
if(cond(cursor.value) ) res.push(cursor.value);
cursor.continue();
} else {
ixdb.close();
cb(res);
}
}
}
Try using a browser database API adapter and read about its usage from its wiki page.
You need to include all 3 JS files to get started.
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) {
...
}