jQuery dropdown not firing the delete button - javascript

In my small practice project, I have a dropdown with a delete button:
function getMessages() {
$.ajax({
type: "POST",
url: "/Message/GetMessageMethod",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function(data) {
var jsonData = $.parseJSON(data);
var newHtml = "<table style='width: 100%;'class='table-hover'><tr><th>Message</th><th>Date Posted</th><th>Posted by</th></tr>";
for (var i = 0; i < jsonData.length; i++) {
newHtml += "<tr><td>" + jsonData[i].message + "</td><td>" + jsonData[i].date + " - " + jsonData[i].time + "</td><td>" + jsonData[i].name + "</td><td><div class='btn-group'>"+
"<a class='btn dropdown-toggle' data-toggle='dropdown' href='#'> Actions " +
"<span class='caret'></span></a>" +
"<ul class='dropdown-menu' role='menu'>" +
"<li role='presentation'><input type='button' role='menuitem' value='Delete' class='btn btn-danger delMsg'/></li>" +
"</ul></div></td></tr>";
}
newHtml += "<table>";
$('#txfMessage').html(newHtml);
}
});
};
But my delete button is not firing when I click on it... I have a break point in firebug, but its not reaching it...
$('.delMsg').on('click', function () {
$.ajax({
type: "POST",
url: "/Message/DeleteMessage",
contenetType: "application/json; charset=utf-8",
datatype: "json",
cache: false,
data: JSON.stringify({
id: $('#txfMessage').val()
}),
success: function() {
getMessages();
}
});
});
What could be I doing wrong, I've been busy with this since yesterday but couldn't find anything... Help please!
Thank you in advance!

