Simplifying onclick jquery/JavaScript functions - javascript

I am trying to simplify all .js functions on the site to improve page load speed and overall performance of my site. Managed to do most of it on my own, but got stack when started to minimize couple of functions that are mostly call backs and onclick functions called from the functions.js in the page head.
SO here is my question, how can I make one function out of the following 2 to make script shorter and without loosing any functionality, or if there any alternative way to make it all simpler than it currently is?
function user_dialog(dialog_content, download_button) {
if (typeof jQuery.ui != 'undefined') {
$("#dialog").attr("title", "Lets share it").html(dialog_content);
$("#dialog").dialog({
modal: false,
width: 400,
buttons: {
Cancel: function() {
$(this).dialog("close");
},
"Download": function () {
$(this).dialog("close");
window.location = download_button;
}
}
});
} else {
window.location = download_button;
}
}
function user_notice(link_source) {
download_link = $(link_source).attr("href");
$.ajax({
type: "POST",
url: "/includes/json.php",
data: "action=reminder&thepath=" + download_link,
dataType: "json",
error: function() {
window.location = download_link;
},
success: function(resp_dialog) {
if (resp_dialog.status == 1) {
user_dialog(resp_dialog.html, download_link);
}
}
});
}
Thanks for your help in advance!!!

add an action variable in your function vars, like us_action and un_action then use an if statement to say if is us_acion, perform this else if un_action do this

Related

Initialize common JS functions for performance

