cannot get data-value from paragraph - javascript

I have a very frustrating issue. I have two kind of paragraphs in a div , a built in one like you see below
<div >
<table id="box">
<thead>
<tr>
<td><p class="linkin" data-value="test22">test</p></td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
And fetched ones like this:
$('.menu').on('click', function(){
$('#box').toggle('slide').show();
$.ajax({
url:'fetchsubmenu.php',
data : {nume : $(this).attr('data-value')},
dataType : 'json',
success:function(data){
console.log(data);// process your response
showObjects(data);
}
});
});
function showObjects(obiecte){
$('#box tbody').html('');
for(var i=0; i<obiecte.length; i++){ //Functia care arata obiectele
var aparat = obiecte[i];
$('#box tbody').append(getRow(aparat));
}
}
function getRow(aparat){
var row = '<tr>'+
'<td>' + '<p class="linkin" data-value='+aparat.id+' >'+aparat.nume+'</p>' + '</td>'+ //functia care le aranjeaza
'</tr>';
return row;
}
The problem is that when I want to get the data-value attribute like this:
$('.linkin').on('click',function(){
$.ajax({
url:'test.php',
dataType:'JSON',
data : {id : $(this).attr('data-value')},
success:function(){
console.log();
alert('success');
}
});
});
the built in paragraph works just fine, I get the data-value attribute , but the fetched paragraphs don't work, I am not able to get any attributes.
Sorry for my english.

This is happening because the event listening is only being bound to objects present when the code runs. That would explain why objects that are fetched after the code runs do not work as anticipated. This can be fixed by simply binding to the document.
$(document).on('click', '.linkin', function() {
$.ajax({
url:'test.php',
dataType:'JSON',
data : {id : $(this).attr('data-value')},
success:function() {
alert('success');
}
});
});

Related

Dynamically list and click event

I need to make list (like ng-repeat in angularjs) and click on any of item in list, call function with passed data of the selected item
I make list with $.ajax call and $.each
$(document).ready(function() {
var inHTML = "";
$.ajax({
url: 'http://some.some',
dataType: "json",
success: function(data){
$("#dynamicTable").append('<tr><th><h5 style="margin-left: 15px; margin-top: 15px;">' + "Events" + '</h5></th></tr>');
$.each(data.videos, function(key, value){
$("#dynamicTable").append('<table><tr><td class="aktivniItem backgroundIdKlupa_izbornik_td" style="color: white">'+ moment(value.time).format('DD-MM-YYYY HH:mm:ss') +'</td><tr></table>').click({param1: value.href}, setSourceToVideoPlayer);
});
function setSourceToVideoPlayer(event){
alert(event.data.param1);
}
}
});
});
and in HTML
<table id="dynamicTable" class="table-hover"></table>
Problem is, with this code, when I click on any of item in list I get alert with passed datafor all items, one-by-one, not only for clicked.
Please try below code. I have given the only idea, it might be possible some syntax error.
$(document).ready(function() {
var inHTML = "";
$.ajax({
url: 'http://some.some',
dataType: "json",
success: function(data){
$("#dynamicTable").append('<tr><th><h5 style="margin-left: 15px; margin-top: 15px;">' + "Events" + '</h5></th></tr>');
$.each(data.videos, function(key, value){
$("#dynamicTable").append('<table><tr><td class="aktivniItem backgroundIdKlupa_izbornik_td" data="' + value.href + '" style="color: white">'+ moment(value.time).format('DD-MM-YYYY HH:mm:ss') +'</td><tr></table>');
});
$(".aktivniItem").click(function (){
alert($(this).attr("data"));
});
}
});
});
Only way I can get this to work, for now, is with event.stopImmediatePropagation();
function setSourceToVideoPlayer(event){
alert(event.data.param1);
event.stopImmediatePropagation();
}
Here is detail about this. If this is not a good way to do this, pls tell me. Thnx

How to send parameters to Action from javascript function?

