How to run code if yepnope returns true? - yepnope

I use yepnope.js to load a polyfill (Intl). If window.Intl doesn't exist, it loads my polyfill, and executes some code. However, if windows.Intl does in fact exist, I need to execute another code, and I havn't been able to figure out how.
Here is what I have:
yepnope({
test : window.Intl,
nope : ['lib/Intl.min.js'],
callback: function(u,r,k){
$.ajax({
type: "GET",
url: 'sv-SE.json',
dataType: "json",
success: function(data) {
Intl.__addLocaleData(data,"sv-SE");
self.numberFormatter = new Intl.NumberFormat("sv-SE");
}
});
},
complete: function(){
/* Do stuff! */
The code I need to run if window.Intl already exists is self.numberFormatter = new Intl.NumberFormat("sv-SE");, but I can't figure out how, as callback is only called on false, as far as I can tell.

Related

Ajax not passing values

WordPress
I have a ajax function passing value to a function in functions.php
The function on functions.php sends the response to ajax success but the value I am passing using ajax is not going to the function in functions.php
$.ajax({
url: ajaxStuff.ajaxurl,
type: "GET",
processData :true,
data: {
action: 'filter_package',
value: data,
},
success: function (data) {
alert(data);
},
});
The console.log for data shows as:
{cat_names: Array(1), reg_names: Array(0), dest_names: Array(0), fromPrice: '', toPrice: '', …}
which is correct one.
If I enter some hardcoded message to my filter_package function in functions.php the ajax shows the response which means the ajax function hits my function on functions.php but when I try to get the data from ajax on my function I shows Array0
function filter_package()
{
$value = $_REQUEST['value'];
$cat_slug = $value['cat_names'];
echo 'sadasd'.$cat_slug;
The output:
sadasdArray0
check your ajax url and make sure admin.ajax hit correctly in networkbdev tools
also can check Ajax call to PHP action/function with array as data (in wordpress)

Upload file size limit with custom webscript on Alfresco Community 5.2

I need help to upload document content back in Alfresco Community 5.2 though a share javascript.
The destination noderef is already existing, I upload a new version of a document.
I can't use the api/upload web service because I also need to do some operation on the noderef and I have a base64 content of the file which need to be converted.
So I wrote a new webscript and it is all working fine, at least while I upload documents which are smaller than 3MB,
Here it is the code
Alfresco.util.Ajax.request({
method: Alfresco.util.Ajax.POST,
dataObj: {
bytes: response.bytes,
digestAlgorithm: response.digestAlgorithm,
mimeType: response.mimeType.mimeTypeString,
name: response.name,
nodeRef: this.nodeRef,
signatureLevel: this.signatureLevel
},
url: thisClass.urlAlfrescoService + "myOrg/myPackage/uploadDocument",
successCallback: {
fn: thisClass._successOnUploadContent,
scope: this
},
failureCallback: {
fn: thisClass._errorOnUploadContent,
scope: this
},
scope: this,
noReloadOnAuthFailure: true
});
Do I miss some option to increase max upload file size?
I tryed uploading the file normally (with drag and drop) and it works.
The problem is when the file is >= 3MB the java class behind the webscript does not receive any byte
UPDATE
After some researches I found it could be a problem of how data are passed through POST, as application/x-www-form-urlencoded instead of multipart/form-data, but I can't find a way to specify the request content type in the ajax request
SOLUTION
The problem was the application/x-www-form-urlencoded instead of the multipart/form-data, I used a fetch POST request as stated here, but also the ajax request solution is good.
Last week,I had a same very similar problem with Alfresco AJAX request on Alfresco 5.0.2.5 and I used jquery's AJAX calls and it worked for me.
$.ajax({
url: Alfresco.constants.PROXY_URI + "your_web_script",
type: "POST",
data: dataFromFiles,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
dataType: "text",
success: function(data, textStatus, jqXHR) {
},
error: function(jqXHR, textStatus, errorThrown) {
}
});
Reference link : https://blog.arvixe.com/sending-multipart-form-using-ajax/
Hope this helps you.

Angular.js simple get object from ASP.NET controller

Been some time since I last looked at Angularjs. I have a simple get that calls an ASP.NET Controller and returns a Json object - the get is triggered but nothing is getting populated on the view. The Json object shows in the browser, so it's purely a JS Angular thing. I know I am missing something simple, but I can't quite put my finger on it. If someone would be kind enough to show what I'm missing preferably with an example that would great. I haven't been able to find a simple example, that's similar.
Angularjs.
var ngCurrent = angular.module("ngCurrent", ['ngResource']);
var ctrCd;
// Declaring a Service
ngCurrent.factory("CurrentService", function ($resource) {
return {
data: $resource("/Current/Data/:id")
}
});
ngCurrent.controller("CurrentController", function ($scope, CurrentService) {
$scope.current = CurrentService.data.get({ "id": id}, isArray = false);
});
In the CSHTML View (Condensed but all relevant rows included)
<div ng-app="ngCurrent" class="row">
<div ng-controller="CurrentController" class="col-md-1"></div>
<div class="row">
<span class="col-sm-2">{{current.RecordName}}</span>
It runs triggers the "Get" from the controller but displays no data and $scope.current contains no object.
I have had a go at JSFiddling without success here it is http://jsfiddle.net/Mark_Dete/Lfy66re1/1/
(note the Json mocking is based on http://jsfiddle.net/ExpertSystem/6PYsq/)
You can return a promise from your service like:
return $http({
url: '/api/v1/service/',
method: "GET",
headers: {'X-API-TOKEN': api_key },
params: _params
})
Then use the promise callbacks on the http object in your controller (the one returned from your service)
$scope.getApiData = function(){
Service.getData($scope.api_key)
.then(function(_data) {
console.log(_data.data);
$scope.data_obj = _data.data;
});
here's an all in one version without the service abstraction but it should work for testing.
$scope.getApiData = function(){
$http({
url: '/api/v1/service/',
method: "GET",
headers: {'X-API-TOKEN': api_key },
params: _params
})
.then(function(_data) {
console.log(_data.data);
$scope.data_obj = _data.data;
});
Make sure you remember to inject the $http dependency!

Mustache JS Template with JSON Collection

Hi this is my first attempt to use MustacheJS with a JSON webservice in .net
Currently I am struggling I can't seem to find what I am doing wrong setting this basic example:
My Webservice is returing the following string:
[
{
"ShortDescription":"BOX",
"Description":"BOXING",
"Id":1
},
{
"ShortDescription":"EPL",
"Description":"ENGLISH PREMIER LEAGUE",
"Id":2
}
]
I have validated its syntax with this website: http://json.parser.online.fr/
and here is the HTML code I am using:
google.load("jquery", "1");
google.setOnLoadCallback(function () {
$(document).ready(
function () {
$.ajax({
url: "../data.asmx/geteagues",
type: "POST",
dataType: "json",
data: "",
contentType: "application/json; charset=utf-8",
success: function (data) {
var template = "<h1>{{ShortDescription}} {{Description}}</h1>";
var html = Mustache.render(template, data);
$('#sampleArea').html(html);
alert(html);
}
})
}
)
});
I am posting the whole JS code, since I am not very good with javascript, basically I want to load always the latest JQuery version from google and then work my WS call.
The problem so far is that when I place a breakpoint in the following line:
var html = Mustache.render(template, data);
I see that the template is setn ok, and so does the data, same value as I posted above, but the .render function is returning: I seems It didnt like the data.
So far all the examples I have seen for inline data come as the following structure:
{
"repo": [
{ "name": "resque" },
{ "name": "hub" },
{ "name": "rip" },
]
}
And then a template defined like this:
{{#repo}}
<b>{{name}}</b>
{{/repo}}
But the only difference of that against my data is that I dont have a "parent" like "repo"
At server side, I am using a .net library called JSON.net and in the documentation of how are collections being serialized:
james.newtonking.com/projects/json/help/html/SerializingCollections.htm
the final result does not include the parent node's name, which I thing is missing from my Mustache Template definition:
[
{
"Name": "Product 1",
"ExpiryDate": "2000-12-29T00:00Z",
"Price": 99.95,
"Sizes": null
},
{
"Name": "Product 2",
"ExpiryDate": "2009-07-31T00:00Z",
"Price": 12.50,
"Sizes": null
}
]
Is this what I am missing? the "repo" parent node from my data so I can iterate my Template?
Thanks in advance for your time.
-ed
Per #stealth on this question Mustache.js: Iterate over a list received via json
{{ #. }}
<b>{{Name}}</b>
{{ /. }}
Note the only difference from #stealth's answer is a "#" instead of "/".
The line data = { 'roles': data }; is the most crucial. Its attaching the key to the data returned by web api or any other source of data like pagemethods or web service
$.ajax({
dataType: "json",
url: '/api/TestApi/GetAllRole',
success: function (data) {
data = { 'roles': data }; // formatting the data to support the mustache format
var html = Mustache.to_html($('#RoleTemplate').html(), data);
$('#tblRole').append(html);
}
});
Few of my articles on the MustacheJs can be found here
INLINE FILTER FOR BASIC GRID USING MUSTACHEJS
http://www.techguides.in/add-inline-filter-to-basic-grid-using-mustache/
Master Details Grid on Demand data loading : Using Mustache.JS
http://www.techguides.in/master-details-grid-on-demand-data-loading-using-mustache-js/
Sorting a Grid using MustacheJs
http://www.techguides.in/enable-sorting-in-a-grid-bound-using-mustache-js/
short answer: YES
long answer: for security reasons [1], you need to wrap your JSON aray in an object anyways. for Mustache or any other library to be able to access your array you need to have at least one parent key on which you can base your iterator.
The "repo" key on your sample is the helper you need to tell mustache "go and iterate on the array that is inside the repo key", otherwise you have no way to tell the template what you want to output where
[1] this is just one of many resources you can find about why you need to wrap your JSON response in an object http://incompleteness.me/blog/2007/03/05/json-is-not-as-safe-as-people-think-it-is/

how do you pass a parameter to an asp.net page method using jquery/ajax?

I'm trying to pass parameters to my static web method (which is in an asp.net page). I'm trying to pass the "test1" param with a value of "myvalue". Any ideas on what I am doing wrong?
$.ajax({
type: "POST",
url: "WebForm1.aspx/WebMethod1",
data: {"test1": "myvalue"},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
}
});
my "data" section was wrong. it needs to be "{'test1':'myvalue'}"
What error are you getting?
I've used prototype before (similar to jQuery for ajax) and with that you don't quote the parameter names. So your data parameter should probably be:
data: {test1: "myvalue"}
Give that a shot.
You could also try setting up Fiddler and see the actual request being made.
The way you have it set up, any error that may occur in the ajax call will get silently swallowed. I'd suggest adding an error callback like this:
$.ajax({
type: "POST",
url: "WebForm1.aspx/WebMethod1",
data: {"test1": "myvalue"},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
},
error: function(response) {
$('body',document).html(response.responseText);
}
});
Also, if you are using Visual Studio, you could run your ASP.NET app in debug mode to catch any server-side error. You can also put a breakpoint somewhere in the server-side code to make sure it's getting hit at all, and to inspect the Request.Form collection.
Hope this helps.

Resources