how to create a new AJAX object using Prototype - ajax

How can i create a new Ajax object everytime for a particular ajax request, using Prototype library? It seems in Prototype, "Ajax" is a global object and all reqs are its instances. Please help..
Thanks

Actually, Prototype creates a new "instance" for each request. You do it like this:
var request = new Ajax.Request('/your/url', {
onSuccess: function(transport) {
// yada yada yada
}
});
Normally you skip the "var request = " part, unless you need access to the public properties of the instance. One possible reason would be to access the "transport" property which contains the "raw" XMLHttpRequest object.

Related

AngularJS: Setting Global Variable AJAX

I am looking for best practices with AngularJS:
I need to share a json ajax response between nested controllers.
Controller1->Controller2->Controller3
Right now I have a working version that simply sets a $scope.variable with the response in controller1, and the other controllers access it by calling the same variable.
I have tried creating a global service, but the problem is I make the ajax call in a controller, and before the ajax call is finished, the global variable defaults to null for all the other controllers.
I am just trying to understand what best approach is in this situation.
Thanks
Create publisher/subscriber service or factory and subscribe methods from your controller2 and 3 to data change. Just like this:
angular
.module('')
.factory('GlobalAjaxVariable', function() {
var subscribers = [];
function publish(data) {
callbacks.forEach(function(clb) {
clb(data);
});
}
return {
setData: function(ajaxData) {
publish(ajaxData);
},
addSubscriber: function(clb) {
subscribers.push(clb);
}
};
});
You can put the value in $rootScope.variable and after access it from any other controller (as $scope.variable)

angular $http service singleton clash

