angular: Why won't ng-repeat update with data from ajax call? - ajax

From a controller a do a ajax call. The call can be triggered from two different links, both in the same html template. When using the above link that switches to the tab the data returned by the ajax call is displayed correctly. When using the refresh link the element in the ng-repeat won't be updated. Anyone knows why this is?
angularjs:
app.controller("ActiveSimulations",
["$scope", "$http", "socket",
function($scope, $http, socket){
$scope.active_simulations_dict = {};
$scope.get_active_simulations = function() {
var responsePromise = $http.get("/active_simulations");
responsePromise.success(function (data, status, headers, config) {
$scope.active_simulations_dict = data;
console.log($scope.active_simulations_dict)
});
responsePromise.error(function (data, status, headers, config) {
console.log('Warning - "AJAX failed!"')
alert("AJAX failed!");
});
};
}]);
HTML
<div id="followSim" class="tab-pane fade">
<h3>Follow running simulations</h3>
<div class="inline-containers">
<div id="simulation-list-wrapper">
<ul class="list-unstyled">
<li ng-repeat="(key, value) in active_simulations_dict">
<a ng-show="value[0] && value[2]" ng-click="followActiveSimulation(key)">
{[{ value[0] }]} ( {[{ value[2] }]} is director)
</a>
</li>
</ul>
</div> <!--end simulation list wrapper-->
<div id="refresh-simulation-list" ng-controller="ActiveSimulations">
<a id="refresh-link"
class="right-side"
ng-click="get_active_simulations()">
<i class="icon-refresh right-side"></i>
refresh list
</a>
</div>

As #kasoban pointed out you might have an issue with multiple instances. Best practice is to create a service which handles your requests. You can inject it and call the request function from any controller then e.g.:
$scope.active_simulations_dict = RequestService.get_active_simulations();

Related

Can't work with object after sending it via Ajax request

I sent to my bootstrap modal this content with Ajax:
<div class="list-of-players text-center">
<div class="list">
#foreach($team->players as $player)
<a class="player_choose" id="player_id_Standard_{{$player->id}}">
<div class="player">
<span class="p_name"><span class="flag-icon {{$player->nationality->flag}}"></span> {{$player->fullname}}</span>
</div>
</a>
#endforeach
</div>
</div>
But then when I want to choose some element of this modal window by this code:
$('.player_choose').click(function () {
$('.modal').modal('hide');
});
It doesn't work. What can be a problem? Maybe js don't see "player_choose" elements after ajax?
Yes. Your script executes before you get this element with ajax. You should use event delegation. This should work:
$(document).on('click','.player_choose', function () {
$('.modal').modal('hide');
});

Display data in a Vue component with ajax

I seem to be misunderstanding how to pass data to a Vue.js component with an ajax call.
My understanding of how this should work:
I need to create an empty object called campaigns in the data section of my component.
Then call method "fetchCampaigns" on page ready to replace the data object.
fetchCampaign method completes an AJAX call and inside of the success callback use this.$set('campaigns', campaigns) to replace the empty campaign object with the newly returned campaign object
Use v-for on the template to iterate through the campaign object and access values with #{{campaign.type}}
My html (I am use vue router, vue resource and laravel blade) :
<router-view></router-view>
<template id="campaignBlock" v-for="campaign in campaigns">
<div class="row">
<div class="block">
<div class="block-title">
<h2>Type: <em>#{{campaign.id}}</em></h2>
</div>
<div class="row"><!-- Grid Content -->
<div class="hidden-sm hidden-xs col-md-4 col-lg-4">
<h2 class="sub-header">#{{campaign.title}}</h2>
</div>
</div>
</div><!-- END Grid Content -->
</template>
Vue component
Vue.component('app-page', {
template: '#campaignBlock',
data: function() {
return{
campaigns: []
}
},
ready: function () {
this.fetchCampaigns();
},
methods: {
fetchCampaigns: function () {
var campaigns = [];
this.$http.get('/retention/getCampaigns')
.success(function (campaigns) {
this.$set('campaigns', campaigns);
})
.error(function (err) {
campaigns.log(err);
});
},
}
})
This is the result of my ajax call from console:
{"campaigns":[{"id":1,"user_id":2,"target_id":1,"name":"Test Campaign","description":"This is a test Campaign","target":"Onboarding","created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00","deleted_at":null}]}
I'm not sure why I can't get my vue component to recognize the new data. Anyone see what I'm missing? TIA
Turns out that v-for="campaign in campaigns" should not go on the template tag, but inside of it.
So this:
<template id="campaignBlock" v-for="campaign in campaigns">
<div class="row">
Should be changed to this:
<template id="campaignBlock">
<div class="row" v-for="campaign in campaigns">

