What's the best way to add the same ajax function to a list of comments? - ajax

Source code is like this:
<div>
<h4>comment content</h4>
<a id="delcmt_{{ comment.id }}">delete this comment</a>
</div>
......
<div>
<h4>comment content</h4>
<a id="delcmt_{{ comment.id }}">delete this comment</a>
</div>
I what to add ajax function to each of the "delete this comment" link:
<script type=text/javascript>
$(function() {
$('a#delcmt_id').bind('click', function() {
$.get($SCRIPT_ROOT + '/del_comment', {
}, function(data) {
$("#result").value(data.result);
});
return false;
});
});
</script>
What I can come out is using a loop to copy the upper ajax function for each comment, that must be very ugly. Any good ideas?

Try adding a class and select it with jquery add an event handler. You have to use the 'on' event because the elements you wish attach behavior to might be dynamic and load after document ready.
#*Render all this with razor, or angular or knockout*#
<div>
<h4>comment content</h4>
<span style="cursor: pointer;" id="1" data-rowid="1" class="delete-me-class">delete this comment</span>
</div>
<div>
<h4>comment content</h4>
<span style="cursor: pointer;" id="2" data-rowid="2" class="delete-me-class">delete this comment</span>
</div>
<script>
$(function () {
$('body').on('click', '.delete-me-class', function () {//http://api.jquery.com/on/ on is the latest 'live' binding for elements that may not exists when DOM is ready.
var rowId = $(this).data('rowid');
//TODO Use rowId for your delete ajax, or your element Id if you wish.
alert('You clicked on the delete link with the row ID of ' + rowId);
});
});
</script>
Here is a working Fiddle

Related

Kendo UI Tabstrip 1 on click

I want to make an alert when click on Tab 1 only, but seem it not working. Appreciate your help here.
<div id="tabstrip">
<ul>
<li>Tab 1</li>
<li>Tab 2</li>
</ul>
<div>
<div>Content 1</div>
</div>
<div>Content 2</div>
</div>
<script>
var tabStrip = $("#tabstrip").kendoTabStrip().data("kendoTabStrip");
tabStrip.select("li:first");
$("#tabstrip").on("click", function() {
tabStrip.select(1);
alert("hi");
});
</script>
full demo in here
Currently you are setting the onclick function to the whole tabstrip. Try it like this:
$("#tabstrip li:first").on("click", function() {
alert("hi");
});
Additionally you can use the onSelect event function to identify the selected element anytime.
var onSelect = function(e) {
var a = e.item.innerText;
console.log(e.item.innerText);
if(a ==="Tab 1"){
console.log("Tab 1 selected");
}
};
https://docs.telerik.com/kendo-ui/api/javascript/ui/tabstrip/events/select

every bootstrap modal repeat same id in laravel with ajax

