Angular ng-grid issue - ng-grid

I am trying to use ng-grid using the following tutorial.
http://angular-ui.github.io/ng-grid/
Here is my View
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-1.8.2.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/angular.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/angular-resource.js")"></script>
#*<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>*#
<script type="text/javascript" src="#Url.Content("~/Scripts/ng-grid-2.0.7.min.js")"></script>
<script src="~/Scripts/PostsController.js"></script>
<script src="~/Scripts/postreq.js"></script>
<link rel="stylesheet" type="text/css" href="~/Content/ng-grid.min.css" />
<div data-ng-controller="PostsController">
<div class="gridStyle" data-ng-grid="gridOptions"></div>
</div>
Here is my Angular code
function PostsController($scope, $http) {
$http({ method: 'GET', url: '/api/request' }).
success(function (data, status, headers, config) {
$scope.posts = data;
}).
error(function (data, status, headers, config) {
$scope.error = "An Error has occured while loading posts!";
$scope.loading = false;
});
$scope.gridOptions = { data: 'posts' };
}
However, when i run the application i see blank square in browser and there is no error showing in the console.
Please help me to fix this issue.
FYI: I checked API response directly in browser and it shows with data.

It seems to me that you are missing some steps of the tutorial you are following :
Where you declare your app module, add ngGrid:
angular.module('myApp',['ngGrid']);
I do not see your module declaration anywhere.

Do you have ng-app="myApp" defined at the top of your page?
I also noticed that you do not have a css class defined for "gridStyle". "gridStyle" is not part of the ng-grid css.

Sounds odd, but this worked for me by using a timeout. Try it like this:
setTimeout(function () {
$http.get('/api/request')
.success(function (data, status) {
$scope.posts = data;
})
.error(function (data, status) {
alert(status);
});
}, 100);

Related

Vue JS Ajax Calls

I am trying to make the change from jQuery to Vue.js and am having some difficulty running an Ajax Call using vueresource. Below is a sample script I am using, with both jQuery and Vuejs. Both trying to access the same ajax call. The jQuery call works, the vuejs call doesn't. The sendAjax method is being called because the first 2 alerts show - then nothing.
Edit - this is only causing an error while running the Ajax call through Wordpress. Outside of WP, it does work. Any ideas??
<!DOCTYPE html>
<html>
<head>
<title>Vue Resource</title>
<script src="https://cdn.jsdelivr.net/npm/jquery#3.2.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/vue/latest/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-resource#1.5.1"></script>
</head>
<body>
<button id="jQueryAjax">Jquery AJAX</button>
<div id="myvue">
<button #click.prevent="sendAjax()">AJAX</button>
</div>
<script>
let AjaxUrl = "http://localhost:8888/mySite/wp-admin/admin-ajax.php";
const postData = { action: 'my_ajaxcall', function: 'AjaxTest' };
Vue.use(VueResource);
const ajax_app = new Vue({
el: '#myvue',
methods: {
sendAjax() {
alert("VueAjax");
alert(JSON.stringify(postData));
this.$http.post(AjaxUrl, postData).then(res => {
alert(JSON.stringify(res));
});
}
}
});
$("#jQueryAjax").click(function() {
alert("jQueryAjax");
alert(JSON.stringify(postData));
alert(AjaxUrl);
$.ajax({
type: 'POST',
url: AjaxUrl,
data: postData,
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data));
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error");
}
});
});
</script>
</body>
</html>
You AJAX call probably encounters an error and you handle only the successful calls. Please extend your sendAjax function like this:
this.$http.post(AjaxUrl, postData).then(res => {
alert(JSON.stringify(res));
}, err => {
alert(err);
});
Now an error should be alerted.
BTW: It is better to use console.log() instead of alert(), it is much more readable and you won't have to confirm every alert.
After #mbuechmann pointing me to be able to see the actual error, I was able to determine that the issue I was having was actually to do with Wordpress. In order to use the Wordpress Ajax handler, you need to send an action to the REQUEST header. To do this, you need to send FormData, and without sending headers.
This code was found in this question : Custom Shortcode AJAX 400 Bad Request and enabled me to get my Fetch working with Wordpress.
var data = new FormData();
data.append( 'action', 'aj_ajax_demo' ); data.append( 'nonce', aj_ajax_demo.aj_demo_nonce );
fetch(aj_ajax_demo.ajax_url, {
method: 'POST',
body: data, }).then(response => {
if (response.ok) {
response.json().then(response => {
console.log(response);
});
} });

