Callback functions for jquery-templ? - javascript

I'm using the plugin jquery-tmpl. Is there a way to specify a callback after a template is run? I want to do something like
<script id='itemTemplate' type='text/html'>
<li class="item" id=${timestampMs}>
<span class="content">${content}</span>
</li>
${processItem($('#' + timestampMs))}
</script>
Where processItem does something to the <li> element that just got generated. As it's written, though, the element doesn't exist at the time processItem is called.
Here's how I run the template:
// Make the AJAX call to the service
$.ajax({
dataType: "json",
url: "/getItems",
success: function(data) {
// fill out template from json
$('#itemTemplate').tmpl(data).appendTo('#container');
}
});
Thanks!

After you call .tmpl, you have nodes that you can act upon, so you can do this:
$.ajax({
dataType: "json",
url: "/getItems",
success: function(data) {
// fill out template from json
$('#itemTemplate').tmpl(data).each(function (index) {
processItem($(this))
}).appendTo('#container');
}
});
That's similar to your workaround, but you shouldn't need to reselect the items, and you should be able to chain the call.

Here's the workaround I'm using for now:
$.ajax({
dataType: "json",
url: "/getItems",
success: function(data) {
// fill out template from json
$('#itemTemplate').tmpl(data).appendTo('#container');
// now process the new events
$('#container .item').each(function (index) {
processItem($(this))
});
}
});

Related

How to put ajax request inside function and call it when necessary?

I have an ajax request:
$.ajax({
type: 'POST',
url: '/get-result.php',
dataType: 'json',
data: 'pid=' + $(this).attr("id"),
success: function(response) {
$(".reviewee-fname").append(response['fname']);
$(".reviewee-lname").append(response['lname']);
} }); };
I want to be able to put this inside a function that waits for me to trigger it with a return call. I am not exactly sure how to word it, I am new to javascript and jquery. But basically, I want to trigger this ajax call with various different button clicks and instead of having to put the ajax call inside every button click event, I want to put it in a stand alone function so if I ever update it later I dont have to change it 5 times.
Heres an example of a click event Id like to call the ajax request function with. Thanks!
$(function() {
$(".task-listing").click(function() {
//Call Ajax function here.
});
});
Callbacks are well-suited for this scenario. You can encapsulate your ajax call in a callback function.
function apiCall() {
$.ajax({
type: 'POST',
url: '/get-result.php',
dataType: 'json',
data: 'pid=' + $(this).attr("id"),
success: function(response) {
$(".reviewee-fname").append(response['fname']);
$(".reviewee-lname").append(response['lname']);
} }); };
}
You can now hook apiCall()method as a callback to button click.
$(function() {
$(".task-listing").click(apiCall);
});
By doing this you will able to achieve this.
I want to put it in a stand alone function so if I ever update it later I dont have to change it 5 times.
EDIT:
Note:
This is lead to start, you can alter this according to your requirement.
Is this not working for you? ↓↓
$(function() {
$(".task-listing").click(function() {
let pid = $(this).attr("id"); //get any other value which you want to pass in function, say url
someFunction(pid); // pass any other parameters, eg- someFunction(pid, url)
});
});
function someFunction(pid){ // someFunction(pid, url)
$.ajax({
type: 'POST',
url: '/get-result.php', // url: url
dataType: 'json',
data: 'pid=' + pid,
success: function(response) {
$(".reviewee-fname").append(response['fname']);
$(".reviewee-lname").append(response['lname']);
}
});
}

How to write dynamic text between div tags?