i wrote some code to view my all showing events details using bootstrap modal popup when click read more button. but when i click read more button every response repeats same id.
this is my laravel code
#if(!empty($event))
#foreach($event as $value)
<!-- Single Blog Post -->
<div class="single-blog-post d-flex" id="event_tag">
<div class="post-thumbnail">
<img src="{{asset('images/'.$value->image)}}" alt="">
</div>
<div class="post-content">
<a class="post-title">
#if(strlen($value->title) <= 35)
{{$value->title}}
#else
{{substr($value->title, 0, 35) . '...'}}
#endif
</a>
<div class="post-meta d-flex justify-content-between">
<center><button id="event_button" class="post-cata cata-sm cata-success text_white" data-toggle="modal" data-target="#myModal">Read More</button></center>
</div>
</div>
<input type="hidden" name="event_id" id="event_id" value="{{$value->id}}"></div>
#endforeach
#endif
and this is javascript code to get id and show every id detail.
<script>
$(document).on("click", "#event_button", function() {
var id = $("event_id").val();
console.log(id);
$.ajax({
url: "/event/" + id + "/show",
dataType: "json",
success: function(html) {
$("#event_title").html(html.data.title);
}
});
})
</script>
every time repeats id no 2 when click each event read more button. how can i fix this?
Your code has some mistakes in html too. For example, has fixes ids in html.
'event_id'
'event_button'...
Try this...
<button id="event_button-{!! $value->id !!}" data-target="event_id-{!! $value->id !!}"
<input type="hidden" name="event_id" id="event_id-{!! $value->id !!}"
The code above will fixed the id issue.
Now let's to the JS code... Change the click event:
$(document).on("click", "button.post-cata", function() {
var id = $("#" . $(this).data("target").val();
...
Do you need to associate tags to work with the right value. Avoid to put fixes ids inside a php loop. The html id element must be unique in document.
So, has many ways to do this. In this case, the input hidden fild is not necessary. you can put the id in a attribute in the button tag too.
<button data-id="{!! $value->id !!}...
So in the jquery click event do:
var id = $(this).data('id');
It's more ease and clean.
give class name to button and add attribute to button
<button class="event_button post-cata cata-sm cata-success text_white" data-eventid="{{$value->id}}">Read More</button>
so no need to use hidden input id
now using jQuery :
$(document).on('click','.event_button',function(){
var event_id = $(this).attr("data-eventid");
$("#myModal").modal("show");
$.ajax({
url: "/event/" + event_id+ "/show",
dataType: "json",
success: function(html) {
$("#event_title").html(html.data.title);
}
});
});

Updating a polymer element property with data from API call

I'm trying to update a property in a polymer element with data from an ajax api call. I have something similar working elsewhere in the app where users are able to add packages dynamically.
Anyone know what I'm doing wrong here?
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="address-input.html">
<link rel="import" href="package-list.html">
<link rel="import" href="../bower_components/iron-ajax/iron-ajax.html">
<dom-module id="step-one">
<style>
</style>
<template>
<section id="addresses">
<div class="container">
<div class="row">
<h5>Addresses</h5>
<address-input></address-input>
</div>
</div>
</section>
<section id="packages">
<div class="container">
<div class="row">
<h5>Packages</h5>
<package-list></package-list>
</div>
</div>
</section>
<section id="submit-shipping-info">
<div class="container">
<div class="row">
<a class="waves-effect waves-light btn col s12 m12 l12" id="submit" on-click="submitInfo">Submit</a>
<template is="dom-repeat" items="{{options}}">
<p>{{item.rates}}</p>
</template>
</div>
</div>
</section>
</template>
</dom-module>
<script>
Polymer ({
is: 'step-one',
properties: {
options: {
type: Object,
notify: true,
value: []
}
},
submitInfo: function(e) {
e.preventDefault();
//add dimensions of all packages to the dimensions array
var dimensions=[];
$('#packages .package-card').each(function(){
var weight= $(this).find('.weight').val();
var length= $(this).find('.length').val();
var height= $(this).find('.height').val();
var width= $(this).find('.width').val();
var dimension={width:width,length:length,height:height,weight:weight};
dimensions.push(dimension);
});
//capture address data
var from = $('#fromAddress').val();
var to = $('#toAddress').val();
//URL that processes getting a URL
var getQuoteURL = '../v2/API/get_rates.php';
var stuff = [];
jQuery.ajax({
type: "POST",
dataType: "json",
cache: false,
url: getQuoteURL,
data:{
from:from,
to:to,
dimension:dimensions
}
}).done(function(data){
$.each(data['rates'], function(i, rate ) {
stuff.push({carrier:rate.carrier});
return stuff;
});
//show step two when ajax call completes
$('.step-two').removeClass('hide').addClass('show');
console.log(stuff);//I can see all objects I need to pass to the 'options' property
return stuff;
});
this.push('options',stuff);//doesn't seem to update the 'options' property with these as a value
}
});
</script>
I'm able to console.log the array i'm trying to use, but when I try to push it to the 'options' property, it won't update.
Consider using Polymer built in methods instead of jQuery.
1. A button to submit a request.
<paper-button on-click="handleClick">Send a package</paper-button>
2. AJAX requests using <iron-ajax> element!
<iron-ajax id="SendPkg"
url="my/api/url"
method="POST"
headers='{"Content-Type": "application/json"}'
body={{packageDetails}}
on-response="handleResponse">
</iron-ajax>
3. Handle the on-click event,
On click, select <iron-ajax> by ID and call <iron-ajax>'s generateRequest()
Use either data binding or Polymer's DOM API to get the package's width, height ...etc
handleClick: function() {
this.packageDetails = {"width": this.pkgWidth, "height": this.pkgHeight };
this.$.SendPkg.generateRequest();
},
4. Handle the response
handleResponse: function() {
//Push data to options...
},
return stuff;
});
this.push('options',stuff);//doesn't seem to update the 'options' property with these as a value
should be
return stuff;
this.push('options',stuff);//doesn't seem to update the 'options' property with these as a value
)};
otherwise
this.push('options',stuff);
is executed before data has arrived
The solution ended up being to put this into a variable:
var self = this;
then in the ajax .done() replace the value of the object with the new object from the ajax call.
self.options = stuff;
I guess you have to put "this" into a variable before you can overwrite it's values. Then the other issue was that I was trying to use .push() to add to it, but really all I needed to do was replace it. (Using self.push('options',stuff); didn't seem to work as far as adding to an object)