I have a simple view that show a table of data, I want to sort one of its columns when the header is clicked by AJAX, I'm new to AJAX and JS, so this was my try in the view:
<table id="tbl" class="table">
<tr>
<th>
<a style="cursor: pointer" onclick="getData('desc')" id="sort">Title</a>
</th>
<th>
Author
</th>
<th></th>
</tr>
</table>
#section scripts{
<script type="text/javascript">
$(document).ready(getData('asc'))
function getData(sort) {
var srt = sort;
$.ajax({
type: 'GET',
url: '/Book/BooksData/' + srt,
dataTtype: 'json',
success: function (data) {
$("#tbl > tr").remove();
$.each(data, function (index, val) {
$('#tbl').append('<tr><td>' + val.Title + '</td><td>' + val.Author.Name + '</td></tr>')
});
}
});
}
</script>
}
but when I click the header the sort parameter goes null in the action,
public JsonResult BooksData(string sort)
{
var books = new List<Book>();
if (sort == "asc") books = db.Books.Include(b => b.Author).OrderBy(b => b.Title).ToList();
else books = db.Books.Include(b => b.Author).OrderByDescending(b => b.Title).ToList();
return Json(books, JsonRequestBehavior.AllowGet);
}
Yes I'm doing it wrong, but I revised it many times, I can't see logical error except that passing parameters in JavaScript is different than C#
Here is the simpliest way.You need to concatenate sort value to url, using query string.
Now, when you click header the sort parameter must goes with your value in the action.
Please try this:
$.ajax({
type: 'GET',
url: '/Book/BooksData?sort=' + srt,
dataType: 'json',
success: function (data) {
$("#tbl > tr").remove();
$.each(data, function (index, val) {
$('#tbl').append('<tr><td>' + val.Title + '</td><td>' + val.Author.Name + '</td></tr>')
});
}
});
Another way is to use this:
url: '#Url.Action("BooksData","Book")?sort=' + srt
The #Url.Action returns just a string.
In Razor every content using a # block is automatically HTML encoded by Razor.

Reload Table getting its name instead id

