jQuery selector to handle click function inside a loop result - javascript

Sorry for asking this again but code won't execute. The problem is that I have a php loop that produces a html like below
<a class="js-delete-comment1" data-url="http://localhost/project/document_items/delete_item_comment/1">link</a>
<a class="js-delete-comment2" data-url="http://localhost/project/document_items/delete_item_comment/2">link</a>
<a class="js-delete-comment3" data-url="http://localhost/project/document_items/delete_item_comment/3">link</a>
Now, I want to select specific class to use as a jQuery selector but won't work. See below code
$("[id*=js-delete-comment]").each(function(){
$(this).click(function(){
var url = $('.js-delete-comment').attr('data-url');
// var id = $('.js-delete-comment').attr('data-id');
$.ajax({
url : url,
type : 'POST',
dataType : 'json',
success : function(result) {
console.log(result);
}
});
});
});
Any help would be much appreciated!

There is no ID on the elements, use class^= selector. There is no need of iterating over the elements and then bind the event, the event can be bind directly on the selector itself.
$("[class^='js-delete-comment']").click(function() {
Also, use $(this).data('url') to get the data-url attribute of the element that is clicked.
Code:
$("[class^='js-delete-comment']").click(function (e) {
e.preventDefault(); // To stop page redirection
var url = $(this).data('url');
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
success: function (result) {
console.log(result);
}
});
});

You can use,
$("[class^=js-delete-comment]").click(function() {
var url = $(this).data("url");
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
success: function(result) {
console.log(result);
}
});
});
^ is the attribute starts with selector. you can use that for selecting the class
Use data() method for getting the data-url

Just use click event like this:
$("[class^=js-delete-comment]").click(function(){
var url = $(this).attr('data-url');
$.ajax({
url : url,
type : 'POST',
dataType : 'json',
success : function(result) {
console.log(result);
}
});
});

I am not getting why you want to select these <a> links using class name.
Just put your code inside parent <div>
<div id="js-delete-comment">
<a class="js-delete-comment1" data-url="http://localhost/project/document_items/delete_item_comment/1">link</a>
<a class="js-delete-comment2" data-url="http://localhost/project/document_items/delete_item_comment/2">link</a>
<a class="js-delete-comment3" data-url="http://localhost/project/document_items/delete_item_comment/3">link</a>
</div>
And your JQuery code will be
$('#js-delete-comment > a').click(function(){
$.ajax({
url : $(this).data('url'),
type : 'POST',
dataType : 'json',
success : function(result) {
console.log(result);
}
});
});

Related

JQuery text change in h3 tag

I am using ajax to call a page which looks like:
<div class="ui-block-a">
<div class="jqm-block-content invoicehomepage">
<h3>Invoices</h3>
<p>Pages</p>
<p>Navigation</p>
<p>Loader</p>
<p>Transitions</p>
</div>
</div>
and my ajax call is:
var pageContent = '';
$.ajax({
url: 'jsp/home/home.jsp',
type: 'POST',
dataType:'json',
success:function(data) {
$.each(data, function(i, v) {
$.ajax({
url: 'tmpl/homePortlet/'+v.link+'.html',
dataType : "html",
success: function(html_data) {
//var result = $('</div>').append(html_data).find('h3').html();
//$('h3').html(v.portletName);
pageContent += html_data;
//console.log(pageContent);
}
});
console.log(pageContent+'sssss');
});
}
});
I want to change text within h3 tag with the value i got from my second ajax call.
Thanks for help.
You need to change the HTML element h3 by finding it in the content that you have got in your Ajax Call something like this:
pageContent = $(html_data).find("h3:first").html(" YOUR-TEXT-YOU-WANNA-PUT ").parent();
Update:
I think you should use async: false in your second ajax call. And secondly, I don't think so that you needs to store/update html into some Variable as you have used pageContent. You should use JQuery .append() method:
$.ajax({
url: 'jsp/home/home.jsp',
type: 'POST',
dataType:'json',
success:function(data) {
$.each(data, function(i, v) {
$.ajax({
url: 'tmpl/homePortlet/'+v.link+'.html',
dataType : "html",
async: false,
success: function(html_data) {
var new_html_data = $(html_data).find("h3:first").html(v.portletName).parent();
$('.ui-grid-a').append(pageContent);
}
});
});
}
});
use: $('h3').text(v.portletName);
It seems your AJAX request is asynchronous..
You can add async : false, option in ajax request, so when the request end, second request begin and at success of second ajax request you can change text of H3 tag.
var pageContent = '';
$.ajax({
url: 'jsp/home/home.jsp',
type: 'POST',
dataType:'json',
async:false,// add this line so the success callback execute after response receive.
success:function(data) {
$.each(data, function(i, v) {
$.ajax({
url: 'tmpl/homePortlet/'+v.link+'.html',
dataType : "html",
async:false,// add this line so the success callback execute after response receive.
success: function(html_data) {
$('h3').html(v.portletName);
pageContent += html_data;
}
});
console.log(pageContent+'sssss');
});
}
);

pass data($post) to php file using javascript without callback

I need to pass data from HTML page to PHP page But without data callback ....
i'm used two method but One of them did not succeed
1)
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x },
success: function(data)
{
alert("success! X:" + data);
}
});
2)
$.post("getClassStudent.php",
{
},
function(data){
$("#div_id.php").html(data);
}
);
as i can understand, you just want to send info to a php script and don't need the response, is that right?
try this
$.post("phpexample.php", {voteid:x});
or simply remove the "succes" function from the equation if you feel more confortable using $.ajax instead of $.post
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x }
});
your fisrt example is correct, the second is not well formed.
more info:
http://api.jquery.com/jquery.post/
EDIT: to help you some more :)
<button type="button" id="element-id">click</button>
<button type="button" class="class-name">Click</button>
$(document).ready(function(){
//if you are marking ans element by class use '.class-name'
$(".class-name").click(function(){
$.post("getClassStudent.php");
});
//if marking by id element use '#id-name'
$("#element-id").click(function(){
$.post("getClassStudent.php");
});
});
be carefful with the markings, for debuggin try to use "console.log()" or "alert()" so you can see where is the problem and where the code crushes.
var formData = {
'voteid' : 'x',
};
$.ajax({
type : 'POST',
url : 'phpexample.php',
data : formData, // our data object
dataType : 'json',
encode : true
}).done(function(data) {
console.log(data);
});