$http service in angular is singleton, and my previous experience with xhr/ ajax request shown to have clash when two request share the same xhr object. Should it not a problem with angular ? if yes how angular handles such situation ?
I think you're misunderstanding the fact that the $http service is a singleton to mean that all requests somehow will share the same XHR object. They don't.
The $http service itself is a singleton, but that doesn't mean that the requests share the same XHR object.
Anytime you call an $http service method (for example, $http#get), it initializes a new asynchronous request... However, it doesn't initialize a new $http object.
Take a look at some of Addy Osmani's sample code for the singleton pattern:
return {
getInstance: function () {
if ( !instance ) {
instance = init();
}
return instance;
}
};
The singleton pattern simply ensures that a new instance of the $http service itself doesn't get initiliazed over and over again... But it doesn't mean there is just one XHR object.
The pseudo-code for the $http service would look something like this:
var $httpProvider = (function() {
var somePrivateConfig = "something important";
var service = {
request: function() {
// make an HTTP request with an XHR object
}
};
return {
init: function() {
// this is the important part that makes sure its a singleton
window.$http = window.$http || service;
}
};
})();
/**
* Something like this would be called whenever you
* inject the $http service as a dependency...
* However, since it could be passed into multiple things all in the same runtime,
* like controllers, directives, etc., we only need to initialize it ONE time
*/
$httpProvider.init();
/**
* Now let's pretend we're inside, say, a controller.
*
* This method can safely be called many times,
* but the method is always being called from the same singleton object
*/
$http.request();
Also, you'll notice that there's a local variable somePrivateConfig within the $httpProvider IIFE. If we were to re-initialize a new $http every time its injected to a component (whether that's a controller, directive, or whatever), a new private variable would be created, but we always want to be referencing that same value throughout the lifecycle of the $http object, so that we can guarantee that all those components are always referencing the same information.
But this has nothing to do with the XHR object itself. I may have misused some of the terminology above and misrepresented where and how providers themselves within the context of AngularJS are initialized into singleton objects, but the principle of the singleton pattern still stands in that it simply means the async request wrapper "class" (which is the $http service) is a singleton, but the XHR isn't.
$http requests are async and return a promise with methods success() and error(). Below more information ($q service, which is an implementation of promises by Angularjs):
"A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing"
Read here:
https://docs.angularjs.org/api/ng/service/$http
https://docs.angularjs.org/api/ng/service/$q

can.Model destroy with multiple parameters

I'm working with an API over which I have no control. I would like to do something like this:
var Page = can.Model.extend({
destroy: 'DELETE /api/{account_id}/{page_id}'
})
This doesn't work - canjs simply doesn't use the destroy URL. I tried creating a function, but the only param passed is the 'id'. I'm sure you'll say that this is not really REST, but I'm stuck with the API. Any time I put more than one param into the url, the url is not used.
Any ideas?
You're actually setting the prototype destroy property to a string here, because the first object passed to extend() is interpreted as the prototype properties if a second object is not passed. You actually need to do this:
var Page = can.Model.extend({
destroy: 'DELETE /api/{account_id}/{page_id}'
}, {})
(NB: CanJS internally converts destroy and some other properties from AJAX specs to functions when you extend can.Model, but only in the static properties)
It seems this is OK (took a while to figure out that the 2nd parameter is the instance... didn't see that documented anywhere):
var Page = can.Model.extend({
destroy: function(id, page) {
return $.get('/api/'+page.account_id+'/'+page.id);
}
})
Which seems a bit weird, but I'll get over it!

Ajax request, should it be POST or PUT

I have created a Spring MVC web app.
The app makes a few calls to the controller. These calls are close/open/end game.
I make these calls using Ajax, so I can handle a response on the top of the page.
ajaxPost = function (url, action, id, onSuccess, onError) {
$.ajax({
type: "POST",
url: url + "?" + action + "=" + id,
success: function(response) {
if(onSuccess !== null) {
onSuccess(response);
}
},
error: function(e) {
if(onError !== null) {
onError(e);
}
}
});
};
The question I have is that I'm using 'POST' for the Ajax request, is that correct, or should it be 'PUT'?
My controller has a default URL, and I'm using the param attribute to decide which method to call, as I have many buttons on the page.
#RequestMapping(params = "open", method = RequestMethod.POST)
#RequestMapping(params = "close", method = RequestMethod.POST)
It doesn't sit well with me that I'm using 'POST' for these calls. Maybe it should be 'PUT'...
Any suggestions? Does it matter?
It depends on what your request should do. So there's no general rule that you should use one over the other, they have different use cases.
POST for creating a record.
PUT for updating an existing record (or putting a record at a specified location/id).
See this wikipedia article for the definitions.
One thing to note is that PUT should be idempotent, doing the same PUT request multiple times should ideally produce the same result as doing a single PUT request. However, POST is not idempotent, so doing several POST requests should (or will) create multiple new records.
So after having read this you should check what your method does, and select the corresponding request method.
Both PUT and POST may create a new record; PUT may also update/change an existing record.
The difference between POST and PUT is that PUT is expected to address the record with it's ID, so that the server knows what ID to use when creating (or updating) the record, while POST expects the server to generate an ID for the record and return it to the client after the record has been created.
Thus, a POST is addressed to the resource as a collection: POST /resource, while PUT is addressed to a single item in the collection: PUT /resource/1
Use POST. Always use POST, unless you're absolutely rock-solid certain that PUT is properly supported by your hosting system.

Debugging Ajax requests in a Symfony environment

Not sure if SFDebug is any help in this situation. I am making an ajax post using jQuery. Which retrieves JSON data in my action URL and then makes a call to the Model method that executes the action. The part until my action URL, and the jQuery call to it work fine. With the data transmitted from the client to the server well received and no errors being made.
It is the part where it calls the method on the Model that is failing. My jQuery method looks like this:
$.post(url, jsonData, function(servermsg) { console.log(servermsg); }) ;
My server action is like this
public function executeMyAjaxRequest(sfWebRequest $request)
{
if($request->isXmlHttpRequest())
{
// process whatever
$servermsg = Doctrine_Core::getTable('table')->addDataToTable($dataArray);
return $this->renderText($servermsg);
}
return false;
}
The method of concern in the Table.class.php file looks like this:
public function addDataToTable($dataArray)
{
// process $dataArray and retrieve the necessary data
$data = new Data();
$data->field = $dataArray['field'];
.
.
.
$data->save();
return $data->id ;
}
The method fails up here in the model, when renderText in the action is returned and logged into the console, it returns the HTMl for SFDEBUG. Which indicates that it failed.
If this was not an Ajax call, I could debug it by seeing what the model method spat out, but this is a little tedious with Ajax in the mix.
Not looking for exact answers here, but more on how I can approach debugging ajax requests in a symfony environment, so if there are suggestions on how I can debug this, that would be great.
You must send cookie with session ide key via ajax
(Assuming you have XDEBUG configured on the server)
In order to trigger a debug session by an AJAX request you have to somehow make that request to send additional URL parameter XDEBUG_SESSION_START=1. For your example:
$.post(url + '?XDEBUG_SESSION_START=1', jsonData, function(servermsg) { console.log(servermsg); }) ;
You can also trigger it via cookie, but appending URL parameter usually easier.

Resources