I am trying to optimize JS performance for a first-time user and SEO, with the goal of minimizing First Input Delay. When the home page loads, I initialize common JS functionalities and actions across the site with:
<script defer src="~/assets/js/common.js"></script>
In common.js:
$(function () {
initActions();
}
function initActions() {
$(document).on("click", "a.modal-link", function (e) {
var target = $(this).data("target");
$.ajax({
type: "GET",
url: $(this).data("url"),
dataType: "html",
cache: false,
success: function (response) {
$(target + " .modal-content").html(response);
$(target).modal("show");
}
}).fail(function () {
networkError();
});
});
setTimeout(function () {
$("#successLabel").slideUp("slow");
}, 8000);
$(".utcToLocalDate").each(function () {
$(this).text(moment.utc($(this).data("datetimeutc")).local().format("l"));
});
Is there a best practice to structure JS and declare common functions? I am aware this code is inefficient and I am currently going in circles with iterative improvements.

How to call a function in javascript?

I want to call a function every time my update was successful. The update is working my only concern is the alert pop-up every successful update.
$.post(
{
url: 'update_question.php',
data:
{
id: id,
new_question: newText,
},
success: function()
{
that.replaceWith("<section>"+newText+"</section>");
if(text != newText)
{
popup();
}
}
});
var popup = function () {
$(document).ready (function(){
$("#myWish").click(function showAlert() {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
});
});
};
var popup = function () {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
};
On the first update, pop-up showed but it doesn't show on the 2nd update
I think it'll solve your issue
$.post(
{
url: 'update_question.php',
data:
{
id: id,
new_question: newText,
},
success: function()
{
that.replaceWith("<section>"+newText+"</section>");
if(text != newText){
popup();
}
}
});
function popup() {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
};
The $(document).ready jquery function waits until the DOM is loaded into your browser before it executes the javascript code contained within it's function scope {}.
So remove $(document).ready from your code.
Also note that single page applications only need to list $(document).ready once and all the listener events you setup are defined within it's body.
So you should have it listed somewhere at least once and then you define all your initial event listeners within its body.

How to check if my container fully load is completed?

I have an issue, do not know if it possible or not, how to check if my container is already loaded or not, because sometimes it is being loaded faster, sometimes slower and if it does not succeed in time getting an error in javaScript where gridview some functions are not recognizable(because the gridview is not loaded fast enough). Hope it is clear. Thanks for Your time.
Code:
function LoadPartial(partialUrl, container) {
$.ajax({
type: 'POST',
url: partialUrl,
success: function (returnData) {
$(container).html(returnData);
}
});
//.done(function () {
// return;
//});
}
you can use something like this.
$(".container").load(function (){
alert("Loaded :)");
});
Let me know in-case this doesn't work.
You can try using .data()
if ($('#mycontainer').data('loaded')) {
// your code
}
If you mean to find event when data received use "complete" function:
$.ajax({
type: 'POST',
url: partialUrl,
success: function (returnData) {
$(container).html(returnData);
},
complete: function() {
console.log('container filled with data');
}
});

jQuery .ajax blocking .getJSON?

this is my first question, please be gentle :) I've been trying to resolve this for a couple of hours now and I'm getting nowhere fast.
Background
I have a web application where a process is kicked off with .ajax(). This can take a little while to complete, so I have set up a jQuery.progressbar() system to give UI feedback that is started (using setInterval) at the same time as the .ajax(), and every 250ms it calls a .getJSON() to read the progress of the background event. Everything server-side seems to function flawlessly.
The Problem
It seems that (from copious use of console.log() that the .ajax() event blocks the .getJSON() from running, until the .ajax() has completed. In my console log I have every 250ms an indication that updateProgressBar() is running, but I never get into the .done portion of it until the original .ajax() call finishes.
What am I missing here?
// file copy dialog
$(function () {
$("#file_copy_dialog").dialog({
autoOpen: false,
resizable: false,
height: 250,
width: 400,
modal: true,
buttons: {
"Copy Files": function () {
// do ajax copy request
console.log("Starting setInterval updateProgressBar()");
window.interval = setInterval('updateProgressBar()', 250);
console.log("---------------------------------- Firing file_copy AJAX request ---------------------------------");
$.ajax({
type: "POST",
url: "/ajax/file_copy.php",
data: {
job_id: "<?php echo $item_data['job_id']; ?>",
item_id: "<?php echo $item_id; ?>",
quote_id: "<?php echo $item_data['quote_id']; ?>"
}
})
.done(function () {
console.log("----------------------------- file_copy AJAX done --------------------------------------");
});
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
});
// paste button click event handler
$(function () {
$("#paste_files").click(function () {
// open dialog box
$("#progressbar").progressbar({
value: 0
});
$(".progress-label").text("Ready");
$("#file_copy_dialog").dialog("open");
});
});
// progress bar initiator
$(function () {
var progressbar = $("#progressbar"),
progressLabel = $(".progress-label");
progressbar.progressbar({
value: false,
change: function () {
progressLabel.text(progressbar.progressbar("value") + "%");
},
complete: function () {
progressLabel.text("Complete!");
}
});
});
// file copy progress checker
function updateProgressBar() {
console.log("Running updateProgressBar()");
$.getJSON("/ajax/file_copy_progress.php")
.done(function (json) {
console.log("In UpdateProgressBar().done");
// successful check
if (json.status == 'ERROR') {
console.log("updateProgressBar() json.status = ERROR");
$('#progresstext').text(json.message);
clearInterval(window.interval);
} else {
console.log("updateProgressBar() json.status = " + json.status + " json.value = " + json.value);
$('#progressbar').progressbar({
value: json.value
});
$('#progresstext').text(json.message);
}
if (json.value == 100) {
console.log("ClearInterval()");
clearInterval(window.interval);
}
})
.fail(function (jqxhr, textStatus, error) {
// check failed
$('#progresstext').text("Progress check request failed");
});
}
Forgive my formatting ... and thank you for any help you may be able to provide.
EDIT
Thanks to Adeneo, turns out there's nothing wrong with the above code at all. The issue lies with PHP locking the session file. Calling session_write_close() and session_start() in strategic places in your initial backend ajax() called' script, will allow the second script to get a look-in occasionally and read the status.
The issue lies with PHP, not jQuery in this instance.
As pointed out by #adeneo, only one process can read/write the session file at once. (Quite logical when you think about it!). Calling
session_write_close()
and then
session_start()
in strategically good places in your initial script, will permit the first script to get a go at reading the session variables occasionally, and make the whole thing work as intended.

How to extend jQuery's AJAX function

I've played around with creating my own jquery functions, this done via the
$.fn.extend({
myFunc: function () {
}
});
However, after scouring the web and SO for an answer, I would like to ask:
How can I extend $.ajax()
The new implementation of $.ajax can be used by running
$.ajax({
}).done(function (e) {
}).fail(function (e) {
});
What I would like to do is to add a .progress() so that I don't always have to write
$.ajax({
url: path,
xhrFields: {
onprogress: function (e) {
if (e.lengthComputable) {
console.log(e.loaded /e.total * 100 + '%');
}
}
}
});
each time I want to monitor the progress. e.g.
$.ajax({
url: '/somewhereorother',
type: 'post',
dataType: 'json'
}).progress(function (e) {
updateProgressBar(e.percentage + '%');
}).done(function (e) {
}).fail(function (e) {
});
$.ajax is a function attached to $ object.
As such, to extend it you would have to store the reference to it somewhere, and call it when needed, something like:
var ajax = $.ajax;
$.ajax = function()
{
if (!arguments[0].success)
arguments[0].success = function()
{
window.alert('done!');
}
ajax.apply(ajax, arguments);
}
This is a concept (I'm not sure of this scope in apply - would have to actually run it) ;) Also, I'd say it's ugly as hell way of doing things.
If you want your $.ajax function to differ from official function, I'd still separate it. Either via $.my_ajax or by separate namespace (take a look at http://api.jquery.com/jquery.sub/)

Categories

Resources