I have a web page that uses
app.controller('listCtrl', function ($scope, $http) {
$http.get("http://data.com/?region=north").success(function (data) {
$scope.properties = data;
});
});
On the click of a button, I'd like to reload the source from a different URL
$http.get("http://data.com/?region=south").success(function (data) {
$scope.properties = data;
});
Is there a way of doing this?
Encapsulate the getting of the resource in a function that is parameterized, so you can call it once when the controller is initializing, and any time they click the button after that.
app.controller('listCtrl', function ($scope, $http) {
function getResource(region) {
$http.get("http://data.com/?region=" + region).success(function (data) {
$scope.properties = data;
});
}
$scope.changeRegion = getResource; // provide function for button click
getResource('north'); // initialize default
});
View:
<button type="button" ng-click="changeRegion('south')">Change Region</button>
Related
I have a originCtrl template and controller. In this one i have a button to go to another template and controller. But on the destCtrl, i need information from an ajax request.
This is a part of my controller code:
.controller('OriginCtlr', function ($scope, $rootScope, $http, $location, $cookies) {
$scope.startTest = function () {
$http.post(API_URL + 'creates/tests.json', {'id':$scope.dic.id, 'nbQuestion':$scope.nbquestion}).success(function (data) {
$rootScope.words = angular.toJson(data.words);
$location.path('/questions');
});
};
})
.controller('DestCtrl', function ($scope, $http, $location, $cookies) {
$rootScope.$watch('words', function(newValue, oldValue) {
scope.word = scope.counter + 1;
});
})
I want to know where i have to do my ajax request:
1) do ajax request in the originCtlr, data in rootScoope, and redirect after success
2) do ajax request in the originCtlr, data in rootScoope, and redirect
3) pass argument in $location.pathand do ajax request in the destCtlr
4) ???
If you want to share data between controllers you should be using a service.
.service('testsService', function ($http, $location) {
this.words = {};
this.createTests = function (id, question) {
$http.post(API_URL + 'creates/tests/json', {id: id, nbQuestion: question})
.success(function (data) {
this.words = angular.toJson(data.words);
$location.path('/questions');
}.bind(this));
}
})
Then you can inject testsService into your controllers and access words from the service instead of using $rootScope.
i have the next code
$(document).ready(function () {
$("#productfilter").validate({
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "listproresult_core.php",
data: $("#productfilter").serialize(),
beforeSend: function () {
$("#contentincore").html("<img src='../loading_core/loading animated/loader.gif'class='clock' border='0' />");
},
success: function (result) {
$("#contentincore").html(result);
}
});
}
});
});
and i wish add the next functions inside and that the results of the form, the links are implemented inside the load function results
$('#contentincore a').click(function (e) {
("#contentincore").on("click", "a:not(.minlink)", function (e) {
("#contentincore").load($(this).attr("href"));
e.preventDefault();
});
});
To bind functions to content that is loaded in with ajax, you have to use .on(). Here's a live example: http://jsfiddle.net/GMDah/ (check the console) When pressing the top link, "pressed" will be printed in the console. When the bottom link with class .minlink is pressed, the code in here is not executed.
The code being:
$("#contentincore a:not(.minlink)").on("click", function (e) {
console.log("pressed");
});
Also, don't forget putting the $-sign or jQuery before your brackets, you seem to have missed a few.
in my JSP I have link and button, for both I want to call Ajax action and use with result.
I am creating events for both link and button and calls Ajax. I need to return the result to the calling method.
//event for button
$(document).on('click', ".addComponent", function(){
var htmlContent=$(this).html();
$('.addComponent').html('Loading...').fadeIn();
var urlAction=$(this).attr("id");
var dataFields=$(this).data('val');
var data=callActionUsingAjax(urlAction, dataFields); //data not returning from ajax
var ajaxActionResult=ajaxResult(data);
$('.addComponent').html(htmlContent).fadeIn();
$('#popUpForm').html(ajaxActionResult);
$('#popUpForm').dialog("open");
return false;
});
//event for link
$(document).on('click', "#dimComponentList >TBODY > TR > TD > a", function(){
$("body").css("cursor", "progress");
var urlAction=$(this).attr("href");
var dataFields="";
var data=callActionUsingAjax(urlAction, dataFields);
var ajaxActionResult=ajaxResult(data); //ajax not returning data
$("body").css("cursor", "auto");
$('#applicationList').html(ajaxActionResult);
return false;
});
Here is my method to call Ajax
function callActionUsingAjax(urlAction,datafields)
{
$.ajax({
type: "post",
url: urlAction,
data: datafields,
success: function (data) {
return data;
}
});
}
I tried this link but I don't know how to use call back on my custom method like that. There are some other events also I need to call this Ajax. That's why I used Ajax inside a custom method.
Can anyone give me a solution?
The Ajax call is asynchronous and takes its time to complete, while the execution goes on and that's why you don't have any data in the "return".
You need to pass a callback function to your callActionUsingAjax and call it in your success handler (or complete or error that depends on the logic.
Like this:
$(document).on('click', ".addComponent", function(){
//... other stuff
callActionUsingAjax(urlAction, dataFields, function (data) { //this is tha callback (third argument)
var ajaxActionResult=ajaxResult(data);
$('.addComponent').html(htmlContent).fadeIn();
$('#popUpForm').html(ajaxActionResult);
$('#popUpForm').dialog("open");
// all of the above happens when ajax completes, not immediately.
});
return false;
});
function callActionUsingAjax(urlAction, datafields, callback)
{
$.ajax({
type: "post",
url: urlAction,
data: datafields,
success: function (data) {
callback(data);
}
});
}
I am loading a PartialView into a Jquery UI dialog and if something went wrong during the post method I reload the PartialView into the dialog again ( ModelState errors for example ) . At this point my ajax sumbit doesn't work anymore. It justs redirect me and it should not.
What is wrong in my code ? Here is what I have tried :
$('#editdialog').dialog({
autoOpen: false,
width: '900px',
modal: true,
open: function (event, ui) {
$(this).load('Controller action', function (html) {
$('#incarcerationForm').submit(function () {
$.ajax({
url: 'Controller action',
data: $("#myForm").serialize(),
type: "POST",
success: function (data) {
$('#editdialog').html(data);
$.validator.unobtrusive.parse($("#myForm"));
if ($("#myForm").valid()) {
GetDetails(#Model.FormModel.ID);
$('#editdialog').dialog('close');
console.log("myForm was edited successfully");
return false;
}
return false;
},
error: function (data) {
$('#editdialog').html(data);
console.log("error at edit myForm");
return false;
}
});
return false;
});
return false;
});
}
});
And my [HttpPost] Controller action :
public ActionResult Create(Mymodel viewModel)
{
return CheckValidBusiness(() =>
{
viewModel.Save(viewModel.FormModel); return true;
})
.Valid(() => PartialView(viewModel))
.Invalid(() => PartialView(viewModel));
}
Replace:
$('#incarcerationForm').submit(function () {
with:
$(document).on('submit', '#incarcerationForm', function () {
so that you subscribe to the submit event of the form in a lively manner which will be resilient to DOM changes. Take a look at the .on() method for more information.
I have made an Ajax function but i am getting a big prolem in that.
I was displaying the contents on click of the link..
The links are fetched from the database and also the url of the links are fetched from the datbase.
I have wriiten ajax to call the contents dynamically on click of the link
<script type="text/javascript">
$(document).ready(function () {
$('a').click(function (e) {
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
});
});
</script>
Now FetchUrlByHobbyName is the function called from the Controller thart returns the url
//Ajax routine to fetch the hobbyinfo by hobbyname
[HttpPost]
public ActionResult FetchUrlByHobbyName(string data)
{
HobbyMasters hobbymaster = new HobbyHomeService().FetchHobbyMasterByHobbyName(data);
string url = hobbymaster.InformationUrl;
if (HttpContext.Request.IsAjaxRequest())
return Json(url);
return View();
}
And in my View i have written the link like this:
#foreach (var item in Model)
{
<li >#Html.ActionLink(item.HobbyName, "Hobbies")
</li>
}
i tried this :
#Html.ActionLink(item.HobbyName, "Hobbies", null, new { id = "alink" })
and then calling Ajax on click of 'alink' but with this my ajax function doesnot get called.
Now the problem is the ajax function is getting called on click of every link on the page..
I want to assign a unique Id to it but i am not understanding how to do that
please Help me...
For that specific link, assign an id. E.g
<a id="someID" href="url">Link</a>
and than bind the click only with that link.
$('#someID').click(function (e)) ....
If I understood you correctly this helps you
The text of the link
<script type="text/javascript">
function myAjaxFunction(){
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
</script>
Try to give a css class selector to you action link like this...
#Html.ActionLink("some link", "Create", "Some_Controller", new { }, new { #class = "test" })
then User jquery for it..
<script type="text/javascript">
$(document).ready(function () {
$('.test').click(function (e) {
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
});
});
</script>