Javascript module parttern ajax - javascript

I am learning javascript design patterns. So am converting my rough jquery code into cleaner module pattern. The question is, how will i call a click event after ajax has loaded in module pattern (Object literal). I used to solve it using $(document).ajaxcomplete(callback).
here is the working supergetti code
$('.meidaBtn, #media_load_btn').on('click', function(event) {
event.preventDefault();
$('.media').show(500);
$('#mediaBox').html('Loading...');
var link = location.origin + '/dashboard/media';
$.ajax({
url: link
}).done(function(data) { // data what is sent back by the php page
$('#mediaBox').html(data); // display data
// Click through
$('.imageBox img').bind('click', function() {
var src = $(this).attr('src');
var alt = $(this).attr('alt');
src = src.replace('tumbnail_', '');
tinyMCE.execCommand('mceInsertContent', false, '<img src="' + src + '" alt="' + alt + '">');
$('.media').hide();
});
});
});
Here is the javascript module pattern / object literal
var mediaPlugin = {
init: function() {
this.cacheDom();
this.bindEvents();
},
// Cache Dom
cacheDom: function() {
this.baseUrl = location.origin + '/dashboard/media';
this.$button = $('.meidaBtn, #media_load_btn');
this.$media = $('.media');
this.$mediaBox = $('#mediaBox');
this.$imageBox = $('.imageBox img');
},
// Bind Events
bindEvents: function() {
this.$button.on('click', this.render.bind(this));
this.$imageBox.on('click', this.addImage.bind(this));
},
// Show Data
render: function(e) {
e.preventDefault();
this.$media.show(500);
this.loadData();
},
// Load the data
loadData: function() {
var that = this;
$.ajax({
url: this.baseUrl,
type: 'GET',
success: function(data) {
// console.log(that.$mediaBox);
that.$mediaBox.html(data);
},
error: function() {
console.log("An error occored!");
},
complete: function() {
// console.log("I am now complete");
// that.loadMore();
}
});
},
// Add Image
addImage: function() {
var src = $(this).attr('src');
var alt = $(this).attr('alt');
src = src.replace('tumbnail_', '');
tinyMCE.execCommand('mceInsertContent', false, '<img src="' + src + '" alt="' + alt + '">');
this.$media.hide();
}
};
mediaPlugin.init();

The method provided below adds a simple property to the object which is used as a delegate/callback. You simply point your function to it and then it is called automatically since it is called in the complete event.
var mediaPlugin = {
init: function() {
this.cacheDom();
this.bindEvents();
},
// Cache Dom
cacheDom: function() {
this.baseUrl = location.origin + '/dashboard/media';
this.$button = $('.meidaBtn, #media_load_btn');
this.$media = $('.media');
this.$mediaBox = $('#mediaBox');
this.$imageBox = $('.imageBox img');
},
// Bind Events
bindEvents: function() {
this.$button.on('click', this.render.bind(this));
this.$imageBox.on('click', this.addImage.bind(this));
},
// Show Data
render: function(e) {
e.preventDefault();
this.$media.show(500);
this.loadData();
},
loadDataComplete: function() {},
// Load the data
loadData: function() {
var that = this;
$.ajax({
url: this.baseUrl,
type: 'GET',
success: function(data) {
// console.log(that.$mediaBox);
that.$mediaBox.html(data);
},
error: function() {
console.log("An error occored!");
},
complete: function() {
// console.log("I am now complete");
// that.loadMore();
that.loadDataComplete();
}
});
},
// Add Image
addImage: function() {
var src = $(this).attr('src');
var alt = $(this).attr('alt');
src = src.replace('tumbnail_', '');
tinyMCE.execCommand('mceInsertContent', false, '<img src="' + src + '" alt="' + alt + '">');
this.$media.hide();
}
};
var myCompleteFunction = function myCompleteFunction() {}
mediaPlugin.init();
mediaPlugin.loadDataComplete = myCompleteFunction;
mediaPlugin.loadData();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I finally figured how to get this code working. I used jquery .delegate() and i now work like magic. Below is the working code. thanks #abc123 for stoping by.
var media = (function(){
// Cache dom
var baseUrl = location.origin+'/dashboard/media';
var $button = $('.meidaBtn, #media_load_btn');
var $media = $('.media');
var $mediaBox = $('#mediaBox');
var $imageBox = $mediaBox.find('img');
var options = {
url: baseUrl,
type: 'GET',
success: function(data){
$mediaBox.html(data);
},
error: function(){
console.log("An error occored!");
},
complete: function(){
// console.log("I am now complete");
// that.loadMore();
}
};
// Bind Events
$button.on('click', _render);
$mediaBox.delegate('.imageBox', 'click', _addImage);
function _render(e){
e.preventDefault();
$media.show(500);
_loadData();
}
// Load images
function _loadData(){
$.ajax(options);
}
// Add Images
function _addImage(){
img = $(this).find('img');
console.log(img.attr('src')); // This should display the image url
}
})();