Kendo upload - how to add a javascript event handler for file remove button click

My kendo template is as follows:
<div id="file-err-msg" > Please remove files with errors</div>
<input name="files" id="files" type="file" />
<script id="fileTemplate" type="text/x-kendo-template">
<span class='k-progress'>
</span>
<strong class='k-upload-status'>
<button type='button' class='btn-remove k-button k-button-bare k-upload-action'>
<span class='k-icon k-i-close k-delete' title='Remove'></span>
</button>
</strong>
</script>
<script>
$("#files").kendoUpload({
template: kendo.template($('#fileTemplate').html())
});
</script>
I need to hide the div with id - file-err-msg, when the remove button is clicked. the Remove action is happening when the span with css class "k-delete" is clicked. I need to add the below event handler in addition, and it is never being called.
$(".k-delete").click(function () {
alert("Remove button clicked");
});
since these controls are rendered dynamically, i tried to bind them to the event handler as below, but nothing works.
$("body").on("click", ".btn-remove", function () {
alert("dynamic control event handler");
});
Any help is appreciated!
According to Kendo Upload API documentation, you can bind a function to the remove event.
So this is where you could hide your file-err-msg div :
$("#files").kendoUpload({
template: kendo.template($('#fileTemplate').html()),
remove: function(e) {
$('#file-err-msg').hide();
}
});

How to use AJAX loading with Bootstrap tabs?

