Call AMFPHP from Angular or Javascript - javascript

Hi I have a project in Flash, which calls the AMFPHP for server side integration. Now I want the same connection with Angular JS or any Javascript. So is it possible to make this happen? Actually I don't want to change the Server, because of some issue. I can change the Client Side. So please let me know, if its possible. I tried http://www.bennadel.com/blog/2612-using-the-http-service-in-angularjs-to-make-ajax-requests.htm URL but no success.

I can provide you with a jQuery ajax call. It's almost as simple as this:
<script language="javascript">
function call(){
/**
* notes:
* - parameters here could be left empty, they are just here to make the code easier to adapt
* - $.post method here is used because amfPHP JSON plugin expects data as POST. So can't use more obvious getJSON
* - if you always use the same parameters, you can do without json2.js, by setting for example
* callData = '{"serviceName":"PizzaService", "methodName":"getPizza","parameters":[]}'
*/
var callData = JSON.stringify({"serviceName": "YourController", "methodName": "getSomething", "parameters": []});
$.post("../amfphp/?contentType=application/json", callData, onSuccess);
}
function onSuccess(data){
alert("pizza : " + data);
}
</script>
The important key notes here are:
?contentType=application/json
At the URL Query. That will tell AMF that you want it to return a JSON format instead of a AMF Request.
Now, since you're going with AngularJS, one more thing you should be aware is the fact that angular already sets ajax communication with applicatio/json. So I can't really tell you how amfPHP will handle this. Personally, I believe that if a jQuery call querying an application/json works successfully, your Ajax call from AngularJS will work automatically. If it doesn't, you can try to debug amfPHP and try to see if $_POST or $_REQUEST is being feeded.
You may find some additional information about angularJS and PHP here.

You should be able to use the library I linked above and
$httpProvider.defaults.transformRequest
$httpProvider.defaults.transformResponse
you can configure the $http provider in an angular config block. Something like
angular.module('myApp',[]).config(function($httpProvider){
$httpProvider.defaults.transformRequest = AMF.stringify;
$httpProvider.defaults.transformResponse = AMF.parse;
});

Related

How do I pass node.js server variables into my angular/html view?