Related

Why is my Ajax cannot save data into database? Laravel with Ajax

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>

when use click of item it not go to the JQ function

I update a version of all plugins, PHP, Jquery in my site
and now this code doesn't work.
when i go to this line :
$('#order_line_items .item .create-discount-for-item-'+ order_item_id).click();
it need go to this line:
$('body').on('click', this.selector, function(e)
but it no go there, and I don't have any errors
modalDiscountItem function:
$.fn.modalDiscountItem = function (options){
var settings = $.extend({
onChargeSuccess: false,
onChargeFailed: false,
orderId: 0,
order_item_id : false,
}, options);
var deferred = $.Deferred();
$('body').on('click', this.selector, function(e){
e.preventDefault();
var url = product_picker.ajax_url + "?action=discount_for_item";
url += "&order_id=" + settings.orderId;
url += "&order_item_id=" + settings.order_item_id;
url += "&TB_iframe=true&width=800&height=700";
tb_show("Discount for Item ", url);
icreditChargeModal.success = function(){
tb_remove();
deferred.resolve();
};
icreditChargeModal.failed = function(){
tb_remove();
deferred.fail()
}
});
return deferred;
}
anther function:
order_items_container.on('click', '.create-discount-for-item', function (e) {
var order_id = $('#post_ID').val();
var order_item_id = $(this).closest('tr.item').data('order_item_id');
if (!$('#order_line_items .item .create-discount-for-item-' + order_item_id).hasClass('active')) {
var deferred = $('#order_line_items .item .create-discount-for-item-' + order_item_id).modalDiscountItem({
orderId: order_id,
order_item_id: order_item_id
});
deferred.then(function () {
location.reload(true);
}, function () {
});
}
$('#order_line_items .item .create-discount-for-item-' + order_item_id).click();
$('#order_line_items .item .create-discount-for-item-' + order_item_id).addClass('active');
});
the output of $('#order_line_items .item .create-discount-for-item-' + order_item_id).length is 1

Attaching multiple events to single function in jQuery

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

Bypass Input FIle; Uploading Image directly using javascript

I'd like to automate the uploading of images to a website. The problem is I'm stuck at the input file type. The site seems to use a JQuery uploading method. I'd like to feed the script the image data directly satisfying validation.
Here's the HTML of the input file type used to upload images along with it's structure.
<div id="item_img_msg1" abp="568"></div>
<div class="mg_b5 mg_l10" id="item_img_empty1" abp="569">
<input name="updfile1" class=" " id="item_img_file1" type="file" abp="570">
</div>
<div class="mg_b5 mg_l10" id="item_img_selected1" style="display: none;" abp="571">
<img id="item_img1" src="/common/images/noimage.gif" abp="572">
<input id="item_img_del1" style="vertical-align: bottom;" type="button" value="Delete" abp="573">
</div>
<input name="hdnImgDelFlg1" id="imgdelflg1" type="hidden" value="" abp="574">
<span class="font_85 pg_l10" abp="575">(Sizeļ¼šUnder 1MB;Format:JPEG,GIF,PNG</span>
<br abp="576">
<span class="pg_l10" abp="577">Wide or Tall images will be chopped</span>
<div class="HelpTxt mg_t5" abp="578">
Guide:Image Upload Guide
</div>
And here's the related javascript.
var ImageUploader = function (idx) {
var postData = {
name: "updfile",
index: idx,
imgApiType: $("#img_api_type").val(),
unq: $("#unique_id").val(),
postCnt: 0
};
var deleteData = {
index: idx,
imgApiType: $("#img_api_type").val(),
unq: $("#unique_id").val(),
postCnt: 0
};
var onIamgeUploaded = function (response) {
var status = $(response).find("otoma_status").text();
if (status != "0") {
$("#item_img_msg" + idx).html("<div class='error_with_icon'>Upload Failed</div>");
return;
}
var url = $(response).find("img_url").text();
$("#item_img" + idx).attr("src", url + "?" + new Date().getTime());
$("#item_img_empty" + idx).hide();
$("#item_img_selected" + idx).show();
$("[name='hdnImgDelFlg" + idx + "']").val("0");
postData.postCnt++;
};
this.manualUpload = function (data) {
var postDataForManual = $.extend({}, postData, data);
jQuery.ajax({
data: postDataForManual,
url: "/api/itemimage/upload",
cache: false,
type: "post",
beforeSend: function (XMLHttpRequest) {
var loading_image_tag = $("<img>").attr({
"class": "js-loading_image" + idx,
src: Module.imgpath + "/lib/fileuploader/loading.gif"
});
$("#item_img_empty" + idx).after(loading_image_tag);
$("#item_img_empty" + idx).hide();
},
success: function (response) {
onIamgeUploaded(response);
},
error: function () {
$("#item_img_msg" + idx).html("<div class='error_with_icon'>Upload Failed!</div>");
$("#item_img_empty" + idx).show();
},
complete: function () {
$("img.js-loading_image" + idx).remove();
}
});
};
var init = function (idx) {
postData.index = idx;
try {
new AjaxUpload("#item_img_file" + idx, {
action: "/api/itemimage/upload",
name: "updfile",
data: postData,
onSubmit: function (file, extension) {
AjaxUtils.loading(true);
$("#item_img_msg" + idx).html("");
},
onComplete: function (file, response) {
AjaxUtils.loading(false);
onIamgeUploaded(response);
}
});
} catch (e) {}
$("#item_img_del" + idx).click(function () {
jQuery.ajax({
dateType: "xml",
data: deleteData,
url: "/api/itemimage/delete",
cache: false,
type: "post",
beforeSend: function (XMLHttpRequest) {
deleteData.postCnt = postData.postCnt;
$("#item_img_msg" + idx).html("");
$("#item_img_empty" + idx).show();
$("#item_img_selected" + idx).hide();
$("[name='hdnImgDelFlg" + idx + "']").val("1");
},
error: function () {
$("#item_img_msg" + idx).html("<div class='error_with_icon'>Upload Failed!</div>");
}
});
});
};
init(idx);
};
var ImageUploaders = [];
var maxImageNumber = $("#max_image_number").val();
for (var i = 1; i <= maxImageNumber; i++) {
ImageUploaders.push(new ImageUploader(i));
}
var params = Module.Utility.getParameters();
var buying_support_item_id = params.buying_support_item_id;
if (buying_support_item_id) {
ImageUploaders[0].manualUpload({
buying_support_item_id: buying_support_item_id
});
}
I can make javascript script calls to the webpage. I just basically need to know which calls to make. Does anyone know how to do this? If so, could you provide sample code.
Thanks!

jQuery add/removeClass & AJAX not working

I'm using Isotope with AJAX to pull in some posts in WordPress, pretty much everything is there, except for the default Isotope animation runs when I AJAX in content, which looks a bit weird. I still wanted it to animate when filtered though.
So I thought I could just use add/removeClass within my AJAX function to turn it off/on when needed, but if I do the animation never runs.
Any ideas where I'm going wrong here?
var page = 1;
var loading = true;
var $window = $(window);
var $content = $('.isotope');
if( $('body').hasClass('home') ) {
var loopHandler = '/inc/loop-handler.php';
} else {
var loopHandler = '/inc/loop-handler-archive.php';
}
var load_posts = function(){
$.ajax({
type : "GET",
data : {numPosts : 1, pageNumber: page},
dataType : "html",
url : templateDir+loopHandler,
beforeSend : function(){
if(page != 1){
$('.loader').append('<div id="temp_load" style="text-align:center; z-index:9999;">\
<img src="'+templateDir+'/img/ajax-loader.gif" />\
</div>');
}
},
success : function(data){
$data = $(data);
if($data.length){
var itemHeight = $('.item').height();
var height = $content.height()+itemHeight*2;
$content.append($data);
$content.css('min-height', height);
$data.hide();
// should stop the animation
$('.isotope').addClass('no-transition');
$content.isotope('destroy');
$content.imagesLoaded( function(){
$content.isotope({
// options
layoutMode: 'fitRows',
itemSelector : '.item'
});
});
$data.fadeIn(700, function(){
$("#temp_load").fadeOut(700).remove();
loading = false;
});
// should start up the animation again
$('.isotope').removeClass('no-transition');
$content.css('min-height', '0');
} else {
$("#temp_load").remove();
}
},
error : function(jqXHR, textStatus, errorThrown) {
$("#temp_load").remove();
alert(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
}
$window.scroll(function() {
var content_offset = $content.offset();
console.log(content_offset.top);
if(!loading && ($window.scrollTop() +
$window.height()) > ($content.scrollTop() +
$content.height() + content_offset.top)) {
loading = true;
page++;
load_posts();
}
});
load_posts();
If you need any of the HTML/PHP I'm happy to post it up. Also, here's the dev site if you want to check it out.
I don't know Isotope and I have not tested if it works. But I have refactor your code with annotations to help you better understand the problem.
I think it comes from how you call removeClass and addClass successively, the two instantly cancel.
var page = 1;
var loading = true;
var $window = $(window);
var $content = $('.isotope');
var loopHandler = '/inc/loop-handler.php';
var isotopeController = {
append: function($data) {
// Add AJAX data
var itemHeight = $('.item').height();
var height = $content.height() + itemHeight * 2;
$content.append($data);
$content.css('min-height', height);
// Stop
isotopeController.stop($data);
// Restart
$content.imagesLoaded(function() {
// When images loaded !
isotopeController.start($data);
});
},
start: function($data) {
// Start isotope
$content.isotope({
layoutMode: 'fitRows',
itemSelector: '.item'
});
// Show data
$data.fadeIn(700, function() {
$("#temp_load").fadeOut(700).remove();
loading = false;
});
// Start the animation
$content.removeClass('no-transition');
$content.css('min-height', '0');
},
stop: function($data) {
// Hide data
$data.hide();
// Stop the animation
$content.addClass('no-transition');
// Stop isotope
$content.isotope('destroy');
},
loadPosts: function() {
$.ajax({
type: "GET",
data: {
numPosts: 1,
pageNumber: page
},
dataType: "html",
url: templateDir + loopHandler,
beforeSend: function() {
if (page != 1) {
$('.loader').append('' +
'<div id="temp_load" style="text-align:center; z-index:9999;">' +
'<img src="' + templateDir + '/img/ajax-loader.gif" />' +
'</div>'
);
}
},
success: function(data) {
var $data = $(data);
if ($data.length) {
isotopeController.append($data);
} else {
$("#temp_load").remove();
}
},
error: function(jqXHR, textStatus, errorThrown) {
$("#temp_load").remove();
alert(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
}
};
$window.scroll(function() {
var content_offset = $content.offset();
if (!loading && ($window.scrollTop() + $window.height()) > ($content.scrollTop() + $content.height() + content_offset.top)) {
loading = true;
page++;
isotopeController.loadPosts();
}
});
// On load
$(function() {
if (!$('body').hasClass('home')) {
loopHandler = '/inc/loop-handler-archive.php';
}
isotopeController.loadPosts();
});

Categories