You need to use jQuery event delegation, because you are attempting to attach an event to an element which does not yet exist in the DOM.
Change:
$('.delMsg').on('click', function () {
to:
$(document).on('click', '.delMsg', function () {
Check out this link for more information.

Since the delete button is created AFTER the AJAX call, your "on" method does not attach the event to it. You may use the live method. It will account for elements created after the method is attached.
EDIT: By the way, this depends on the JQuery version. live still works. If you have to use on, use it correctly, like pointed out by Pierre Granger and Jamie Dunstan.

You have to do something like:
$('#txfMessage').html(newHtml);
$('.delMsg').on('click', function () {
$.ajax({
type: "POST",
url: "/Message/DeleteMessage",
contenetType: "application/json; charset=utf-8",
datatype: "json",
cache: false,
data: JSON.stringify({
id: $('#txfMessage').val()
}),
success: function() {
getMessages();
}
});
});
i.e. bind each time you append new html elements, or use event delegation as in the other answers.

Related

Unable to display results using jquery ajax

I am trying to implement a comment feature on my page. I have an itemID 123. on that page, I would like to display the comments that people have posted about itemID 123. However as of now, I am unable to display these comments on my page. There are no errors in the console.
Javascript:
function mywall() {
var url = serverURL() + "/viewwall.php"; //execute viewwall.php in the server
itemID = decodeURIComponent(getUrlVars()["itemID"]);
var JSONObject = {
"itemID": decodeURIComponent(getUrlVars()["itemID"])
};
$.ajax({
url: url,
type: 'GET',
data: JSONObject,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_mywallresult(arr); //success. execute _mywallresult()
},
error: function () {
validationMsg();
}
});
}
function _mywallresult(arr) {
var i;
//for all the shouts returned by the server
for (i = 0; i < arr.length; i++) {
//append the following:
//<b>
//time of posting </b>
//<br/>
//the message
//<br>
//userid
$("#wallcontentset").append("<b>" + arr[i].timeofposting + "</b><br/>" + arr[i].message + "<hr>" + arr[i].userid);
}
}
HTML:
<div data-role="content" class="ui-content" id="wallcontentset"></div>
Try the following :
success: function (response) {
_mywallresult(response.arr);
},

Ajax never calls my .NET method?

Hi I have the following AJAX which references a method in my .aspx page. I've done some console debugging and my data.d is always undefined. So I've put a breakpoint in the .aspx page on the first line of the method referenced and it never hits it.
I'm really stuck - so if someone could point me in the right direction that would be great.
AJAX:
var param = { "mySearchString": str };
$.ajax({
type: 'POST',
url: 'myForm.aspx/myMethod',
data: JSON.stringify(param),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function (data) {
$("#MyResults").empty();
console.log(data);
console.log(data.d);
console.log(data.d.length);
for (i = 0; i < data.d.length; i++) {
$("#MyResults").append("<li><a href='#' onClick='SetName(this)'>" + data.d[i].title + "</" + " a>" + "</" + "li>");
}
if (data.d.length == 0)
{
$("#MyResults").empty();
}
}
});
The initial set up for my .NET method:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod(EnableSession = true)]
public static IEnumerable<MyItem> myMethod(string searchString)
{
I'm passing the right type across, and there are no errors on build or when I run it. So I'm a bit stumped!
Add this to your ajax call to see more about the error:
error: function (request, status, error) {
alert('Error: ' + error);
}
Is this an MVC application? Should the url actually be myForm.aspx/myMethod or just myForm/myMethod? What I am getting at is have you ever hit a breakpoint on the server side and is the path correct?
Try adding this as part of the signature
[HttpPost]
You can add the below attribute to the class, which enables the web method to be called from an ajax script.
[System.Web.Script.Services.ScriptService]
you have
var param = { "mySearchString": str };
but the parameter in you Method is
public static IEnumerable<MyItem> myMethod(string searchString)
Both parameters should have the same name.
You're passing a string as parameter, you should pass an object with a string attribute named searchString:
var param = { "mySearchString": str };
$.ajax({
type: 'POST',
url: 'myForm.aspx/myMethod',
data: param,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function (data) {
$("#MyResults").empty();
console.log(data);
console.log(data.d);
console.log(data.d.length);
for (i = 0; i < data.d.length; i++) {
$("#MyResults").append("<li><a href='#' onClick='SetName(this)'>" + data.d[i].title + "</" + " a>" + "</" + "li>");
}
if (data.d.length == 0)
$("#MyResults").empty();
}
});
kindly remove the following properties, and remove the JSON.stringfy
contentType: 'application/json; charset=utf-8',
dataType: 'json',
and kindly don't remove the async because it will freeze your UI if you set it to false.
you can do it like this:
$.ajax({
type: 'POST',
url: 'myForm.aspx/myMethod',
data: param,
success: function (data) {
$("#MyResults").empty();
console.log(data);
console.log(data.d);
console.log(data.d.length);
for (i = 0; i < data.d.length; i++) {
$("#MyResults").append("<li><a href='#' onClick='SetName(this)'>" + data.d[i].title + "</" + " a>" + "</" + "li>");
}
if (data.d.length == 0)
{
$("#MyResults").empty();
}
}
});
I found my answer here: ASP.NET Calling WebMethod with jQuery AJAX "401 (Unauthorized)"
I was hitting this error:
Object {Message: Ajax error: "Authentication failed.", StackTrace:
null, ExceptionType: "System.InvalidOperationException"}
Turns out that I needed to do:
Inside ~/App_Start/RouteConfig.cs change:
settings.AutoRedirectMode = RedirectMode.Permanent;
To:
settings.AutoRedirectMode = RedirectMode.Off;
Hopefully this will help someone else!

How to correctly post data with ajax into div?

Script:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").ajax({
type: "POST",
url: "BlockEditor/build.php",
data: 'block_id=' + id + '&building=' + building + '&nick=' + nick,
cache: false,
success: function(response)
{
alert("Record successfully updated");
$.load("#BuildedBox")
}
});
}
build.php:
include_once("$_SERVER[DOCUMENT_ROOT]/db.php");
$block_id = $_GET['block'];
$building = $_GET['building'];
$nick = $_GET['nick'];
echo"$block_id - $building - $nick";
index.php:
<a href=\"#\" onClick=\"buttonBuild(k152, digger, Name);\" >[BUILD]</a>
<div id="BuildedBox"></div>
seems my script wont work. what i have done wrong?
check this out
function buttonBuild(id, building, nick)
{
$.ajax({
type: "POST",
url: "BlockEditor/build.php",
data: 'block_id=' + id + '&building=' + building + '&nick=' + nick,
cache: false,
success: function(response)
{
alert("Record successfully updated");
/***************/
$("#BuildedBox").html(response);
/***************/
}
});
}
var weightd = $("#weight").val();
var user_id = 43;
$.ajax({
type: "POST",
url:"<?php bloginfo('template_directory')?>/ajax/insert.php",
data: { weight:weightd,user_ids:user_id},
success:function(result){
$("#result1").html(result);
});
<div id="result1">Result div</div>
change $.load("#BuildedBox") to $("#BulderBox").html(response).
When you ask the script for data via ajax, the data provided gets into the "response" variable. As you want to write this data into the div, you must use the ".html" method.
Easier using "load" in this way:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").load("BlockEditor/build.php?block_id=" + id + "&building=" + building + "&nick=" + nick);
}
The "load" method loads data from the server and writes the result html into the element: https://api.jquery.com/load/
EDIT:
As #a-wolff says in the comment, to use POST in load, you should construct like this:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").load("BlockEditor/build.php",{
block_id:id,
building:building,
nick:nick
});
}