Calling another ajax function on ajax success

I'm calling an ajax function for user login.
After successful login, I want to refresh a div with content like (Ex. Welcome Mr. User, logout).
HTML:
<ul id="signup">
<li>Login</li>
<li>Signup</li>
</ul>
<ul id="loginbox">
<li><label>Enter email address</label><br/><input type="text" class="bookinginput" id="uemail"></li>
<li><label>Enter password</label><br/><input type="password" class="bookinginput" style="width: 151px;" id="upassword">
<button class="styled-button-8" style="margin-top: -43px;margin-left: 10px;" onClick="ulogin()">Login</button>
</li>
</ul>
Ajax:
function ulogin()
{
var uemail = $('#uemail').val();
var upassword = $('#upassword').val();
$.ajax({
type: "POST",
url: "udoologin.php",
data: {email:uemail, password:upassword}
}).done(function( result ) {
$("#loginbox").html(result);
});
}
After successful login, I'm able to change div#loginbox with successfull login message, but I want to replace another div#signup also with
<ul id="signup">
<li>Welcome <?php echo $user?></li>
<li>logout</li>
</ul>
How can I achieve this?
In PHP when u are printing the result,echo
<li>Welcome <?php echo $user?></li>
<li>logout</li>
joined with a seperator like '|||' or something.
in jquery
done(function( result ) {
var log=result.split('|||');
$("#loginbox").html(log[0]);
$('#signup').html(log[1]);
});

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?");
});
}
});

How to trigger Ajax with flash buttons?

I'm working on something where there are 2 links which triggers some Ajax. However I need to turn the links into Flash buttons (AS3). I've never worked with Ajax before, and I have no idea how this can be done.
Edit:
The Ajax:
<script>
$(document).ready(function() {
$('a.catlink').unbind('click').click(function(e)
{
e.preventDefault();
var link = $(this);
var inputs = [];
var cat_type = $(this).attr('href').replace('#', '');
link.attr('disabled', 'disabled');
inputs.push('cat_type=' + escape(cat_type));
$.ajax(
{
type: "POST",
cache: false,
dataType: "html",
url: window.location.href,
data: inputs.join('&'),
success: function(html)
{
var json = $.parseJSON(html);
if (json['status'] == 1)
{
$('div.listing').html(json['html']);
}
link.removeAttr('disabled');
}
});
});
});
</script>
The HTML
<h1 class="section-head">Products
// **The 2 links*** //
<a class="catlink" href="#cinema">cinema</a> <a class="catlink" href="#smart">smart</a></h1>
<div class="listing">
<ul class="listing">
{foreach from=$products item="product_info"}
<li class="clearfix">
<div class="inner-left">
<img height="68" width="90" src="{$product_info.image}" />
<h2 class="normal mt-5">{if $product_info.price != '0'}${$product_info.price}{else}Click for price ยป{/if}</h2>
</div>
<div class="inner-right">
<h3 class="mb-0">{$product_info.productName}</h3>
<p class="small mb-5"><span class="quiet">{$product_info.category}</span></p>
<p class="mb-15">{$product_info.description}</p>
<a class="button getprice" href="{$product_info.url}">Buy Now</a>
<br><br>
</div>
</li>
{/foreach}
</ul>
</div>
If you're going to use AS3 then you can use ExternalInterface.call() to call a JavaScript function on the page. Though, using Ajax may not be required if you're using AS3 because you can make use of the URLLoader class to do the same thing (call a PHP script and decode a result).
If you describe more accurately what you want to achieve then I shall provide some example code and clarify a little more.

Resources