ajax not loading under external div - ajax

I have external html, where i have create the jcorousal (images are loading through ajax). but that external page is not loading in my current div:
<div class="corousal_content" id="MyDivName"> <!-- External html will load here--> </div>
This is my external page which consist jcarousal:
<script type="text/javascript">
alert("load ajax");
function mycarousel_itemLoadCallback(carousel, state)
{
// Since we get all URLs in one file, we simply add all items
// at once and set the size accordingly.
if (state != 'init')
return;
jQuery.get('dynamic_ajax.txt', function(data) {
mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, data);
});
};
function mycarousel_itemAddCallback(carousel, first, last, data)
{
// Simply add all items at once and set the size accordingly.
var items = data.split('|');
for (i = 0; i < items.length; i++) {
carousel.add(i+1, mycarousel_getItemHTML(items[i]));
}
carousel.size(items.length);
};
/**
* Item html creation helper.
*/
function mycarousel_getItemHTML(url)
{
return '<img src="' + url + '" width="75" height="75" alt="" />';
};
jQuery(document).ready(function() {
jQuery('#mycarousel').jcarousel({
itemLoadCallback: mycarousel_itemLoadCallback
});
});
</script>
</head>
<body>
<div id="wrap">
<div id="mycarousel" class="jcarousel-skin-ie7">
<ul>
<!-- The content will be dynamically loaded in here -->
</ul>
</div>
</div>
please solve my problem.....

How do you load your external html?
Because, I think it failed to fire jQuery.ready event on external html.

Related

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)

ReactJS updating coomponents and passing array as argument?

I'm new to ReactJS and I fell I'm missing some fundamental information.
I am working on simple TODO list, where you click on <li> and it gets transfered to Finished section.
http://jsbin.com/gadavifayo/1/edit?html,js,output
I have 2 arrays that contain list of tasks, when you click on one task <li> it is removed from array and transferred to other array. After that clicked <ul> is updated but not the one where task went.
When using it you may notice that <ul> is updated only when clicked.
How can I update both <ul> when clicking on only one?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Testing</title>
<link rel="stylesheet" href="bootstrap.css">
</head>
<body>
<div id="react-app"></div>
<script src="https://fb.me/react-0.14.3.js"></script>
<script src="https://fb.me/react-dom-0.14.3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script type="text/babel">
/*
* Components
*/
var pendingItems = [
'Clean the room',
'Get milf',
'Sellout and stuff'
];
var finishedItems = [
'Clean the room',
];
var TodoList = React.createClass({
getInitialState: function() {
return { items: this.props.list };
},
handleClick: function(i) {
console.log('You clicked: ' + i + ':' + this.props.listString);
if (this.props.listString == "pendingItems") {
var removed = this.state.items.splice(i, 1);
finishedItems.push(removed);
};
if (this.props.listString == "finishedItems") {
var removed = this.state.items.splice(i, 1);
pendingItems.push(removed);
};
this.forceUpdate()
},
render: function() {
return (
<ul>
{this.state.items.map(function(item, i) {
return (
<li onClick={this.handleClick.bind(this, i)} key={i}>{this.state.items[i]}</li>
);
}, this)}
</ul>
);
},
});
var Layout = React.createClass({
render: function (){
return (
<div className='col-xs-12'>
<div className='col-xs-6'>
<TodoList list={pendingItems} listString="pendingItems"/>
</div>
<div className='col-xs-6'>
<TodoList list={finishedItems} listString="finishedItems"/>
</div>
<div className='col-xs-6'></div>
</div>
)
}
});
ReactDOM.render(<Layout />, document.getElementById('react-app'));
</script>
</body>
</html>
You need to use the states. In getInitialState you put your two list, onclick do whatever transformationyou want (you then have for example updated_list1 and updated_list2 and then you set the list like that:
this.setState({ list1: updated_list1, list2: updated_list2 }); in your case this.setState({ pendingItems: pendingItems ... after the .push
the setState function will automatically rerender, no need to call forceupdate.
The second thing important here is that you have to make the two list communication kinda, so my advise would be to put your both ul in the same component (so you can manage the lists in the same component state as mentionned above).
However this is not the only way to go and you may choose the put the states of your two list in the parent component (Layout). In this case you should use this way to go. https://facebook.github.io/react/tips/expose-component-functions.html
In any case you need (if you want to keep it simple and without external model management like backbone or flux pattern) to put lists states in the same component state. (reminder: method 1 => ul in the same componenet so the states too, method 2 => keep state in the parent component)

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

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

Events not working when using Mustache with Backbone.js

So I am making a test app using RequireJs, Mustache and Backbone.js. I had some success with rendering the collection of models with the Mustache template. But my Mustache template has a button and when I try to bind click event on the button in the view, the button click doesn't invoke the callback function. I am really stuck, can someone tell me where I am not doing right?
Here is my code:
ItemView.js:
define(['jquery', 'backbone', 'underscore', 'mustache', '../../atm/model/item'], function ($, Backbone, _, Mustache, Item) {
var ItemView = Backbone.View.extend({
initialize: function() {
},
tagName: 'li',
events: {
'click .button': 'showPriceChange'
},
render: function() {
var template = $('#template-atm').html();
var itemObj = this.model.toJSON();
itemObj['cid'] = this.model.cid;
var rendering = Mustache.to_html(template, itemObj);
this.el = rendering;
return this;
},
showPriceChange: function(event) {
alert('Changing...');
$('#' + elemId).empty();
$('#' + elemId).append(document.createTextNode('Changed'));
},
});
return ItemView;
});
atm.html:
<!DOCTYPE html>
<html>
<head>
<title>Elevator</title>
<script data-main="scripts/main" src="scripts/require-jquery.js"></script>
<style type="text/css">
</style>
</head>
<body>
<h1>Vending Machine</h1>
<div id="atm-items">
</div>
<script id="template-atm" type="html/template">
<li>
<p>Item: {{name}}</p>
<label for="price-{{cid}}">Price:</label>
<input id="price-{{cid}}" type="text" value="{{price}}"/>
<button class="button">Change</button>
<p id="status-{{name}}-{{cid}}">- -</p>
</li>
</script>
</body>
</html>
You're replacing the view's el inside render:
render: function() {
//...
this.el = rendering;
//...
}
When you do that, you're losing the jQuery delegate that is attached to this.el, that delegate handler (which Backbone adds) is responsible for the event routing.
Usually, you add things to this.el rather than replacing this.el. If your template looked like this:
<script id="template-atm" type="html/template">
<p>Item: {{name}}</p>
<label for="price-{{cid}}">Price:</label>
<input id="price-{{cid}}" type="text" value="{{price}}"/>
<button class="button">Change</button>
<p id="status-{{name}}-{{cid}}">- -</p>
</script>
then you would this.$el.append(rendering) in your view's render; this would give you an <li> in this.el since you've set your view's tagName to li.
Alternatively, if you really need to keep the <li> in the template, you could use setElement to replace this.el, this.$el, and take care of the event delegation:
this.setElement(rendering);
Presumably you're wrapping all these <li>s in a <ul>, <ol>, or <menu> somewhere else; if you're not then you're producing invalid HTML and the browser might try to correct it for you, the corrections might cause you trouble elsewhere as your HTML structure might not be what your selectors think it is.

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