I used bootstrap-tabs.js and it has worked perfectly.
But I didn't find information about how to load content through AJAX request.
So, how to use AJAX loading with bootstrap-tabs.js?
In Bootstrap 2.0 and up you have to bind to the 'show' event instead.
Here's an example HTML and JavaScript:
<div class="tabbable">
<ul class="nav nav-tabs" id="myTabs">
<li>Home</li>
<li>Foo</li>
<li><a href="#bar" data-toggle="tab">Bar</li>
</ul>
<div>
<div class="tab-pane active" id="home"></div>
<div class="tab-pane" id="foo"></div>
<div class="tab-pane" id="bar"></div>
</div>
</div>
JavaScript:
$(function() {
var baseURL = 'http://yourdomain.com/ajax/';
//load content for first tab and initialize
$('#home').load(baseURL+'home', function() {
$('#myTab').tab(); //initialize tabs
});
$('#myTab').bind('show', function(e) {
var pattern=/#.+/gi //use regex to get anchor(==selector)
var contentID = e.target.toString().match(pattern)[0]; //get anchor
//load content for selected tab
$(contentID).load(baseURL+contentID.replace('#',''), function(){
$('#myTab').tab(); //reinitialize tabs
});
});
});
I wrote a post about it here: http://www.mightywebdeveloper.com/coding/bootstrap-2-tabs-jquery-ajax-load-content/
You can listen the change event and ajax load content in the event handler
$('.tabs').bind('change', function (e) {
var now_tab = e.target // activated tab
// get the div's id
var divid = $(now_tab).attr('href').substr(1);
$.getJSON('xxx.php').success(function(data){
$("#"+divid).text(data.msg);
});
})
I wanted to load fully dynamic php pages into the tabs through Ajax.
For example, I wanted to have $_GET values in the links, based on which tab it was - this is useful if your tabs are dynamic, based on database data for example.
Couldn't find anything that worked with it but I did manage to write some jQuery that actually works and does what I'm looking for.
I'm a complete jQuery noob but here's how I did it.
I created a new 'data-toggle' option called tabajax (instead of just tab), this allows me to seperate what's ajax and what's static content.
I created a jQuery snippet that runs based on that data-toggle, it doesn't mess with the original code.
I can now load say url.php?value=x into my Bootstrap Tabs.
Feel free to use it if you want to, code is below
jQuery code:
$('[data-toggle="tabajax"]').click(function(e) {
e.preventDefault()
var loadurl = $(this).attr('href')
var targ = $(this).attr('data-target')
$.get(loadurl, function(data) {
$(targ).html(data)
});
$(this).tab('show')
});
HTML:
<li>Val 1</li>
So here you can see that I've changed the way bootstrap loads thing, I use the href for the dynamic ajaxlink and then add a 'data-target' value to the link instead, that should be your target div (tab-content).
So in your tab content section, you should then create an empty div called val1 for this example.
Empty Div (target):
<div class='tab-pane' id='val1'><!-- Ajax content will be loaded here--></div>
Hope this is useful to someone :)
I suggest to put the uri into the tab-pane elements, it allows to take advantage of web frameworks reverse url fonctionnalities. It also allows to depend exclusively on the markup
<ul class="nav nav-tabs" id="ajax_tabs">
<li class="active"><a data-toggle="tab" href="#ajax_login">Login</a></li>
<li><a data-toggle="tab" href="#ajax_registration">Registration</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="ajax_login"
data-target="{% url common.views.ajax_login %}"></div>
<div class="tab-pane" id="ajax_registration"
data-target="{% url common.views.ajax_registration %}"></div>
</div>
And here is the javascript
function show_tab(tab) {
if (!tab.html()) {
tab.load(tab.attr('data-target'));
}
}
function init_tabs() {
show_tab($('.tab-pane.active'));
$('a[data-toggle="tab"]').on('show', function(e) {
tab = $('#' + $(e.target).attr('href').substr(1));
show_tab(tab);
});
}
$(function () {
init_tabs();
});
I loads the active tab, and loads a tab only if it is not already loaded
There is an error in your code user1177811.
It has to be $('[data-toggle="tabajax"]').
Also there is room for improvement. The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted. So i added #content to load the content div of the remote page.
$this.tab('show'); is now only called, when response was a success.
Here is the code
$('[data-toggle="tabajax"]').click(function(e) {
e.preventDefault();
$this = $(this);
var loadurl = $(this).attr('href');
var targ = $(this).attr('data-target');
$(targ).load(loadurl+'?ajax=true #content', function(){
$this.tab('show');
});
});
Here is how I do it. I utilize an attribute data-href which holds the url I want to load on show. This will not reload data that is already loaded unless you set $('#tab').data('loaded'); to 0 or remove it. It also handles relative vs. absolute urls by detecting the location of the first slash. I am not sure of the compatibility with all browsers but it works in our situation and allows for the functionality we are looking for.
Javascript:
//Ajax tabs
$('.nav-tabs a[data-href][data-toggle="tab"]').on('show', function(e) {
var $this = $(this);
if ($this.data('loaded') != 1)
{
var firstSlash = $this.attr('data-href').indexOf('/');
var url = '';
if (firstSlash !== 0)
url = window.location.href + '/' + $this.attr('data-href');
else
url = $this.attr('data-href');
//Load the page
$($this.attr('href')).load(url, function(data) {
$this.data('loaded', 1);
});
}
});
HTML:
<div class="tabbable">
<ul class="nav nav-tabs">
<li class="active">
Tab 1
</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="js-tab1">
<p>
This content isn't used, but instead replaced with contents of tab1.php.
</p>
<p>
You can put a loader image in here if you want
</p>
</div>
</div>
</div>
Here is a solution I have found - and modified to suit my needs:
$("#tabletabs").tab(); // initialize tabs
$("#tabletabs").bind("show", function(e) {
var contentID = $(e.target).attr("data-target");
var contentURL = $(e.target).attr("href");
if (typeof(contentURL) != 'undefined') { // Check if URL exists
$(contentID).load(contentURL, function(){
$("#tabletabs").tab(); // reinitialize tabs
});
} else {
$(contentID).tab('show');
}
});
$('#tabletabs a:first').tab("show"); // Load and display content for first tab
});
This is an MVC example using Razor. It will interact with two partial views named: _SearchTab.cshtml and _SubmissionTab.cshtml
Notice that I am naming the id of the tabs the same as the partials.
Markup:
<!-- Nav tabs -->
<ul id="tabstrip" class="nav nav-tabs" role="tablist">
<li class="active">Submission</li>
<li>Search</li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane fade in active" id="_SubmissionTab">#Html.Partial("_SubmissionTab")</div>
<div class="tab-pane fade" id="_SearchTab"></div>
</div>
The #Html.Partial will request the page on the active tab on page load
Script:
<script>
$('#tabstrip a').click(function (e) {
e.preventDefault()
var tabID = $(this).attr("href").substr(1);
$("#" + tabID).load("/#ViewContext.RouteData.Values["controller"]/" + tabID)
$(this).tab('show')
})
</script>
The load function will perform an ajax request as each tab is clicked. As for what path is requested you will notice a #ViewContext.RouteData.Values["controller"] call. It simply gets the controller of the current view assuming the partial views are located there.
Controller:
public ActionResult _SubmissionTab()
{
return PartialView();
}
public ActionResult _SearchTab()
{
return PartialView();
}
The controller is needed to relay the load request to the proper partial view.
Here is the Bootstrap tab Ajax example, you can use it...
<ul class="nav nav-tabs tabs-up" id="friends">
<li> Contacts </li>
<li> Friends list</li>
<li>Awaiting request</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="contacts">
</div>
<div class="tab-pane" id="friends_list">
</div>
<div class="tab-pane urlbox span8" id="awaiting_request">
</div>
</div>
and here is the AJAX call
$('[data-toggle="tabajax"]').click(function(e) {
var $this = $(this),
loadurl = $this.attr('href'),
targ = $this.attr('data-target');
$.get(loadurl, function(data) {
$(targ).html(data);
});
$this.tab('show');
return false;
});
I use this function and it's really nice because she prevent's you from load ajax again when going back to that tab.
Tip: on tab href, just put the destination. Add this to footer:
$("#templates_tabs").tabs({
beforeLoad: function( event, ui ) {
if (ui.tab.data("loaded")) {
event.preventDefault();
return;
}
ui.ajaxSettings.cache = false,
ui.jqXHR.success(function() {
ui.tab.data( "loaded", true );
}),
ui.jqXHR.error(function () {
ui.panel.html(
"Not possible to load. Are you connected?");
});
}
});

Resources