I am typing with the div on the login screen. I want this article to be dynamic. That's why I am using ajax jQuery to pull data. I want it to be written in the div. How do you do that?
<div class ="bas">Write here(title)</div>
$.ajax({
type: "GET",
url: MY,
success: function (msg, result, status, xhr) {
var obj = jQuery.parseJSON(msg);
title = obj[0].Write;
}
});
You can use either text() or html() to set the content of the required div element. Try this:
<div class="bas">Write here(title)</div>
$.ajax({
type: "GET",
url: MY,
dataType: 'json',
success: function(msg) {
$('.bas').text(msg[0].Write);
}
});
Note that by using dataType: 'json' jQuery will deserialise the response for you, so you don't need to call JSON.parse manually.
Use .text() function
<div class ="bas">Write here(title)</div>
$.ajax({
type: "GET",
url:MY,
success: function (msg, result, status, xhr) {
var obj = jQuery.parseJSON(msg);
title= obj[0].Write;
$(".bas").text(title);
}
});
You can do it by html() or text() depends on what object contains. If containing data includes html tags such as <strong> or .. use html() but if it's plain text use text() instead.
$.ajax({
type: "GET",
url:MY,
success: function (msg, result, status, xhr) {
var obj = jQuery.parseJSON(msg);
title= obj[0].Write;
$('.bas').html(title); // this line
}
});
if only remote read text file
<div class="bas">Write here (title)</div>
jQuery.get(myURL, /*ifMyParams,*/ function(data){
jQuery('.bas').text(data);
})
Use hanlderbars.js or <div class ="bas">Write here<span class="title"></span></div>

load data using jquery multiple div

I have the below jquery function to load data from database which works fine, however I would like to show that same data again over the same page, When I do that it doesn't work. it will only shows for the first one. could someone help me out?
<script type="text/javascript">
$(document).ready(function() {
loadData();
});
var loadData = function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "second.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
setTimeout(loadData, 1000);
}
});
};
</script>
<div style='display:inline' id='responsecontainer'></div><!--only this one is displayed-->
<div style='display:inline' id='responsecontainer'></div><!-- I want it to show me the same data here too-->
ID of an element must be unique in a document, use class attribute to group similar elements
<div style='display:inline' class='responsecontainer'></div>
<div style='display:inline' class='responsecontainer'></div>
then use class selector
$(document).ready(function () {
loadData();
});
var loadData = function () {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "second.php",
dataType: "html", //expect html to be returned
success: function (response) {
$(".responsecontainer").html(response);
setTimeout(loadData, 1000);
}
});
};
The ID selector will return only the first element with the given ID

Javascript breaks when I update html with Ajax

Having a problem with a webapp i've been working on lately, and it has to do with ajax reloading breaking javascript.
I have the following Ajax Call
$.ajax({
type: "POST",
url: "/sortByIngredient/",
data: JSON.stringify(
{
selectedIngredients: tempDict
}),
contentType: "application/json; charset=utf-8",
success: function(data){
var curList = $("#drinkList").contents();
console.log(curList);
$("#drinkList").empty()
$("#drinkList").append(data)
and the following Html UL
<div id = "drinkList" class="d-list">
<ul>
<li id='someID'>some Item</li>
<li id='someID2'>some Item2</li>
</ul>
</div>
I also have a jQuery callback set to activate on clicked list items. On initial loading, all works well. Once the ajax call occurs, and replaces the contents of #drinkList with another list, formatted identically. In case anyone is curious, here is the onClick callback:
$("li").click(function()
{
window.currentDrink = $(this).attr("id");
console.log(window.currentDrink);
$.ajax({
url: "/getDrink/" + $(this).attr("id"),
type: "get",
success: function(data){
$("#ingDiv").html(data);
}
});
});
After I make that Ajax call, the list modifies correctly, but after that, no more javascript seems to work. For example,the console.log is not called when i click on a list item, and the proper view doesnt update(#ingDiv, as shown in the above call)
Is my changing the HTML through Ajax breaking the javascript somehow?
Am I missing something obvious? If it isn't clear already, I am not a web developer.
use event delegation like this -
$('#drinkList').on('click','li',function(){
// do your stuff here
});
As you are not a web developer - This is what your code should look after changes
$('#drinkList').on('click', 'li', function () {
window.currentDrink = $(this).attr("id");
console.log(window.currentDrink);
$.ajax({
url: "/getDrink/" + $(this).attr("id"),
type: "get",
success: function (data) {
$("#ingDiv").html(data);
}
});
});
http://learn.jquery.com/events/event-delegation/
http://api.jquery.com/on/

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