How to get Ajax responce in Framework7?

I am new to Framework7. In this code i am not getting response from Ajax.
Guide me please.
Thanks in advance.
<!-- Path to Framework7 Library JS -->
<script type="text/javascript" src="js/framework7.min.js"></script>
<!-- Path to your app js -->
<script type="text/javascript" src="js/my-app.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script>
var myApp = new Framework7();
var $$ = Dom7;
$$('.form-to-json').on('click', function(){
var name = $$('#name').val();
var password = $$('#password').val();
var data = {"name":name,"password":password};
$$.ajax({
url: "validation.php",
type: "post",
data: data,
//dataType: 'json',
success: function (data)
{
alert("data");
}
});
});
</script>
Validation Page
<?php
echo "Hi";
?>
There's a slight error in your code. In the callback, you are displaying alert("data") which will always display "data". To display what's been sent from the php script, you need to change alert("data") to alert(data).

Understanding jQuery ' $(function () {...}); ' logic

I have a partial view in ASP.NET MVC 3, with a script:
<script type="text/javascript" >
$(function () {
$("#tagbox").autocomplete({
source: "/Tag/GetTags",
minLength: 1,
select: function (event, ui) {
$("tagbox").val(ui.item.value);
}
});
});
</script>
when I load the patial view in my content div, the auto complete won't work, unless I remove the '$(function () {... }) so the script looks like this:
<script type="text/javascript" >
$("#tagbox").autocomplete({
source: "/Tag/GetTags",
minLength: 1,
select: function (event, ui) {
$("tagbox").val(ui.item.value);
}
});
</script>
But when loading it as new view by accessing the URL, everything works just fine.
Also I have those references on my main view:
<script src="http://static.jsbin.com/js/prod/jsbin-3.4.4.min.js"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="../../Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
Second, when I change the order between the references, my ajax call opens as a new view and not as partial. Maybe one of them is unnecessary or something?
Please follow the below link it will clearly explain about the jquery $(function(){}.
$(function(){}

Google map not showing in partial view

i am working on an asp.net mvc3 application.
I am trying to load a google map inside a partial view but it is not working:
My partial view _Map.cshtml
<style type="text/css">
#map_canvas
{
position:absolute;
top:40px;
left:12px;
width:576px;
height: 450px;
}
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div class="sTitle">Name</div>
<div id="map_canvas"></div>
<script type="text/javascript">
var map;
$(document).ready(function () {
var map;
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
google.maps.event.addDomListener(window, 'load', initialize);
});
</script>
The map is loaded Via an AJAX Call:
$.ajax({
type: 'GET',
url: '#Url.Action("GetMapById", "Map")',
data: { 'id': sId },
success: function (html) {
$("#content").html(html);
},
complete: function () {
},
error: function () {
alert("There was an error opening the Map. Please try again or contact an administrator");
}
});
The partial is loaded in a div named Content
And in the controller I just return the Partial View
return PartialView("_Map");
The View is loading but the map is not visible.
I used Firebug to track the problem and I got this error:
“google is not defined”
Any idea about the problem?
Thanks a lot
I solved this by putting this
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
in the Layout page nad not in the subview
You have to load google map in this way:
<script type="text/javascript">
var map;
google.load("maps", "3", { other_params:"sensor=false" });
$(document).ready(function () {
And you reinitialize "var map" two times.
I didn't want to load the maps in a Layout page... Doing that would mean that if the script was taking long to load, it would slow the whole page and besides, if it is not needed there, then why make the browser download it?
To get around that, I found that you can load the maps API in your partial view like this:
$.getScript('http://maps.googleapis.com/maps/api/js',function (){
google.maps.event.addDomListener(window, 'load', initialize);
});

Basic example of using .ajax() with JSONP?

Please could someone help me work out how to get started with JSONP?
Code:
$('document').ready(function() {
var pm_url = 'http://twitter.com/status';
pm_url += '/user_timeline/stephenfry.json';
pm_url += '?count=10&callback=photos';
var photos = function (data) {
alert(data);
};
$.ajax({
url: pm_url,
dataType: 'jsonp',
jsonpCallback: 'photos',
jsonp: false,
});
});
Fiddle: http://jsfiddle.net/R7EPt/6/
Should produce an alert, as far as I can work out from the documentation: isn't (but isn't producing any errors either).
thanks.
JSONP is really a simply trick to overcome XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.)
So - instead of using XMLHttpRequest we have to use script HTMLl tags, the ones you usually use to load JS files, in order for JS to get data from another domain. Sounds weird?
Thing is - turns out script tags can be used in a fashion similar to XMLHttpRequest! Check this out:
script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data";
You will end up with a script segment that looks like this after it loads the data:
<script>
{['some string 1', 'some data', 'whatever data']}
</script>
However this is a bit inconvenient, because we have to fetch this array from script tag. So JSONP creators decided that this will work better (and it is):
script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data?callback=my_callback";
Notice my_callback function over there? So - when JSONP server receives your request and finds callback parameter - instead of returning plain JS array it'll return this:
my_callback({['some string 1', 'some data', 'whatever data']});
See where the profit is: now we get automatic callback (my_callback) that'll be triggered once we get the data.
That's all there is to know about JSONP: it's a callback and script tags.
NOTE:
These are simple examples of JSONP usage, these are not production ready scripts.
RAW JavaScript demonstration (simple Twitter feed using JSONP):
<html>
<head>
</head>
<body>
<div id = 'twitterFeed'></div>
<script>
function myCallback(dataWeGotViaJsonp){
var text = '';
var len = dataWeGotViaJsonp.length;
for(var i=0;i<len;i++){
twitterEntry = dataWeGotViaJsonp[i];
text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
}
document.getElementById('twitterFeed').innerHTML = text;
}
</script>
<script type="text/javascript" src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback"></script>
</body>
</html>
Basic jQuery example (simple Twitter feed using JSONP):
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
dataType: 'jsonp',
success: function(dataWeGotViaJsonp){
var text = '';
var len = dataWeGotViaJsonp.length;
for(var i=0;i<len;i++){
twitterEntry = dataWeGotViaJsonp[i];
text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
}
$('#twitterFeed').html(text);
}
});
})
</script>
</head>
<body>
<div id = 'twitterFeed'></div>
</body>
</html>
JSONP stands for JSON with Padding. (very poorly named technique as it really has nothing to do with what most people would think of as “padding”.)
There is even easier way how to work with JSONP using jQuery
$.getJSON("http://example.com/something.json?callback=?", function(result){
//response data are now in the result variable
alert(result);
});
The ? on the end of the URL tells jQuery that it is a JSONP request instead of JSON. jQuery registers and calls the callback function automatically.
For more detail refer to the jQuery.getJSON documentation.
In response to the OP, there are two problems with your code: you need to set jsonp='callback', and adding in a callback function in a variable like you did does not seem to work.
Update: when I wrote this the Twitter API was just open, but they changed it and it now requires authentication. I changed the second example to a working (2014Q1) example, but now using github.
This does not work any more - as an exercise, see if you can replace it with the Github API:
$('document').ready(function() {
var pm_url = 'http://twitter.com/status';
pm_url += '/user_timeline/stephenfry.json';
pm_url += '?count=10&callback=photos';
$.ajax({
url: pm_url,
dataType: 'jsonp',
jsonpCallback: 'photos',
jsonp: 'callback',
});
});
function photos (data) {
alert(data);
console.log(data);
};
although alert()ing an array like that does not really work well... The "Net" tab in Firebug will show you the JSON properly. Another handy trick is doing
alert(JSON.stringify(data));
You can also use the jQuery.getJSON method. Here's a complete html example that gets a list of "gists" from github. This way it creates a randomly named callback function for you, that's the final "callback=?" in the url.
<!DOCTYPE html>
<html lang="en">
<head>
<title>JQuery (cross-domain) JSONP Twitter example</title>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON('https://api.github.com/gists?callback=?', function(response){
$.each(response.data, function(i, gist){
$('#gists').append('<li>' + gist.user.login + " (<a href='" + gist.html_url + "'>" +
(gist.description == "" ? "undescribed" : gist.description) + '</a>)</li>');
});
});
});
</script>
</head>
<body>
<ul id="gists"></ul>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>An JSONP example </title>
</head>
<body>
<!-- DIV FOR SHOWING IMAGES -->
<div id="images">
</div>
<!-- SCRIPT FOR GETTING IMAGES FROM FLICKER.COM USING JSONP -->
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
format: "json"
},
//RETURNED RESPONSE DATA IS LOOPED AND ONLY IMAGE IS APPENDED TO IMAGE DIV
function(data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
});
});</script>
</body>
</html>
The above code helps in getting images from the Flicker API. This uses the GET method for getting images using JSONP. It can be found in detail in here

Resources