i use javascript to reload my table after i input some data, my table goes like this
BEFORE INPUT
AFTER INPUT
u can see that after i input some data the table reload its id instead of its name like on the image, how can i make a way for javascript to reload its name instead of id, below are my code
JS
//reload table data
function reloadTableDataBasedOnVal(result){
var table = tableProject.dataTable(),
oSettings = table.fnSettings();
table.fnClearTable(this);
var contents = result.content;
for(var i = 0 ; i < contents.length ; i++){
var project = contents[i];
var item=[project.cv_id,project.cv_name,project.cv_client_id,project.cn_invoice_method,project.cn_project_rate,project.cn_note,btn];
table.oApi._fnAddData(oSettings, item);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
table.fnDraw();
}
function reloadTableData(){
$.ajax({
url : 'get-all-project',
type : 'GET',
dataType : 'json',
success: function(result,status){
if(status == successStatus){
reloadTableDataBasedOnVal(result);
}
},
errror: function(result,status){
errorNotification("Unknown error, Please contact your administrator!");
}
});
}
VIEW
#foreach($projects as $project)
<tr class="odd gradeX">
<td>{{$project->cv_id}}</td>
<td>{{$project->cv_name}}</td>
<td>{{$project->client['cv_name']}}</td>
<td>{{$project->invoice['cv_method']}}</td>
<td>{{$project->cn_project_rate}}</td>
<td>{{$project->cn_note}}</td>
</tr>
#endforeach
in the view i can do something like this <td>{{$project->client['cv_name']}}</td> since it was a simple php but in javascript i did something similar its show an error, the main code in JS is this line var item=[project.cv_id,project.cv_name,project.cv_client_id,project.cn_invoice_method,project.cn_project_rate,project.cn_note,btn]; that code is the one make the output when the tables reloaded

$(this).find(".text") and (".loading") inside a AJAX success function not working

I've been searching Stack Overflow for well over an hour now and can't seem to find a solution to this problem. To reduce loading time on this PHP page I'm trying to place content from other pages into a div.
The page queries correctly and I can see the output in Safari (Inspector) and FireBug.
The content inside the success: function(output_string) will not load. I have tried every possible combination. I have also attempted var self = this; with no luck although I think this may be due to jQuery(document).ready(function() { But I am using 2 versions of jQuery.
Here's my attached code:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(".text").hide();
//toggle the component with class msg_body
jQuery(".ttop2").click(function() {
jQuery(this).next(".text").slideToggle(500);
var expanded = "./expand.png";
var collapsed = "./collapse.png";
var src = $(this).find(".toggle").attr('src');
<? if($show == 'off') { ?>
if (src == expanded){
$(this).find(".toggle").attr('src',collapsed);
var office = $(this).attr("id");
var month = "<? echo $month; ?>";
var year = "<? echo $year; ?>";
$(this).closest(".loading").html("Loading...");
alert(office);
$.ajax({
url: 'LTData.php',
type:'POST',
data: 'office=' + office + '&month=' + month + '&year=' + year,
dataType: 'json',
success: function(output_string){
$(this).find(".loading").html("");
$(this).find(".text").html(output_string);
} // End of success function of ajax form
}); // End of ajax call
} else {
$(this).find(".toggle").attr('src',expanded);
var office = $(this).attr("id");
alert(office);
}
});
});
<? } else {
//..... Etc.
?>
P.S: I started Javascript programming today so I would love some critical responses. Thanks!
Edit: Script is in the head.
Edit 2: Attached HTML/PHP.
$sqlb="SELECT * FROM league ORDER by total DESC";
$resultb=mysql_query($sqlb);
$num=mysql_num_rows($resultb);
while($rowsb=mysql_fetch_array($resultb)){
if($rowsb[total] == '0') {
continue;
}
if($col=='ebdff2'){
$col='efefef';
}else{
$col='ebdff2';
}
?>
<table class="ttop2" id="<? echo $rowsb["office"]; ?>" bgcolor="#<? echo $col;?>" width="100%">
<tr>
<td width="50%" align="left"><b style="text-transform: capitalize; color:rgb(98, 188, 70);"><? echo $rowsb[office];?></b></td>
<td width="20%" align="left"><b style="text-transform: capitalize; color:rgb(98, 188, 70);"><? echo $rowsb[leads];?></b></td>
<!-- <td width="200px" align="left">Total leads</td>
<td width="270px" align="left">Leads converted</td>-->
<td width="20%" align="left"><b style="text-transform: capitalize; color:rgb(98, 188, 70);"><? echo $rowsb[total];?></b></td>
<td width="10%" align="left"><img style="float: right;" class="toggle" alt="" src="./expand.png" /></td>
</tr>
</table>
<div class="text"><div class="loading"></div></div>
<? } ?>
<?
}///end of show what...
?>
In the ajax success function, you lose you this reference. You need to cache it before the function :
var $this = $(this); //Here
$.ajax({
url: 'LTData.php',
type:'POST',
data: 'office=' + office + '&month=' + month + '&year=' + year,
dataType: 'json',
success: function(output_string){
$this.find(".loading").html("");
$this.find(".text").html(output_string);
} // End of success function of ajax form
}); // End of ajax call
Or, as Kevin B said, pass it in the context option :
$.ajax({
url: 'LTData.php',
type:'POST',
data: 'office=' + office + '&month=' + month + '&year=' + year,
dataType: 'json',
context : this,
success: function(output_string){
$(this).find(".loading").html("");
$(this).find(".text").html(output_string);
} // End of success function of ajax form
}); // End of ajax call
after
jQuery(".ttop2").click(function() {
do
var parent = $(this);
and replace all your calls to $(this) with parent. You are having a lot of enclosure issues with the use of $(this) so fix this first and let us know if that helped.
The below code needs to be written under success event, where response is the returned data in html.
//use filter to find an element is at the root level of response.
if ($(response).filter('#Display').length > 0) { }
//use find to search an element is not at the root level of response.
if ($(response).find('#AddNew').length > 0) { }

jquery each function on string variable

I have wrote a function in javascript which takes title attributes of <tr> calls ajax then after some operation it retreive some title attributes from them. depending on that title attribute i want to remove those <tr> rows
function currentTicketStatus() {
var ids = '';
$('tbody tr[title]').each(function() {
ids += ((ids == '') ? '' : ',') + $(this).attr('title');
});
$.ajax({
url: 'ajaxExecute.aspx?Fn=CTS',
type: 'POST',
context: document.body,
cache: false,
data: 'Tickets=' + ids,
success: function(response) {
if (response != '') {
if (response.substr(0, 5) != 'ERROR') {
var sTickets = response.split('|');
sTickets.each(function() {
$(this).parent().parent().remove();
});
}
}
}
});
}
Example : at the time of ajax call ids="100,101,102,103,104" after ajax call sTickets="101|102" . Now remove those rows with attributes of sTickets
HTML (Not Exactly )
<tbody>
<tr title="100"> some data part </tr>
<tr title="101"> some data part </tr>
<tr title="102"> some data part </tr>
<tr title="103"> some data part </tr>
</tbody>
the this in the each is a "title" (a string), you need the DOM element (the <tr>) instead
sTickets.each(function() {
$('tbody tr[title="'+ this +'"]').remove();
});
demo
try this code in your success function :
success: function(response) {
if (response != '') {
if (response.substr(0, 5) != 'ERROR') {
var sTickets = response.split('|');
$.each(function(i,v){ $('tr[title=' + v + ']') }).remove();
}
}
Explanation:
1- SELECT DOM element by attribute :
$('[ATTRIBUTE=VALUE]') // $('[title="myTitle"]')
you can find more in this link http://api.jquery.com/attribute-equals-selector/
2 - $.each Iteration
which can be used to seamlessly iterate over both objects and arrays.
more : http://api.jquery.com/jquery.each/

Categories

Resources