Problem with jquery live method - event-handling

I have something like wall posts which have the option of 'remove'. Since posts can be added any time hence I'm using jquery live method for event handling.
The problem is, multiple events are getting attached to 'remove' on click event
$(document).ready(function(){
$('.actions .remove_wall_post').live('click', function(){
var wall_post_id = $(this).attr('id');
var data = {
'action' : 'remove',
'wall_post_id' : wall_post_id
};
var url = myurl;
$.post(url, data, function(response){
if(response == '1'){
$('#post_list #'+wall_post_id).hide();
var total_posts = $('#total_posts').text();
} else{
alert('ERROR');
}
});
return false;
});
});
Suppose there are n posts, when I click on 'remove' of any post, the first event works fine...but after that i get n ERROR alerts and all events have the same wall_post_id

Related

ionic reload a page from another page/modal

EDIT
I noticed that the subscribe event must come first before and publish get called. But it will be silly to ask user to open TabOut page every time when app start.
I do not need to always reloading the TabOut page, so I need this event sort of method to do the job. Or else could've just call the reload on ionViewDidEnter().
I have 2 Tabs and 1 modal. /TabIn, /TabOut, and /ModalIn.
The Tabs page serve as data listing which display the data from database on ionViewDidLoad().
The ModalIn page serve as data entry for the user to key in and submit data. This page resides in the TabIn page and will get called when user clicked on each of the list of data.
After successfully submit the form in the ModalIn page I want to call refresh again on the TabOut page (no matter it has been loaded before or not). I tried using events publish it is not working. Below are my code.
ModalIn .ts
let headers: any = new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }),
options: any = { "username": val, formValue },
url: any = "some_url_here";
this.http.post(url, options, headers)
.subscribe((data: any) => {
if (data.status == 'success') {
this.events.publish('shouldReloadData');
} else {
}
},
(error: any) => {
console.log(error);
});
TabOut .ts
constructor(public events: Events) {
events.subscribe('shouldReloadData', () => {
// Reload the page here
console.log("should reloadddd"); // <- This is not working
});
}
Call subscribe with this keyword inside TabOut.ts.
constructor(public events: Events) {
this.events.subscribe('shouldReloadData', () => {
});
}

How do I know that I'm still on the correct page when an async callback returns?

