Hello great Stackoverflow, am learning angular js and so am querying database records via angular js and everything works fine. now i want to display a loading image as the database content is loading and the image will fade off as soon as the content is loaded. please how do i achieve that. Thanks
below is the working code
var app = angular.module('angularTable', ['angularUtils.directives.dirPagination']);
app.controller('listdata',function($scope, $http){
$scope.users = []; //declare an empty array
$http.get("data.php").success(function(response){
$scope.users = response; //ajax request to fetch data into $scope.data
});
$scope.sort = function(keyname){
$scope.sortKey = keyname; //set the sortKey to the param passed
$scope.reverse = !$scope.reverse; //if true make it false and vice versa
}
});
You can add smth like $scope.loading = true; before $http.get("data.php").success(function(response){ line.
And $scope.loading = false; inside success function.
In markup, smth like <table ng-hide="loading"> and <img ng-show="loading" src="loader.gif">
Related
I'm using Laravel 5.8 and in this project, I wanted to show some results in Javascript based on the variable which is sent to View.
So at the Controller, I have added this:
$title = "";
if($popup->showtitle == 1){
$title = $popup->title;
}
return view("frontend.home")->with('title',$title);
Then at the view:
<script>
var title = JSON.parse("{{ json_encode($title) }}");
if(!title){
console.log(1);
}else{
console.log(2);
}
</script>
So basically, if title does not have any value, it should be showing 1 at the Console bar, otherwise 2 must be appears.
But the problem is, it does not show anything at all!
So what's going wrong out there? How can I properly get the result based on this variable value?
in controller
$title = "your title";
return view('rontend.home')->with([
'title' => $title,
]);
in blade
<script>
$(document).ready(function() {
var title = {!! json_encode($title) !!};
console.log(title);
});
</script>
I have a registration form in my Laravel project. I submit that registration form data to laravel controller using ajax from javascript. After successfully stored those registration data in database I return the insertedID from controller to javascript and use console.log() function to show that id. In my javascript, console.log() shows that id and auto disappear after half mili second. But I don't want it to disappear.
Here is my js code
var name = $('#reg_name').val(); //reg_name is the id of the input field
var email = $('#reg_email').val(); //reg_email is the id of the input field
$.get( 'signup', {'name': name, 'email': email,'_token':$('input[name=_token]').val()}, function( data )
{
//Here 'signup' is my route name
console.log(data);
});
Here is my controller function
public function signup(RegistrationFormValidation $request)
{
$data = new User();
$data->name = $request->name;
$data->email = $request->email;
$data->save();
$lastInsertedId = $data->id;
if($lastInsertedId > 0)
{
return $lastInsertedId;
}
else
{
return 0;
}
}
Here I concise my code.
What's the problem in my javascript ?
If you are loading a new page, the default behaviour of the Chrome Dev Tools is to clear the logs. You can enable the Preserve log checkbox at the top of the console to prevent this behaviour.
In other situations, the data emitted to the console is modified after the logging to reflect subsequent updates. To prevent this, one can log a JSON serialized version of the data:
console.log(JSON.stringify(data))
(but probably this is not your case).
When I load the page for first time, I'm getting 200 status code and the page is loading file. The problem is from second time getting 304 status and the page is not working. How to set the cache control off for the particular JSON file in my JS file
var app = angular.module("myApp", ['angular.filter']);
app.controller("deviceCtrl", function($scope, $rootScope, $http,$timeout) {
var planReq = $http.get("data/callplans.json").then(function (response1) {
$scope.callplanList = response1.data;
return response1;
});
});
try this..:
var planReq = $http.get("data/callplans.json?r=" + Math.random() ).then(function (response1) {
I use a image gallery plugin called Unite Gallery plugin in an ASP.NET MVC project in order to display images stored in database. However, loading all of the images at the same time takes too long time (because each photo is in 1MB-4MB size and loading 500 photos at the same time on page load is not a good idea) and I think there must be a better approach i.e. asenkron loading or partial loading. Here is my Razor and Controller code. I have a look at many pages on the wweb and docs, but there is not an example in the documentation page. Do you have any idea?
<div id="gallery" style="display:none;">
#foreach (var item in Model)
{
if (item.FileData != null)
{
var base64 = Convert.ToBase64String(item.FileData);
var imgSrc = String.Format("data:image/gif;base64,{0}", base64);
<img alt='Image'
src="#imgSrc"
data-image="#imgSrc"
data-description='Image'>
}
}
</div>
<script type="text/javascript">
jQuery(document).ready(function () {
var gallery = jQuery("#gallery").unitegallery({
gallery_theme: "default" //theme skin
});
gallery.on("item_change", function (num, data) {
if((num%15) == 0)
{
$.ajax({
url: '#Url.Action("List", "PhotoContest")',
data: { isAll: isAllChecked, page: num }, //??? I pass the page parameter???
success: function(data){
//call is successfully completed and we got result in data
//??? NO IDEA ???
},
error:function (xhr, ajaxOptions, thrownError){
//some errror, some show err msg to user and log the error
alert(xhr.responseText);
}
});
}
});
});
</script>
public ActionResult List(string query)
{
var model = db.Photo.Select(m => new PhotoViewModel
{
Id = m.Id,
Name = m.Name,
StatusId = m.StatusId,
SubmitDate = m.SubmitDate,
FileAttachments = m.FileAttachments,
SubmitNo = m.SubmitNo
})
.ToArray();
return View("List", model);
}
Update:
After trying to apply #Kris's perfect approach, I encountered the error shown below. There is not a fix or solution regarding to this specific problem on the web. Any idea?
The image after page load overloads div and gallery borders as shown below:
Load 30 images at a time
Load remaining in Itemchange event available in Unite gallery
Main Page
<div id="gallery" >
<input type="hidden" id="galleryPage" value="0"/>
#HTML.Action("GalleryImages") //first load 30 items as PageNo = 0
</div>
<script type="text/javascript">
var gallery;
jQuery(document).ready(function () {
gallery = jQuery("#gallery").unitegallery({
gallery_theme: "default" //theme skin
});
gallery.on("item_change", function (num, data) {
//when item loaded equals to 15 or 30 or multiples of 15 another 30 items get loaded
if((num%15) == 0)
{
$.ajax({
url: '#HTML.Action("GalleryImages")'+"?pageNo="+jQuery("galleryPage").val(),
data: { isAll: isAllChecked },
success: function(data){
jQuery("gallery").append(data);//partial view with new images
jQuery("galleryPage").val(gallery.getNumItems()/30); //page number total items/number of items per page
},
error:function (xhr, ajaxOptions, thrownError){
//some errror, some show err msg to user and log the error
alert(xhr.responseText);
}
});
}
});
});
</script>
Partial View (_galleryImages.cshtml)
#foreach (var item in Model)
{
if (item.FileData != null)
{
var base64 = Convert.ToBase64String(item.FileData);
var imgSrc = String.Format("data:image/gif;base64,{0}", base64);
<img alt='Image'
src="#imgSrc"
data-image="#imgSrc"
data-description='Image'>
}
}
Controller
//Main View
public ActionResult List()
{
return View();
}
//Partial View
public Action GalleryImages(int PageNo)
{
int PageSize = 30;
var model = db.Photo.Select(m => new PhotoViewModel
{
Id = m.Id,
Name = m.Name,
StatusId = m.StatusId,
SubmitDate = m.SubmitDate,
FileAttachments = m.FileAttachments,
SubmitNo = m.SubmitNo
}).Skip(PageNo*PageSize).Take(PageSize).ToArray();
return PartialView("_galleryImages", model);
}
I don't think there's just one issue here. First, loading 100s of images all at once is going to be slow no matter what you do. For this point #Kris probably has the right idea. I'm unfamiliar with this particular library, but if it provides a way to progressively load in a handful of images at a time, you should definitely make use of that.
The second issue is that you're using base64-encoded data URIs. Images encoded in this way are roughly 150% as large as the actual image data itself. In other words, you're adding greater stress to an already stressed situation. Instead, you should have an action that returns the image data, something like:
public ActionResult GetImage(int id)
{
var image = db.Images.Find(id);
if (image == null)
{
return new HttpNotFoundResult();
}
return File(image.FileData, image.FileType);
}
You can get somewhat creative here by caching the database query result or even the entire response, but be advised that you'll need a significant amount of RAM, since you're going to be storing a lot of image data there.
Third, there's the issue of using a database to store image data in the first place. Just because databases provide a blob type, doesn't mean you need to use it. The most performant approach is always going to be serving directly from the filesystem, as IIS can serve static files directly, without involving all the ASP.NET machinery. Instead of storing the image data in your database, write the image to a filesystem location and then merely store the path to the image in the database. You could then optimize even further by actually offloading all the images to a CDN, ensuring super-fast delivery and taking virtually all load off your server.
Okay so I am new to AngularJS, and am trying to get data from an external API. The end result of this is basically going to help me understand angularjs, using external data, some more as well as getting some stats for Call Of Duty Ghosts for my account or others that I search for.
I know that $http.jsonp is the way to go, but the API doesn't really support it as well as CORS... I have accounted for that. I have been able to use jquery to test to make sure I can do it, but am unable to figure it out with AngularJS.
One issue I am having using whateverorigin and anyorigin from https://stackoverflow.com/a/7910570/1888585 and https://stackoverflow.com/a/6104416/1888585 is that I am getting http error 500 (Internal server error)
Without them I am getting an error regarding the json I am getting (which is valid json, checked with json linter) -> 'Uncaught SyntaxError: Unexpected token : '
So here is what I have:
<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body ng-controller="GhostsCtrl">
<div id="text">
Data from site: {{getGhostData()}}
Data from site: {{info}}
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.15/angular.js"></script>
<script>
var myApp = angular.module('myApp', []);
var ucdid = "3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c";
var network = "xbl";
var url = "api.codcp.com/user_stats?ucdid="+ucdid+"&network="+network;
var wrapURL = "http://anyorigin.com/get?url="+url+"&callback=?";
var wrapURL4 = 'http://whateverorigin.org/get?url='+url+"&callback=?";
//-----------
myApp.service('dataService', function($http) {
console.log("in service!!");
this.getData = function() {
console.log("http fn");
resp = "test";
// from here i get the syntax error
$http.jsonp("http://"+url+"&callback=JSON_CALLBACK")
.success(function(data) {
console.log("Data gotten");
console.log(data.contents.user);
resp = "Success";
}).error(function(data ) {
console.log("error");
resp = "error";
});
return resp;
}
});
myApp.controller('GhostsCtrl', function($scope, $http, dataService){
$scope.info = null;
$scope.info = dataService.getData();
$scope.getGhostData = function() {
// from here I get the 500 error
delete $http.defaults.headers.common['X-Requested-With'];
$http.jsonp(wrapURL4).success(function(data) {
console.log("success: "+data.contents);
$scope.info = data.contents.user;
}).error(function(data) {
console.log("error: " + data);
});
}
});
</script>
</body>
</html>
And for my jquery code that works just fine:
$.getJSON('http://anyorigin.com/dev/get?url=api.codcp.com/user_stats%3Fucdid%3D3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c%26network%3Dxbl&callback=?', function(data){
$.each(data.contents.user, function(val, idx) {
$("#text span").append(val+" ");
})
console.log(data.contents.user);
});
The json that comes back is as follows:
{"user":{"profile":{"ucdid":"3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c","gamertag":"xNF6xVENGE","network":"xbl","image":"http://avatar.xboxlive.com/avatar/xNF6xVENGE/avatarpic-l.png","kdr":1.109316019930545,"winr":2.7632311977715878,"kill":14694,"deaths":13246,"wins":992,"losses":359,"hoursPlayed":147.32049180327868,"currentStreak":0,"preferredWeapon":"weapon.iw6_arx160"},"squadMember":{"gamertag":"Erskine","xp":1031872,"background":20,"patchbacking":0,"patch":"patch_590","level":57,"nextLevelXp":1070000,"nextLevel":58,"prevLevel":56,"prevLevelXp":1030000,"progress":0.0468,"prestige":6},"careerHistory":{"blackops2prestige":3,"mw3prestige":6,"nextreadblackops2":1405837382,"nextreadmw3":1405841587,"playedblackops2":true,"playedmw3":true},"accounts":["xbl","ucd"],"clan":{"teamId":34018,"name":"xATFWx","memberCount":24,"tag":"ATFW","motto":"Search & destroy ","mottoBg":22,"motd":"","stats":null,"entitlements":268435448,"cxp":1991990,"kdr":1.5,"winp":74,"chat_token":"a2236f048c2a5ab71473b6765909a7f88b8716782dff8fd7b1f9df43b4b2c00ad60ba1e1a47cbea0153f590b89b698de9b91e240a8427fae4a9d8d48ea10d4fe941ab40f62acca0497e3b9c39967621abb9d6c2863ac1935d4fc193b44e2bb19","clanLevel":25,"progress":1,"nextLevelXp":1991990,"cxpNeeded":0,"nextLevel":25,"membership":0,"invited":null}}}
If there is a way I can either call jquery from angularjs easily, or avoid either error I get would be great.
I created a fiddle to figure out what your problem may be and found out that your return statement was getting fired before parsing the data in the service. I have modified the service in order to return a callback and it will work fine.
Since I cannot mock your server request here is sample fiddle and code snippet
myApp.service('dataService', function($http) {
console.log("in service!!");
return {
getData: function(callback) {
console.log("http fn");
resp = "test";
// from here i get the syntax error
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
$http.jsonp(url)
.success(function(data){
console.log(data.found);
resp="success";
callback(resp);
});
}
}
});
Looks like there are 2 reasons the anyorigin URL is not working.
The URL parameter needs to be properly encoded.
The callback should be JSON_CALLBACK instead of ?
Try this...
var ucdid = "3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c";
var network = "xbl";
var url = "api.codcp.com/user_stats?ucdid="+ucdid+"&network="+network;
var wrapURL = "http://anyorigin.com/get?url=" + encodeURIComponent(url) +"&callback=JSON_CALLBACK";
This should build this URL which properly returns a JSONP response that can be consumed by angular:
http://anyorigin.com/get/?url=api.codcp.com%2Fuser_stats%3Fucdid%3D3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c%26network%3Dxbl&callback=JSON_CALLBACK
See this Fiddle: Live Demo
The jQuery's $.getJSON() is not a jsonp, so if you are able to retrieve the data by $.getJSON(), you could also do it with a normal $http.get() (of course with the use of anyorigin.com).
It seems the api.codcp.com doesn't support JSONP, it response with a normal JSON regardless of a callback=? exists in a url or not.
Fix this for starters, as it is just mixing single and double quote strings in concatenation:
var wrapURL4 = 'http://whateverorigin.org/get?url='+url+"&callback=?";
By the way watch out. He is out there to get you !
Motto:
Search & destroy
and he's armed!
If you have not figured out the jsonp callback in angularjs! here is something that helped me:
$http.jsonp("http://anywebsite.com/?json=get_recent_post&callback=JSON_CALLBACK")
I hope you find this helpful.
jv