ajax doesn't update on first click

I have a problem with my code, it's a like button. It shows the number of likes. If user haven't voted yet (cookie) he can click and counter increases. Problem is counter doesn't update on first click (if i deactivate cookie check and vote several times) on next refresh is everything updated. It seems some count happens before insert in the backend. I suppose probem is in JavaScript, ajax post cross domain works but gives error that's why "error: setCookieAndUpdateButton()"
here is my frontend code:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<div><a id="like_button" href="#">Like</a></div>
<script>
var url = "http://thumbs-up.some-server.com/";
var appName = "next_test";
document.write("<script src=\"" + url + "jquery.cookie.js\"><\/script>");
$(document).ready(function(){
updateButton();
$("#like_button").click(function(){
if ($.cookie(appName + "_voted") == "true") {return;}
$.ajax({
type: "POST",
dataType: "json",
crossDomain: true,
url: url + "increase_counter.php",
data: {referrer: appName},
success: setCookieAndUpdateButton(),
error: setCookieAndUpdateButton()
});
});
});
function setCookieAndUpdateButton()
{
updateButton();
$.cookie(appName + "_voted", "true", {expires: 20*365});
}
function updateButton()
{
$.ajax({
type: "GET",
async: false,
contentType: "application/json",
dataType: "jsonp",
jsonpCallback: 'callback4jquery',
url: url + "get_counter_for_referrer.php",
data: {referrer: appName},
success: function (json) {
if ($.cookie(appName + "_voted") != "true"){
$("#like_button").html("<a id=\"like_button\" href=\"#\"><img src=\"" + url + "like.png\">Good to know " + json.count + "x</a>")
}
else{
$("#like_button").html("<span id=\"like_button\"><img src=\"" + url + "like.png\">Good to know " + json.count + "x</span>");
$('#like_button').unbind('click');
}
}
});
}
</script>
In first ajax call change your code like this:
success: setCookieAndUpdateButton,
error: setCookieAndUpdateButton
without () in both of them

jQuery Live() doesn't work

Hi from some reason my live() function doesn't work.
i want to add a mew li element with click functionality by clicking on li element inside the ulAllApps. a new li element created inside the ulMyApps but without the click functionality.
HTML:
<div class="MyApps" >
<ul class="ulMyApps">
<li class="MYLinkTR">app1</li>
</ul>
</div>
<div class="AllApps">
<ul class="ulAllApps">
<li class="IECLinkTR">app1</li>
<li class="IECLinkTR">app2</li>
</ul>
</div>
jQuery code:
$(document).ready(function () {
$(".IECLinkTR").click(function () {
var tmp = $(this).html();
$.ajax({
type: "POST",
url: window.location.href+"/addToMyLinks",
data: "{'app': '" + tmp + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$(".ulMyApps").append("<li class=\"MYLinkTR\">"+ tmp +"</li>");
},
error: function (msg) {
alert("You have already have that app");
}
});
});
$(".MYLinkTR").live('click', function () {
var tmp = $(this);
$.ajax({
type: "POST",
url: window.location.href + "/removeFromMyLinks",
data: "{'app': '" + $(this).html() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
tmp.closest('li').remove();
},
error: function (msg) {
}
});
});
});
from some reason the new li element created dynamically dont have the CLICK functionality coming from the Live function......
All I can see is that on your MYLinkTR click function you are trying to remove the tmp.closest('li'). Now looking at the docs I think closest is moving up the DOM looking for the closest next ('li') rather then the one it is on. Are you sure you don't want tmp.remove()?
Perhaps seeing if an alert is thrown first on the click to see if it is firing as you don't do anything on error. Something might be happening here that you are not aware of. The other options is changing LIVE to delegate and attaching this to the ul and see if this fires
$('ul.MyApps').delegate('li', 'click', function(e){
alert('does this at least fire');
});

Categories