I'm building a Metro app using the single-page navigation model. On one of my pages I start an async ajax request that fetches some information. When the request returns I want to insert the received information into the displayed page.
For example:
WinJS.UI.Pages.define("/showstuff.html", {
processed: function (element, options) {
WinJS.xhr(...).done(function (result) {
element.querySelector('#target').innerText = result.responseText;
});
}
};
But how do I know that the user hasn't navigated away from the page in the meantime? It doesn't make sense to try to insert the text on a different page, so how can I make sure that the page that was loading when the request started is still active?
You can compare the pages URI with the current WinJS.Navigation.location to check if you are still on the page. You can use Windows.Foundation.Uri to pull the path from the pages URI to do this.
WinJS.UI.Pages.define("/showstuff.html", {
processed: function (element, options) {
var page = this;
WinJS.xhr(...).done(function (result) {
if (new Windows.Foundation.Uri(page.uri).path !== WinJS.Navigation.location)
return;
element.querySelector('#target').innerText = result.responseText;
});
}
};
I couldn't find an official way to do this, so I implemented a workaround.
WinJS.Navigation provides events that are fired on navigation. I used the navigating event to build a simple class that keeps track of page views:
var PageViewManager = WinJS.Class.define(
function () {
this.current = 0;
WinJS.Navigation.addEventListener('navigating',
this._handleNavigating.bind(this));
}, {
_handleNavigating: function (eventInfo) {
this.current++;
}
});
Application.pageViews = new PageViewManager();
The class increments a counter each time the user starts a new navigation.
With that counter, the Ajax request can check if any navigation occurred and react accordingly:
WinJS.UI.Pages.define("/showstuff.html", {
processed: function (element, options) {
var pageview = Application.pageViews.current;
WinJS.xhr(...).done(function (result) {
if (Application.pageViews.current != pageview)
return;
element.querySelector('#target').innerText = result.responseText;
});
}
};

Re-POST-ing a form using Ajax, for back/fwd history, in jQuery Mobile

I'm investigating the suitability of the jQM history management for my organization's mobile web site. Part of our requirement is that when a user posts a form, it posts using Ajax. When a user taps "back" and then "forward" browser buttons, we need to re-post the form using Ajax again. Here's a diagram:
[home.php: post to new.php] =>
[new.php: post to list.php] =>
[from list.php, click back twice to home.php] =>
[* home.php: click fwd, does a GET request to new.php *] =>
[* new.php: click fwd, does a GET request to list.php *]
[*] not the behavior I want. I want to re-POST data from steps 1 and 2
During steps 4 and 5, I want to intercept the jQM execution at the "pagebeforeload" event (seems like the right place), and modify the data.options.data (to include the serialized post data) and data.options.type (to POST) properties of the data object which is passed to the event handler. Then I'd let the pageload process move on with the modified values. This, I think, would give me the behavior I want.
So far, I see that I can intercept the pagebeforeload event and modify the values with the below event handler:
$(document).bind("pagebeforeload",
function( e, data ) {
console.log(data.toPage);
console.log(data.options);
data.options.type = "POST";
data.options.data = "edit=Hanford";
}
);
But the missing piece is, how can I "store" the information in steps 1 and 2, such that when I intercept the pagebeforeload event in 4 and 5, I can know to modify the "type" and "data" properties properly.
I've made a jquery/browser History prototype to illustrate the behavior I would like to get from jQuery Mobile. The JavaScript is:
$(window).load(function() {
//listen to the history popstate event
$(window).bind('popstate',
function(e) {
if (e.originalEvent.state && e.originalEvent.state.type && e.originalEvent.state.type == "post") {
//do an ajax post based on what is stored in history state
$.post(e.originalEvent.state.path,
e.originalEvent.state.data,
function(data) {jaxer(data,'POST')});
} else if (e.originalEvent.state !== undefined){
//do an ajax get
$.get(location.pathname,
function(data) {jaxer(data,'GET')});
}
});
//add event listeners
addClickHandler();
});
function jaxer(data, msg) {
if (msg) {console.log(msg+' request made using ajax');}
$('#slider')[0].innerHTML = data;
addClickHandler();
}
//hijax hyperlinks and form submissions
function addClickHandler() {
$('a').click(function(e) {
history.pushState({
path: this.path
},
'', this.href);
$.get(this.href,
function(data) {jaxer(data,'GET')});
e.preventDefault()
});
$('form').submit(function(e) {
var formData = $(this).serialize();
console.log('saving serialized form data into historyState: '+formData);
history.pushState({path: this.action, data: formData, type: "post"},'',this.action);
$.post(this.action,
$(this).serialize(),
function(data) {jaxer(data,'POST')});
e.preventDefault();
});
//add the form submit button to the form as a hidden input such that it will get serialized
$('form input[type="submit"]').click(function() {
$(this.form).append("<input type='hidden' name='" + this.name + "' value='" + this.value + "'/>");
});
console.log("event handlers added to DOM");
};
When a user-initiated POST occurs, I put the serialized POST data into the history's state object. Then, when a popstate event occurs, I can query the state object for this information. If I find it, then I can perform an ajax POST. I would like to get the same functionality within the jQuery Mobile history handling. That way I can take advantage of the page change animations, etc.

Unlike event similar to edge.create

Via the Facebook javascript API, you can subscribe to the 'event.create' event to listen for when users "Like" something on a page via the Like Plugin. Is it possible to respond to the same user un-liking it as well? I don't see any events documented, wondering if this is a hidden feature.
You can now subscribe to the “edge.remove" event to know when a user unlikes a page. For example:
FB.Event.subscribe('edge.remove', function(href, widget) {
alert('You just unliked '+href);
});
Announcement: http://developers.facebook.com/blog/post/446/ documented at http://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe
Recently added:
http://bugs.developers.facebook.net/show_bug.cgi?id=10796
The javascript sdk does not have an event for this. I have run into this problem before. The only way to check if a user has unliked an item is to do a Graph or Rest query to determine if they currently like the item.
Unfortunately "edge.remove" won't get triggered when you dislike a facebook-page via "liked"-button (on the top right) and click on "unlike". -.-
This event is very useful to create a vote system. The js-script below does an ajax-call to a PHP-page that updates a database.
var _paq = _paq || [];
FB.Event.subscribe('edge.create', function(response) {
var page = $("#pageid").val();
$.post("ajax_vote.php", { page: page },
function(data) {
//alert("voted : " + data);
});
});
FB.Event.subscribe('edge.remove', function(response) {
var page = $("#pageid").val();
$.post("ajax_unvote.php", { page: page },
function(data) {
//alert("unvoted : " + data);
});
});

Jeditable CANCEL callback from AJAX callback?

I see some answers for the Jeditable plugin to use a callback function from AJAX using complete callback function.
I know that the Jeditable has a callback function for the SUBMIT button, so I would like to know if there is a way to have a callback for the CANCEL button? I haven't found on the plugin docs.
Thanks for reply,
Carlos
PD. This is the source I see for COMPLETE from AJAX callback:
$("#editable_text").editable(submitEdit, {
indicator : "Saving...",
tooltip : "Click to edit...",
name : "Editable.FieldName",
id : "elementid",
type : "text",
});
function submitEdit(value, settings)
{
var edits = new Object();
var origvalue = this.revert;
var textbox = this;
var result = value;
edits[settings.name] = [value];
var returned = $.ajax({
url: "http://URLTOPOSTTO",
type: "POST",
data : edits,
dataType : "json",
complete : function (xhr, textStatus)
{
var response = $.secureEvalJSON(xhr.responseText);
if (response.Message != "")
{
alert(Message);
}
}
});
return(result);
}
Yes, there is a "onreset" parameter that is called when clicking cancel, or more generally, before jEditable resets the control back to the state before it was clicked. Add this to your code:
$("#editable_text").editable(submitEdit, {
//...
onreset: jeditableReset,
//...
});
function jeditableReset(settings, original) {
// whatever you need to do here
}
This is documented in the header of the jquery.jeditable.js file.
Another note - if you don't submit on blur (you don't appear to be in the sample), the onreset event will fire then too.