Not able to prevent redirecting

Here is script for action.
I want to prevent redirecting to url.
$('#rem_btn').click(function(event) {
event.preventDefault();
var remove = $(this).attr('href');
$.ajax({
type: 'get',
url: remove,
success: function(data) {
$('shop_pro_remove').html(data);
}
});
return false;
});
Please try this
HTML:
<a id='rem_btn' rel='remove_product.php?id=<?php echo $pro_id; ?>&name=<?php echo $product_name;?>' href="javascript:void(0)"> remove </a>
AJAX call:
$('#rem_btn').click(function(event) {
event.preventDefault();
var remove = $(this).attr('rel');
$.ajax({
type: 'get',
url: remove,
success: function(data) {
$('#shop_pro_remove').html(data);
}
});
return false;
});
The reason you’d want to do this with the href of a link is that normally, a javascript: URL will redirect the browser to a plain text version of the result of evaluating that JavaScript. But if the result is undefined, then the browser stays on the same page. void(0) is just the smallest script possible that evaluates as undefined.
Reference VOID
First of all, you're missing a closing } and a ). Second, there is an invalid selector in your ajax success callback , you probably wanted to use a class or an id.
Should look like:
$('#rem_btn').click(function(event) {
event.preventDefault();
var remove = $(this).attr('href');
$.ajax({
type: 'get',
url: remove,
success: function(data) {
$('#shop_pro_remove').html(data);
}
});
return false;
});

.keyup() is only working once, why?

I am using this pretty simple jquery function, but it seems to work only on the first keyup..
$('#cmentuser').keyup(function() {
var mess = document.getElementById('cmentuser').value;
var dataString = 'message='+ mess;
$.ajax({
type: "POST",
url: "atuamae.org/comentbyuser.php",
data: dataString,
success: function() {
}
});
});
any ideas on how to keep it active?
It works, also in the following form (changed mess into jQuery(this).val() and relied on jQuery when encoding the data string):
$('#cmentuser').keyup(function() {
$.ajax({
type: "POST",
url: "atuamae.org/comentbyuser.php",
data: {
'message': jQuery(this).val()
},
success: function() {
// success callback
}
});
});
Proof that it works: jsfiddle.net/xfxPR/
You may be dynamically changing some elements (eg. changing ID or assuming id does not need to be unique), or maybe unbinding the event. Just make sure the event is being attached and stays attached to the element you need.
$(document).on('keyup', '#cmentuser', function(e) {//try to find lower element then doc
var dataString = 'message='+ $(e.target).val();
$.ajax({
type: "POST",
url: "/comentbyuser.php", //no cross domain requests, no need for domain name
data: dataString,
success: function() {}
});
});
try this
$('#cmentuser').live('keyup',function() {
var mess = $(this).val();
var dataString = 'message='+ mess;
$.ajax({
type: "POST",
url: "atuamae.org/comentbyuser.php",
data: dataString,
success: function() {
}
});
});

Setting data-content and displaying popover

I'm trying to get data from a resource with jquery's ajax and then I try to use this data to populate a bootstrap popover, like this:
$('.myclass').popover({"trigger": "manual", "html":"true"});
$('.myclass').click(get_data_for_popover_and_display);
and the function for retrieving data is:
get_data_for_popover_and_display = function() {
var _data = $(this).attr('alt');
$.ajax({
type: 'GET',
url: '/myresource',
data: _data,
dataType: 'html',
success: function(data) {
$(this).attr('data-content', data);
$(this).popover('show');
}
});
}
What is happening is that the popover is NOT showing when I click, but if I hover the element later it will display the popover, but without the content (the data-content attribute). If I put an alert() inside the success callback it will display returned data.
Any idea why is happening this? Thanks!
In your success callback, this is no longer bound to the same value as in the rest of get_data_for_popover_and_display().
Don't worry! The this keyword is hairy; misinterpreting its value is a common mistake in JavaScript.
You can solve this by keeping a reference to this by assigning it to a variable:
get_data_for_popover_and_display = function() {
var el = $(this);
var _data = el.attr('alt');
$.ajax({
type: 'GET',
url: '/myresource',
data: _data,
dataType: 'html',
success: function(data) {
el.attr('data-content', data);
el.popover('show');
}
});
}
Alternatively you could write var that = this; and use $(that) everywhere. More solutions and background here.
In addition to the answer above, don't forget that according to $.ajax() documentation you can use the context parameter to achieve the same result without the extra variable declaration as such:
get_data_for_popover_and_display = function() {
$.ajax({
type: 'GET',
url: '/myresource',
data: $(this).attr('alt'),
dataType: 'html',
context: this,
success: function(data) {
$(this).attr('data-content', data);
$(this).popover('show');
}
});
}

Categories

Resources