I'm looking for the opposite of that everyone's been looking for. I have this anonymous jQuery function that I want to keep that way, but I want to attach multiple events handlers to it on different events (two events exactly).
When the textarea has text inside it changed (keyup)
When document is clicke (click).
I know that grabbing the callback function and putting it in a function declaration, then using the function on both cases would do the job, but is there something around that wont require me to put the callback function in a normal function and just leave it as is?
This is the code I currently have:
urls.keyup(function(){
delay('remote', function(){
if (urls.val().length >= char_start)
{
var has_lbrs = /\r|\n/i.test(urls.val());
if (has_lbrs)
{
urls_array = urls.val().split("\n");
for (var i = 0; i < urls_array.length; i++)
{
if (!validate_url(urls_array[i]))
{
urls_array.splice(i, 1);
continue;
}
}
}
else
{
if (!validate_url(urls.val()))
{
display_alert('You might have inserted an invalid URL.', 'danger', 3000, 'top');
return;
}
}
final_send = (has_lbrs && urls_array.length > 0) ? urls_array : urls.val();
if (!final_send)
{
display_alert('There went something wrong while uploading your images.', 'danger', 3000, 'top');
return;
}
var template = '<input type="text" class="remote-progress" value="0" />';
$('.pre-upload').text('').append(template);
$('.remote-progress').val(0).trigger('change').delay(2000);
$('.remote-progress').knob({
'min':0,
'max': 100,
'readOnly': true,
'width': 128,
'height': 128,
'fgColor': '#ad3b3b',
'bgColor': '#e2e2e2',
'displayInput': false,
'cursor': true,
'dynamicDraw': true,
'thickness': 0.3,
'tickColorizeValues': true,
});
var tmr = self.setInterval(function(){myDelay()}, 50);
var m = 0;
function myDelay(){
m++;
$('.remote-progress').val(m).trigger('change');
if (m == 100)
{
// window.clearInterval(tmr);
m = 0;
}
}
$.ajax({
type: 'POST',
url: 'upload.php',
data: {
upload_type: 'remote',
urls: JSON.stringify(final_send),
thumbnail_width: $('.options input[checked]').val(),
resize_width: $('.options .resize_width').val(),
album_id: $('#album_id').val(),
usid: $('#usid').val(),
},
success: function(data) {
// console.log(data); return;
var response = $.parseJSON(data);
if (response)
{
$('.middle').hide();
$('.remote-area').hide();
window.clearInterval(tmr);
}
if ('error' in response)
{
//console.log(response.error);
if (!$('.top-alert').is(':visible'))
{
display_alert(response.error, 'danger', 3000, 'top');
}
return;
}
if (!target.is(':visible'))
{
target.show().addClass('inner');
}
else
{
target.addClass('inner');
}
for (var key in response)
{
var image_url = response[key];
var thumb_uri = image_url.replace('/i/', '/t/');
var forum_uri = '[img]' + image_url + '[/img]';
var html_uri = '<a href="' + image_url + '">' + image_url + '</a>';
var view_url = image_url.replace(/store\/i\/([A-Za-z0-9]+)(?=\.)/i, "image/$1");
view_url = strstr(view_url, '.', true);
// Append the upload box
target.append(upload_box(key));
// Hide knob
$('.knobber').hide();
// Put the image box
putImage($('.' + key), view_url, image_url, thumb_uri, forum_uri, html_uri);
}
},
});
}
}, 2000); // Delay
}); // Remote upload
How do I make this code run on document click as well?
Thank you.
As you yourself has said in you question, the answer is to create an external named reference to the callback function and use it as the callback.
Like
jQuery(function () {
function callback(e) {
console.log('event2', e.type);
}
$('input').keyup(callback);
$(document).click(callback)
})
But since you have asked for a different style have a look at, it essentially does the same as the above one
jQuery(function () {
var callback;
$('input').keyup(callback = function (e) {
console.log('event', e.type);
});
$(document).click(callback)
})
Demo: Fiddle
Related
I am trying to save data using ajax. The ajax is inside my javascript file and passed to my controller and route. However the issue is it cannot save the data into my database.
Here is my jquery.hotspot.js file that include ajax:
(function ($) {
var defaults = {
// Object to hold the hotspot data points
data: [],
// Element tag upon which hotspot is (to be) build
tag: 'img',
// Specify mode in which the plugin is to be used
// `admin`: Allows to create hotspot from UI
// `display`: Display hotspots from `data` object
mode: 'display',
// HTML5 LocalStorage variable where hotspot data points are (will be) stored
LS_Variable: '__HotspotPlugin_LocalStorage',
// CSS class for hotspot data points
hotspotClass: 'HotspotPlugin_Hotspot',
// CSS class which is added when hotspot is to hidden
hiddenClass: 'HotspotPlugin_Hotspot_Hidden',
// Event on which the hotspot data point will show up
// allowed values: `click`, `hover`, `none`
interactivity: 'hover',
// Action button CSS classes used in `admin` mode
save_Button_Class: 'HotspotPlugin_Save',
remove_Button_Class: 'HotspotPlugin_Remove',
send_Button_Class: 'HotspotPlugin_Send',
// CSS class for hotspot data points that are yet to be saved
unsavedHotspotClass: 'HotspotPlugin_Hotspot_Unsaved',
// CSS class for overlay used in `admin` mode
hotspotOverlayClass: 'HotspotPlugin_Overlay',
// Enable `ajax` to read data directly from server
ajax: false,
ajaxOptions: { url: '' },
listenOnResize: true,
// Hotspot schema
schema: [
{
'property': 'Title',
'default': ''
},
{
'property': 'Message',
'default': ''
}
]
};
// Constructor
function Hotspot(element, options) {
var widget = this;
// Overwriting defaults with options
this.config = $.extend(true, {}, defaults, options);
this.element = element;
// `tagElement`: element for which hotspots are being done
this.tagElement = element.find(this.config.tag);
// Register event listeners
$.each(this.config, function (index, fn) {
if (typeof fn === 'function') {
widget.element.on(index + '.hotspot', function (event, err, data) {
fn(err, data);
});
}
});
if (this.config.mode != 'admin' && this.config.listenOnResize) {
$(window).on('resize', function () {
$(element).find('.' + widget.config.hotspotClass).remove();
widget.init();
});
}
if (this.config.tag !== 'img') {
widget.init();
return;
}
if (this.tagElement.prop('complete')) {
widget.init();
} else {
this.tagElement.one('load', function (event) {
widget.init();
});
}
}
Hotspot.prototype.init = function () {
this.parseData();
// Fetch data for `display` mode with `ajax` enabled
if (this.config.mode != 'admin' && this.config.ajax) {
this.fetchData();
}
// Nothing else to do here for `display` mode
if (this.config.mode != 'admin') {
return;
}
this.setupWorkspace();
};
Hotspot.prototype.createId = function () {
var id = "";
var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < 7; i++) {
id += letters.charAt(Math.floor(Math.random() * letters.length));
}
return id;
};
Hotspot.prototype.setupWorkspace = function () {
var widget = this;
// `data` array: to contain hotspot objects
var data = [];
var tHeight = $(widget.tagElement[0]).height(),
tWidth = $(widget.tagElement[0]).width(),
tOffset = widget.tagElement.offset(),
pHeight = $(widget.element[0]).height(),
pWidth = $(widget.element[0]).width(),
pOffset = widget.element.offset();
// Create overlay for the tagElement
$('<span/>', {
html: '<p>Click this Panel to Store Messages</p>'
}).css({
'height': (tHeight / pHeight) * 100 + '%',
'width': (tWidth / pWidth) * 100 + '%',
'left': (tOffset.left - pOffset.left) + 'px',
'top': (tOffset.top - pOffset.top) + 'px'
}).addClass(widget.config.hotspotOverlayClass).appendTo(widget.element);
// Handle click on overlay mask
this.element.delegate('span', 'click', function (event) {
event.preventDefault();
event.stopPropagation();
// Get coordinates
var offset = $(this).offset(),
relativeX = (event.pageX - offset.left),
relativeY = (event.pageY - offset.top);
var height = $(widget.tagElement[0]).height(),
width = $(widget.tagElement[0]).width();
var hotspot = { x: relativeX / width * 100, y: relativeY / height * 100 };
var schema = widget.config.schema;
for (var i = 0; i < schema.length; i++) {
var val = schema[i];
var fill = prompt('Please enter ' + val.property, val.default);
if (fill === null) {
return;
}
hotspot[val.property] = fill;
}
data.push(hotspot);
// Temporarily display the spot
widget.displaySpot(hotspot, true);
});
// Register admin controls
var button_id = this.createId();
$('<button/>', {
text: "Save data"
}).prop('id', ('save' + button_id)).addClass(this.config.save_Button_Class).appendTo(this.element);
$('<button/>', {
text: "Remove data"
}).prop('id', ('remove' + button_id)).addClass(this.config.remove_Button_Class).appendTo(this.element);
$(this.element).delegate('button#' + ('save' + button_id), 'click', function (event) {
event.preventDefault();
event.stopPropagation();
widget.saveData(data);
data = [];
});
$(this.element).delegate('button#' + ('remove' + button_id), 'click', function (event) {
event.preventDefault();
event.stopPropagation();
widget.removeData();
});
if (this.config.ajax) {
$('<button/>', {
text: "Send to server"
}).prop('id', ('send' + button_id)).addClass(this.config.send_Button_Class).appendTo(this.element);
$(this.element).delegate('button#' + ('send' + button_id), 'click', function (event) {
event.preventDefault();
event.stopPropagation();
widget.sendData();
});
}
};
Hotspot.prototype.fetchData = function () {
var widget = this;
// Fetch data from a server
var options = {
data: {
HotspotPlugin_mode: "Retrieve"
}
};
$.ajax($.extend({}, this.config.ajaxOptions, options))
.done(function (data) {
// Storing in localStorage
localStorage.setItem(widget.config.LS_Variable, data);
widget.parseData();
})
.fail($.noop);
};
Hotspot.prototype.parseData = function () {
var widget = this;
var data = this.config.data,
data_from_storage = localStorage.getItem(this.config.LS_Variable);
if (data_from_storage && (this.config.mode === 'admin' || !this.config.data.length)) {
data = JSON.parse(data_from_storage);
}
$.each(data, function (index, hotspot) {
widget.displaySpot(hotspot);
});
};
Hotspot.prototype.displaySpot = function (hotspot, unsaved) {
var widget = this;
var spot_html = $('<div/>');
$.each(hotspot, function (index, val) {
if (typeof val === "string") {
$('<div/>', {
html: val
}).addClass('Hotspot_' + index).appendTo(spot_html);
}
});
var height = $(this.tagElement[0]).height(),
width = $(this.tagElement[0]).width(),
offset = this.tagElement.offset(),
parent_offset = this.element.offset();
var spot = $('<div/>', {
html: spot_html
}).css({
'top': (hotspot.y * height / 100) + (offset.top - parent_offset.top) + 'px',
'left': (hotspot.x * width / 100) + (offset.left - parent_offset.left) + 'px'
}).addClass(this.config.hotspotClass).appendTo(this.element);
if (unsaved) {
spot.addClass(this.config.unsavedHotspotClass);
}
if (this.config.interactivity === 'hover') {
return;
}
// Overwrite CSS rule for `none` & `click` interactivity
spot_html.css('display', 'block');
// Initially keep hidden
if (this.config.interactivity !== 'none') {
spot_html.addClass(this.config.hiddenClass);
}
if (this.config.interactivity === 'click') {
spot.on('click', function (event) {
spot_html.toggleClass(widget.config.hiddenClass);
});
} else {
spot_html.removeClass(this.config.hiddenClass);
}
};
Hotspot.prototype.saveData = function (data) {
if (!data.length) {
return;
}
// Get previous data
var raw_data = localStorage.getItem(this.config.LS_Variable);
var hotspots = [];
if (raw_data) {
hotspots = JSON.parse(raw_data);
}
// Append to previous data
$.each(data, function (index, node) {
hotspots.push(node);
});
this.data=data;
$.ajax({
type:"POST",
url:"/store",
dataType:'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data:{
Title:$('#Title').val(),
Message: $('#Message').val(),
x:$('#relativeX').val(),
y: $('#relativeY').val(),
},
success: function(data){
console.log(data,d);
},
error: function(data)
{
console.log(data);
},
});
localStorage.setItem(this.config.LS_Variable, JSON.stringify(hotspots));
this.element.trigger('afterSave.hotspot', [null, hotspots]);
};
Hotspot.prototype.removeData = function () {
if (localStorage.getItem(this.config.LS_Variable) === null) {
return;
}
if (!confirm("Are you sure you wanna do everything?")) {
return;
}
localStorage.removeItem(this.config.LS_Variable);
this.element.trigger('afterRemove.hotspot', [null, 'Removed']);
};
Hotspot.prototype.sendData = function () {
if (localStorage.getItem(this.config.LS_Variable) === null || !this.config.ajax) {
return;
}
var widget = this;
var options = {
data: {
HotspotPlugin_data: localStorage.getItem(this.config.LS_Variable),
HotspotPlugin_mode: "Store"
}
};
$.ajax($.extend({}, this.config.ajaxOptions, options))
.done(function () {
widget.element.trigger('afterSend.hotspot', [null, 'Sent']);
})
.fail(function (err) {
widget.element.trigger('afterSend.hotspot', [err]);
});
};
$.fn.hotspot = function (options) {
new Hotspot(this, options);
return this;
};
}(jQuery));
Here is my route:
Route::get('hotspots','ImageController#getPin');
Route::post('store','ImageController#storePin')->name('store.storePin');
Here is my ImageController.php:
public function getPin()
{
$pin= Pin::select('Title','Message','x','y');
return hotspot::of($pin)->make(true);
}
public function storePin(Request $request)
{
$validation = Validator::make($request->all(), [
'Title' => 'required',
'Message' => 'required',
'x'=>'required',
'y'=>'required',
]);
if ($request->get('save','button_id') == "insert")
{
$pin = new Pin();
$pin->Title=$request->Title;
$pin->Message= $request->Message;
$pin->x = $request->relativeX;
$pin->y =$request->relativeY;
$pin->save();
//return Request::json($request);
}
}
Here is my hotspot.blade.php:
<!DOCTYPE html>
<html>
<head>
<title>Picomment Hotspot</title>
<link rel="stylesheet" type="text/css" href="{{ asset ('css/bootsrap.min.css') }}">
<script type="text/javascript" src="{{ asset ('js/jquery.min.js') }}"></script>
<link rel="stylesheet" type="text/css" href="{{ asset ('css/jquery.hotspot.css') }}">
<link rel="stylesheet" type="text/css" href="{{ asset ('css/style.css') }}">
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
<div class="container">
<div class="col-md-6" style="margin-top: 40px;">
<div id="theElement-a">
<img src="{{ asset('storage/'.$files) }}" alt="" title="">
</div>
</div>
</div>
<script type="text/javascript" src="{{ asset ('js/jquery.hotspot.js') }}"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#theElement-a").hotspot({
mode: "admin",
// uncomment
/*ajax: true,
ajaxOptions: {
'url': 'links.to.server'
},*/
interactivity: "click",
LS_Variable: "HotspotPlugin-a",
afterSave: function(err, data) {
if (err) {
console.log('Error occurred', err);
return;
}
alert('Saved');
// `data` in json format can be stored
// & passed in `display` mode for the image
localStorage.clear();
console.log(data);
},
afterRemove: function(err, message) {
if (err) {
console.log('Error occurred', err);
return;
}
alert(message);
window.location.reload();
},
afterSend: function(err, message) {
if (err) {
console.log('Error occurred', err);
return;
}
alert(message);
}
});
});
</script>
</body>
</html>
I am using this plugin:http://www.jqueryscript.net/social-media/jQuery-Plugin-To-Display-Instagram-Photos-On-Your-Web-Page-Instagram-Lite.html
When I set up my username and client-ID, it pulls photos from the wrong feed, for which I don't even have access (it pulls from helaspamexico, but instead it should be pulling from helaspa -> I am logged in to this and have generated client-ID for this)... Has anyone experienced something similar?
/*!
Name: Instagram Lite
Dependencies: jQuery
Author: Michael Lynch
Author URL: http://michaelynch.com
Date Created: January 14, 2014
Licensed under the MIT license
*/
;(function($) {
$.fn.instagramLite = function(options) {
// return if no element was bound
// so chained events can continue
if(!this.length) {
return this;
}
// define plugin
plugin = this;
// define default parameters
plugin.defaults = {
username: null,
clientID: null,
limit: null,
list: true,
videos: false,
urls: false,
captions: false,
date: false,
likes: false,
comments_count: false,
max_id: null,
load_more: null,
error: function() {},
success: function() {}
}
// vars
var s = $.extend({}, plugin.defaults, options),
el = $(this);
var getMaxId = function(items) {
// return id of last item
return items[items.length-1].id;
};
var formatCaption = function(caption) {
var words = caption.split(' '),
newCaption = '';
for(var i = 0; i < words.length; i++) {
var word;
if(words[i][0] == '#') {
var a = ''+words[i]+'';
word = a;
} else if(words[i][0] == '#') {
var a = ''+words[i]+'';
word = a;
} else {
word = words[i]
}
newCaption += word + ' ';
}
return newCaption;
};
var loadContent = function() {
// if client ID and username were provided
if(s.clientID && s.username) {
// for each element
el.each(function() {
var el = $(this);
// search the user
// to get user ID
$.ajax({
type: 'GET',
url: 'https://api.instagram.com/v1/users/search?q='+s.username+'&client_id='+s.clientID+'&callback=?',
dataType: 'jsonp',
success: function(data) {
if(data.data.length) {
// define user namespace
var thisUser = data.data[0];
// construct API endpoint
var url = 'https://api.instagram.com/v1/users/'+thisUser.id+'/media/recent/?client_id='+s.clientID+'&count='+s.limit+'&callback=?';
// concat max id if max id is set
url += (s.max_id) ? '&max_id='+s.max_id : '';
$.ajax({
type: 'GET',
url: url,
dataType: 'jsonp',
success: function(data) {
// if success status
if(data.meta.code === 200 && data.data.length) {
// for each piece of media returned
for(var i = 0; i < data.data.length; i++) {
// define media namespace
var thisMedia = data.data[i],
item;
// if media type is image or videos is set to false
if(thisMedia.type === 'image' || !s.videos) {
// construct image
item = '<img class="il-photo__img" src="'+thisMedia.images.standard_resolution.url+'" alt="Instagram Image" data-filter="'+thisMedia.filter+'" />';
// if url setting is true
if(s.urls) {
item = ''+item+'';
}
if(s.captions || s.date || s.likes || s.comments_count) {
item += '<div class="il-photo__meta">';
}
// if caption setting is true
if(s.captions && thisMedia.caption) {
item += '<div class="il-photo__caption" data-caption-id="'+thisMedia.caption.id+'">'+formatCaption(thisMedia.caption.text)+'</div>';
}
// if date setting is true
if(s.date) {
var date = new Date(thisMedia.created_time * 1000),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear(),
hours = date.getHours(),
minutes = date.getMinutes(),
seconds = date.getSeconds();
date = month +'/'+ day +'/'+ year;
item += '<div class="il-photo__date">'+date+'</div>';
}
// if likes setting is true
if(s.likes) {
item += '<div class="il-photo__likes">'+thisMedia.likes.count+'</div>';
}
// if caption setting is true
if(s.comments_count && thisMedia.comments) {
item += '<div class="il-photo__comments">'+thisMedia.comments.count+'</div>';
}
if(s.captions || s.date || s.likes || s.comments_count) {
item += '</div>';
}
}
if(thisMedia.type === 'video' && s.videos) {
if(thisMedia.videos) {
var src;
if(thisMedia.videos.standard_resolution) {
src = thisMedia.videos.standard_resolution.url;
} else if(thisMedia.videos.low_resolution) {
src = thisMedia.videos.low_resolution.url;
} else if(thisMedia.videos.low_bandwidth) {
src = thisMedia.videos.low_bandwidth.url;
}
item = '<video poster="'+thisMedia.images.standard_resolution.url+'" controls>';
item += '<source src="'+src+'" type="video/mp4;"></source>';
item += '</video>';
}
}
// if list setting is true
if(s.list && item) {
// redefine item with wrapping list item
item = '<li class="il-item" data-instagram-id="'+thisMedia.id+'">'+item+'</li>';
}
// append image / video
if(item !== '') {
el.append(item);
}
}
// set new max id
s.max_id = getMaxId(data.data);
// execute success callback
s.success.call(this);
} else {
// execute error callback
s.error.call(this, data.meta.code, data.meta.error_message);
}
},
error: function() {
// recent media ajax request failed
// execute error callback
s.error.call(this);
}
});
} else {
// error finding username
// execute error callback
s.error.call(this);
}
},
error: function() {
// search username ajax request failed
// execute error callback
s.error.call(this);
}
});
});
} else {
// username or client ID were not provided
// execute error callback
s.error.call(this);
};
}
// bind load more click event
if(s.load_more){
$(s.load_more).on('click', function(e) {
e.preventDefault();
loadContent();
});
}
// init
loadContent();
}
})(jQuery);
<ul class="instagram"></ul>
Load more
<br clear="all">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// Wait untill everything loads
$(window).load(function(){
$('.instagram').instagramLite({
username: 'helaspa',
clientID: 'ecdadd6520c04f5b8ae8bfdc888dd59c',
urls: true,
limit: 10,
load_more: '.instagram-more',
captions: false,
likes: false,
comments_count: false,
success: function() {
console.log('The request was successful!');
},
error: function(errorCode, errorMessage) {
console.log('There was an error');
if(errorCode && errorMessage) {
alert(errorCode +': '+ errorMessage);
}
}
});
});
</script>
If you are looking for a bad but quick solution, just put a '$' on the end of your username. The result of the API call will have your result first (by dumb luck) so the library will work.
The library you are using is not parsing the result of the query API correctly. The query API returns results for usernames similar to your query and doesn't filter results that are the wrong username.
Really, you should submit a patch to the library to use an API other than search: https://instagram.com/developer/endpoints/users/
Here is the bad the function:
https://github.com/michael-lynch/instagram-lite/blob/master/src/instagramLite.js#L95
I have a script that pulls data from my CMS and then allows a person to vote on a poll. The script works fine. However, I have Ad Block Plus Plugin installed in Firefox. When that is enabled to blocks the script from submitting the form correctly. It appears to submit correctly in the front end but is never registered in the back end.
Why does Ad Block Plus block my script that has nothing to do with ads?
The script is below:
$(document).ready(function () {
var Engine = {
ui: {
buildChart: function() {
if ($("#pieChart").size() === 0) {
return;
}
var pieChartData = [],
totalVotes = 0,
$dataItems = $("ul.key li");
// grab total votes
$dataItems.each(function (index, item) {
totalVotes += parseInt($(item).data('votes'));
});
// iterate through items to draw pie chart
// and populate % in dom
$dataItems.each(function (index, item) {
var votes = parseInt($(item).data('votes')),
votePercentage = votes / totalVotes * 100,
roundedPrecentage = Math.round(votePercentage * 10) / 10;
$(this).find(".vote-percentage").text(roundedPrecentage);
pieChartData.push({
value: roundedPrecentage,
color: $(item).data('color')
});
});
var ctx = $("#pieChart").get(0).getContext("2d");
var myNewChart = new Chart(ctx).Pie(pieChartData, {});
}, // buildChart
pollSubmit: function() {
if ($("#pollAnswers").size() === 0) {
return;
}
var $form = $("#pollAnswers"),
$radioOptions = $form.find("input[type='radio']"),
$existingDataWrapper = $(".web-app-item-data"),
$webAppItemName = $existingDataWrapper.data("item-name"),
$formButton = $form.find("button"),
bcField_1 = "CAT_Custom_1",
bcField_2 = "CAT_Custom_2",
bcField_3 = "CAT_Custom_3",
$formSubmitData = "";
$radioOptions.on("change", function() {
$formButton.removeAttr("disabled"); // enable button
var chosenField = $(this).data("field"), // gather value
answer_1 = parseInt($existingDataWrapper.data("answer-1")),
answer_2 = parseInt($existingDataWrapper.data("answer-2")),
answer_3 = parseInt($existingDataWrapper.data("answer-3"));
if (chosenField == bcField_1) {
answer_1 = answer_1 + 1;
$formSubmitData = {
ItemName: $webAppItemName,
CAT_Custom_1: answer_1,
CAT_Custom_2: answer_2,
CAT_Custom_3: answer_3
};
}
if (chosenField == bcField_2) {
answer_2 = answer_2 + 1;
$formSubmitData = {
ItemName: $webAppItemName,
CAT_Custom_1: answer_1,
CAT_Custom_2: answer_2,
CAT_Custom_3: answer_3
};
}
if (chosenField == bcField_3) {
answer_3 = answer_3 + 1;
$formSubmitData = {
ItemName: $webAppItemName,
CAT_Custom_1: answer_1,
CAT_Custom_2: answer_2,
CAT_Custom_3: answer_3
};
}
prepForm($formSubmitData);
});
function prepForm(formSubmitData) {
$formButton.click(function(e) {
e.preventDefault();
logAnonUserIn("anon", "anon", formSubmitData); // log user in
}); // submit
} // prepForm
function logAnonUserIn(username, password, formSubmitData) {
$.ajax({
type: 'POST',
url: '/ZoneProcess.aspx?ZoneID=-1&Username=' + username + '&Password=' + password,
async: true,
beforeSend: function () {},
success: function () {},
complete: function () {
fireForm(formSubmitData);
}
});
} // logAnonUserIn
function fireForm(formSubmitData) {
// submit the form
var url = "/CustomContentProcess.aspx?A=EditSave&CCID=13998&OID=3931634&OTYPE=35";
$.ajax({
type: 'POST',
url: url,
data: formSubmitData,
async: true,
success: function () {},
error: function () {},
complete: function () {
window.location = "/";
}
});
}
} // pollSubmit
} // end ui
};
Engine.ui.buildChart();
Engine.ui.pollSubmit();
});
As it turns out easylist contains this filter:
.aspx?zoneid=
This is why my script is being blocked.
I was told I can try this exception filter:
##||example.com/ZoneProcess.aspx?*$xmlhttprequest
I could also ask easylist to add an exception.
Answer comes from Ad Block Plus Forums.
I have a save button that calls a function to open a modal dialog with two buttons; "Save Timelines" and "Cancel". The "Save Timeline" button calls two functions AFTER WHICH the page needs to reload. I've tried a few different ways to get this done...
1 Just calling the functions pragmatically:
function genSaveTimelinesModal() {
$("#saveTimelineDialog").dialog({
resizable: false,
height: 250,
modal: true,
buttons: {
"Save timelines": function() {
editSavedTimelines();
saveTimelines();
$(this).dialog("close");
location.reload();
},
Cancel: function() {
$(this).dialog("close");
}
}
});
}
2 Setting up a callback:
function genSaveTimelinesModal() {
$("#saveTimelineDialog").dialog({
resizable: false,
height: 250,
modal: true,
buttons: {
"Save timelines": function() {
editSavedTimelines(saveTimelines());
location.reload();
},
Cancel: function() {
$(this).dialog("close");
}
}
});
}
3 Using JQuery $.when().do():
function genSaveTimelinesModal() {
$("#saveTimelineDialog").dialog({
resizable: false,
height: 250,
modal: true,
buttons: {
"Save timelines": function() {
$.when(editSavedTimelines(), saveTimelines()).do(location.reload());
},
Cancel: function() {
$(this).dialog("close");
}
}
});
}
My issue, on all three attempts, comes about when the "Save Timelines" button is clicked... the page reloads and none of the functions are run. When I pull the location.reload() call out of each example, the functions run as I want them.
Is there a way to reload the page ONLY AFTER the functions are completed?
For reference, here are the functions I'm calling:
function saveTimelines() {
console.log("start save");
for (i=1; i < timelineIndex + 1; i++) {
var dow = startdow;
var clientValue = $("#clientNameSelect" + i).val();
var projectValue = $("#projectSelect" + i).val();
var taskValue = $("#taskSelect" + i).val();
var billingValue = $("#billingSelect" + i).val();
var activityValue = $("#activitySelect" + i).val();
var stateValue = $("#states" + i).val();
var sundayValue = $("#sun" + i).val();
var mondayValue = $("#mon" + i).val();
var tuesdayValue = $("#tue" + i).val();
var wednesdayValue = $("#wed" + i).val();
var thursdayValue = $("#thu" + i).val();
var fridayValue = $("#fri" + i).val();
var saturdayValue = $("#sat" + i).val();
$.ajax({
type: "GET",
url:"biqqyzqyr?act=API_DoQuery&query={'6'.EX.'" + projectValue + "'}AND{'16'.TV.'" + currUserEmail + "'}&clist=3&includeRids=1&fmt=structured",
dataType: "xml",
success: function (xml) {
$(xml).find("record").each(function () {
var resourceMap = new Array();
$(this).children().each(function () {
var name = $(this).attr("id");
var value = $(this).text();
resourceMap[name] = value;
});
resourceRecords.push(resourceMap);
});
console.log("hi");
var resourceRId = '3';
for (var j = 0; j < resourceRecords.length; j++) {
resourceOptions = resourceRecords[j][resourceRId];
console.log(resourceOptions);
}
$.ajax({
type: "GET",
url: "biha4iayz?act=API_AddRecord&_fid_12=" + dow + "&_fid_36=" + clientValue + "&_fid_9=" + projectValue + "&_fid_7=" + taskValue + "&_fid_10=" + billingValue + "&_fid_15=" + activityValue + "&_fid_11=" + stateValue + "&_fid_13=" + sundayValue + "&_fid_57=" + mondayValue + "&_fid_58=" + tuesdayValue + "&_fid_59=" + wednesdayValue + "&_fid_60=" + thursdayValue + "&_fid_61=" + fridayValue + "&_fid_62=" + saturdayValue + "&_fid_17=" + resourceOptions,
dataType: "xml",
success: function () {
console.log(i+ "new")
},
fail: loadFail
});
},
fail: loadFail
});
}
alert(timelineIndex+savedTimelineIndex+" timelines have been saved to the system...");
}
function editSavedTimelines(callback) {
console.log("start edit");
for (j=1; j < savedTimelineIndex + 1; j++) {
var dow = startdow;
var savedRId = $("#recordsaved" + j).val();
var sundayValue = $("#sunsaved" + j).val();
var mondayValue = $("#monsaved" + j).val();
var tuesdayValue = $("#tuesaved" + j).val();
var wednesdayValue = $("#wedsaved" + j).val();
var thursdayValue = $("#thusaved" + j).val();
var fridayValue = $("#frisaved" + j).val();
var saturdayValue = $("#satsaved" + j).val();
console.log(savedRId);
$.ajax({
type: "GET",
url: "biha4iayz?act=API_EditRecord&rid=" + savedRId + "&_fid_13=" + sundayValue + "&_fid_57=" + mondayValue + "&_fid_58=" + tuesdayValue + "&_fid_59=" + wednesdayValue + "&_fid_60=" + thursdayValue + "&_fid_61=" + fridayValue + "&_fid_62=" + saturdayValue,
dataType: "xml",
success: function () {
},
fail: loadFail
});
}
}
The problem with your usage of when is that both of your functions don't return anything. Your call essentially amounts to this:
$.when(undefined, undefined)
Your saveTimelines function is the more complicated function because you make a 2nd ajax call in the callback of the first. And to make matters even worse, these ajax calls are in a loop. So your function isn't "complete" until the inner ajax calls for each iteration of the loop are complete.
I would strongly suggest trying to completely redesign this to simplify things. If you can eliminate the loop as well as the nested ajax calls, this would be much easier.
That being said, lets look at how we could overcome this issue. First to deal with the issue of the inner ajax call, you can solve this by creating your own deferred object. Something like this (ignoring the loop for the moment):
function saveOneTimeline(/* any params here, such as i */) {
// create a deferred object which will be returned by this function and resolved once all calls are complete
var def = $.Deferred();
/* ... */
$.ajax({
/* ... */
success: function (xml) {
/* ... */
$.ajax({
/* ... */
success: function () {
// we are done, resolve the deferred object
def.resolve();
}
});
}
});
// return the deferred object so that the calling code can attach callbacks/use when
return def;
}
Then finally, our previous method can be called in a loop, placing the returned deferred objects into an array and then using when to return a promise that will only resolve once all of the deferreds resolve. It would look something like this:
function saveTimelines() {
// an array to store all of the deferreds
var defs = [];
for (i=1; i < timelineIndex + 1; i++) {
defs.push(saveOneTimeline(i));
}
// call when on the array of deferred objects and return the resulting promise object
return $.when.apply($, defs);
}
Your editSavedTimelines is slightly less complex due to the fact that you don't have nested ajax calls. However, you still have a loop. A very similar approach can be used, except the helper function can simply return the object returned by the ajax call directly.
As you can see, this all very complex. It would probably be a much better idea to instead try to eliminate some of your complexity to avoid having to go to these lengths. Perhaps if you can make one bulk ajax call instead of many in a loop then allow the backend code to handle the separation.
This should work for you. It uses an array of Deferred objects for the for ajax calls in for loops, and has one final deferred object for when all of those are complete. The outer function listens for completion of those deferred objects. Note that I have snipped a lot of code that isn't relevant, and changed from success callbacks to .done() for your ajax calls.
function genSaveTimelinesModal() {
$("#saveTimelineDialog").dialog({
resizable: false,
height: 250,
modal: true,
buttons: {
"Save timelines": function() {
$.when(editSavedTimelines(), saveTimelines()).done(function() {
location.reload();
});
},
Cancel: function() {
$(this).dialog("close");
}
}
});
}
function saveTimelines() {
var finalDef = $.Deferred();
var defs = [];
for (i=1; i < timelineIndex + 1; i++) {
var def = $.Deferred();
defs.push(def);
$.ajax({...}).done(function(xml) {
$.ajax({...}).done(function() {
def.resolve(true);
});
});
}
$.when.apply(null, defs).done(function() {
finalDef.resolve();
});
return finalDef.promise();
}
function editSavedTimelines() {
var finalDef = $.Deferred();
var defs = [];
for (j=1; j < savedTimelineIndex + 1; j++) {
var def = $.Deferred();
defs.push(def);
$.ajax({...}).done(function() {
def.resolve(true);
});
}
$.when.apply(null, defs).done(function() {
finalDef.resolve(true);
});
return finalDef.promise();
}
var refreshId = setInterval(function() {
$('#livelist').load('/scripts/livelist.php', { guestlist:'<?php echo $_GET['guestlist']; ?>'});
}, 5000);
$.ajaxSetup({ cache: false });
I know I need to attach the .live() event handler to prevent the function from triggering other events (what's currently happening), but where do I add it?
Full Script:
$(document).ready(function() {
$("input#name").select().focus();
$('#livelist').load('/scripts/livelist.php', { guestlist:'<?php echo $_GET['guestlist']; ?>'});
var refreshId = setInterval(function() {
$('#livelist').load('/scripts/livelist.php', { guestlist:'<?php echo $_GET['guestlist']; ?>'});
}, 5000);
$.ajaxSetup({ cache: false });
$("input#name").swearFilter({words:'bob, dan', mask:"!", sensor:"normal"});
var tagCheckRE = new RegExp("(\\w+)(\\s+)(\\w+)");
jQuery.validator.addMethod("tagcheck", function(value, element) {
return tagCheckRE.test(value);
}, "");
$("#addname").validate({
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
$('#naughty').fadeIn('fast');
$('#naughty').delay('1000').fadeOut('fast');
} else {
$('#naughty').hide();
}
}
});
$('#showall').live('click', function() {
$('#showall').hide();
$('div#shownames').slideDown('fast');
});
jQuery(document).ajaxStart(function(){
$("input#name").blur();
$('#working').show();
$('#event-box').fadeTo('fast', 0.5);
})
var names = '';
var dot = '.';
$('#addname').ajaxForm(function() {
var options = {
success: function(html) {
/* $("#showdata").replaceWith($('#showdata', $(html))) */
var value = $("input#name").val().toUpperCase();;
$("span.success").text(value);
if (names == '') {
names = value;
}
else {
names = ' ' + value + ', ' + names;
$("span#dot").text(dot);
}
$("span#name1").text(names);
$('#working').fadeOut('fast');
$('#success').fadeIn('fast');
$('#added-names').fadeIn('fast');
$('#success').delay('600').fadeOut('fast');
$("input#name").delay('1200').select().focus();
$('#event-box').delay('600').fadeTo('fast', 1.0);
$(':input','#addname')
.not(':button, :submit, :reset, :hidden')
.val('')
},
cache: true,
error: function(x, t, m) {
if(t==="timeout") {
$('#working').fadeOut('fast');
$('#fail').fadeIn('fast');
$('#fail').delay('600').fadeOut('fast');
} else {
$('#working').fadeOut('fast');
$('#fail').fadeIn('fast');
$('#fail').delay('600').fadeOut('fast');
alert(t);
}
}
}
$(this).ajaxSubmit(options);
$('body').select().focus();
});
$("input").bind("keydown", function(event) {
var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
if (keycode == 13) {
document.getElementById('#submit').click();
return false;
} else {
return true;
}
});
});
The ajaxForm function is being triggered using my current implementation.
The fault:
jQuery(document).ajaxStart(function(){
$("input#name").blur();
$('#working').show();
$('#event-box').fadeTo('fast', 0.5);
})
As .ajaxStart() is a global parameter, it was being triggered during every AJAX call, including .load(), I'm surprised no one spotted it.