I have this route in my app.js file that starts the server
app.get('/view/:item_id', function(req,res){
var A = 5;
res.render('view_item');
and I have this in my view_item.html:
<p>{{A}}</p>
I want it to display the variable value - 5. If I were using a template engine such as jade it would be easy. I could change that third line of my server code to res.render({A:A},'view_item');
But I am using html as my template engine. My research so far has told me that using a template engine with angular is usually a bad idea, and there is always a way to do it using angular's built in template system. So how do I do this? Do I somehow pass it to the $scope and include like
<script>
$scope.A = {{A}};
</script>
I haven't seen this done anywhere so I don't think its the way to go.
This is a two step process.
First, you need to use a library(server library) like express in node to set the proper routings (REST Services) to respond to your Requests:
Server Side
//app = express();
app.get('/api/:paramID1/:paramID2',function(req, res){
return res.json({ A: 5 });
});
On the client side, you need an ajax call to invoke the service like:
$http.get( "/api/1/abc").success(function( data ) {
$scope.A= data; //from your sample;
alert( "Load was performed. " + data );
});
Please note that when using REST there are different type of "methods" that can be invoked depending on your needs, such as POST, DELETE, UPDATE or the one just mentioned in the example GET.
If you are using Angular you should probably be building a single page app -- this would apply for most of the modern front end frameworks. For SPAs you start out with a basic html file (probably index.html). Then, your framework handles the rendering of everything else. Your server may also emit templates, but it will never render anything itself.
app.get('/view/:item_id', function(req,res){
This shouldn't be rendering anything or returning HTML. Instead, you should be returning data that the front end will use to render -- preferably as JSON.
res.json({A: 5});
Then with Angular you would do something like
$http.get("/view/1").success(function (data) {
ctrl.A = data.A;
});
Your html/template would have something like
<div ng-controller="ctrl as ctrl">
<div>{{ctrl.A}}</div>
Once $http.get completes, ctrl.A is populated.

How to pass parameters to a javascript ajax POST so that Rails will interpret them?

In a Rails 3.2 app I have a coffeescript function that includes a POST to create an Asset with attached file (using Carrierwave)
link = url_to_file
parent = $('#dom_obj').data('id')
$.post( url, { remote_file_url: link, parent_id: parent } )
This gives the following log:
Started POST "/assets" for 127.0.0.1 at 2013-10-05 14:53:57 +0700
Processing by AssetsController#create as JS
Parameters: {"remote_file_url"=>"https://the/correct/path", "parent_id"=>"520"}
In the controller
#asset = Asset.new(params[:asset])
#asset.save
I have some other methods to create an Asset, they all work fine. The variables passed into this ajax call are also correct. But #asset.save is failing due to an error in the uploader which implies that the parent_id is not being set correctly.
As all the components of this work perfectly via other upload pathways, my only conclusion is that the jquery ajax call is incorrect, and I guess I'm not setting the parameters correctly (would params[:asset] in my controller correctly interpret the parameters logged above?).
How to pass parameters to a javascript post so that Rails will interpret them correctly? Any guidance much appreciated as I'm going round in circles!
from the log you provided, there is no such thing called params[:asset] provided by your POST call. So, what would work is to do that in your controller
#asset = Asset.new(params)
#asset.save
or if this doesn't work you could try
#asset = Asset.new(:remote_file_url => params[:remote_file_url], :parent_id => params[:parent_id])
#asset.save
or another solution would be to not change your controller but change your form input names in your html to asset[remote_file_url] and asset[parent_id]

Is there a project that auto-generates JavaScript proxy code to call ASP.NET MVC action methods?

Is there c# code that takes an existing controller, analyse its public Action methods and generate a JavaScript proxy class so that it can be easily called by other Javascript code? I already know we can use jquery to do a $.post and $.get to call our ajax services but I believe the process can be simplified by not having to specify the relative url of the AJAX web service URL and a parameter name for each parameter input.
For example, let's say we have the following C# controller:
public class CustomerController : Controller
{
public JsonResult Create(string name, string address)
{
return new JsonResult {Data = 11111};
}
public JsonResult Update(int id, string name, string address)
{
return new JsonResult {Data = true};
}
}
I would like to call the controller's AJAX action methods by using the following fashion.
Proxy.Customer.Create("Scott Gu", "Somewhere in Redmond").done(function(id) {
/* id is an int and not an string */
Proxy.Customer.Update(id, "Scott Gu", "Somewhere in Seattle");
});
Does a project exist that allow me to do this?
Update
it turns out there's no project that does what I asked for. Something that could be of use, besides SignalR, is Phil Haack's Controller Inspector project. It can inspect any given controller and reveal what action method it has, the parameters it accepts, their types, etc.
The following link contains the getter method for retrieving a details about a given controller.
https://github.com/Haacked/CodeHaacks/blob/master/src/MvcHaack.ControllerInspector/ControllerDetailer.cs
Update 2
Doh. Phil Haack already developed a JavaScript proxy. Tutorial can be found here.
I know, it's an old question, but I just found a project which seems to match your requirements:
ProxyApi by Steve Greatrex
http://blog.greatrexpectations.com/2012/11/06/proxyapi-automatic-javascript-proxies-for-webapi-and-mvc/
I don't know of a project that does exactly what your after but have you looked at SignalR by David Fowl? This project has a javascript proxy generator based off a SignalR hub rather than an MVC controller. I'm sure the code can be modified though.
If you get the source code from github and look at the sample project there's a chat room sample. Using firebug/chrome dev tools etc you can see the javascript that is called.
From what I've looked at the javascript is created through a proxy. In the sample project there's a "hubs" folder that has methods that get inserted into a javascript file via the proxy.
The actual proxy stuff is done in the core SignalR library here, this is the default javascript proxy generator used.
You can see a live sample of the chat here, David Fowl is sometimes in the room as well. I'm sure he can explain the proxy stuff much better than myself.
Phil Haack has a project that solves 1 of my needs. It still require pairing each parameter input with a parameter name. Here's a tutorial.
This excellent another project allows you to do what you asked for.
http://jsnet.codeplex.com/
This poject auto-generates JavaScript proxies for MVC and WebApi controllers.
With this project, you will have also the Intellisense.
Example
window.test = function test() {
/// <summary>
///This example works.
///You have the Intellisense. It's great!!!
///No hard coded url.
///</summary>
//-- settings of ajax request.
var a = $dpUrlSet.Customer.Create.$action0.$AjaxSettings();
//-- your parameters of action method
a.data.name = "Scott Gu";
a.data.address = "Somewhere in Redmond";
//-- stringify
a.data = JSON.stringify(a.data);
//-- send ajax request
var xhr = $.ajax(a);
xhr.success(function (id) {
/// <summary>Response of ajax request</summary>
//-- settings of ajax request.
var a = $dpUrlSet.Customer.Update.$action0.$AjaxSettings();
//-- your parameters of action method
a.data.id = id;
a.data.name = "Scott Gu";
a.data.address = "Somewhere in Seattle";
//-- stringify
a.data = JSON.stringify(a.data);
//-- send ajax request
var xhr = $.ajax(a);
});
}

Check iframe status after AJAX File Upload with Rails

There is a similar post Retrieving HTTP status code from loaded iframe with Javascript but the solution requires the server-side to return javascript calling a function within the iframe. Instead, I would simply like to check the HTTP status code of the iframe without having to call a function within the iframe itself since my app either returns the full site through HTML or the single object as JSON. Essentially I've been trying to implement a callback method which returns success|failure dependent upon the HTTP status code.
Currently I have uploadFrame.onLoad = function() { ... so far pretty empty ... } and I am unsure what to check for when looking for HTTP status codes. Up until now, I've mainly relied upon jQuery's $.ajax() to handle success|failure but would like to further understand the mechanics behind XHR calls and iframe use. Thanks ahead of time.
UPDATE
The solution I came up with using jQuery
form.submit(function() {
uploadFrame.load(function() {
//using eval because the return data is JSON
eval( '(' + uploadFrame[0].contentDocument.body.children[0].innerHTML + ')' );
//code goes here
});
});
I think the best solution is injecting <script> tag into your iframe <head> and insert your "detecting" javascript code there.
something like this:
$('#iframeHolderDivId').html($.get('myPage.php'));
$('#iframeHolderDivId iframe head').delay(1000).append($('<script/>').text('your js function to detect load status'));
Maybe it's not the best solution but I think it works

Loopback jQuery AJAX Request

What is the best way to build a loopback URL for an AJAX call? Say I have a page at
http://www.mydomain.com/some/subdir/file.php
that I want to load with an AJAX call. In Firefox, using jQuery this works fine:
$.post('/some/subdir/file.php', ...);
Safari/WebKit tries to interpret this as a location on the local filesystem (so it ends up translating to 'file://some/subdir/file.php'). Not only does this not point to anything useful, it also results in a security error.
Is there a way to accomplish this without hard-coding the domain into the URL? I'd like to make this as domain-independent as possible.
Update
I ended up parsing out the base url from location.href and throwing it into an accessible jQuery function like this:
/**
* Retrieves the current root URL.
*
* #return string the root URL
*/
$.fn.rootUrl = function() {
var url = location.href;
return url.substring(0, url.indexOf('/', 7));
};
Wow, that's pretty poor of Safari/WebKit, IMO.
You could observe document.href, count the slashes, and add that many "../" to the beginning of your URL.
You could have the server insert its own URL as a javascript variable when it serves up the page, then use that variable as part of your Ajax calls. It would then be both secure and automatic.
Alternatively, you can assemble your URL as follows:
'http://'+document.domain

Categories

Resources