how to get request data in ajax success callback method - ajax

I do ajax request in foreach and question is that how to get request data in success callback or how to match response data and request.
Thank you in advance!

Something like this:
var makeRequest = function(data){
doAjaxRequest(data, function(dataFromServer){
console.log(data);
});
}
array.forEach(function(element){
makeRequest(element.getData());
}
What this does is for each element in array, the variable data is different because it refers to the local scope of the function makeRequest. This way, each callback refers to the proper data.

Related

AJAX how to return a value

I know this is a question that's been asked to death, but I still struggle with how to use callbacks. I just want to return a value from the ajax's request.done outcome. I tried to follow Felix Kling's very informative answer on using callbacks with AJAX, but can't get my code to work.
My code below submits a form with user input data to the database. I would like it to retrieve the property employeeId. I am able to alert the correct value inside the submit function, but I would like to use this value in other functions. From reading up on asynchronous functions,i think this is because submit function exits before returning the value. I would really appreciate some guidance on using callbacks to return values.
I tried to only include the code pertaining to my issue
$('#employeeForm').submit(function(event,callback){
var values = $(this).serialize(); //gather form data
var result = foo(); //callback implementation from Felix Kling's SO answer
foo(function(result){
var request = $.ajax({
url: "game.php",
type:"post",
dataType:"json",
data: values
});
function foo(response.employeeId){ //I am trying to return value response.employeeIda in the success situation
request.done(function (response,textStatus,jqXHR){
document.getElementById("submitEmployeeInfo").innerHTML=response.employeeId;
var employeeId = response.employeeId;
}
});
})

Backbone fetching a collection using callbacks vs promises

I have a Location collection, and I have back a JSON response from the serve r on fetch including the root title with format:
{'locations':[
{
"id": 1,
"address": 'first address'
},{
"id": 2,
"address": 'second address'
}
]}
I've read everywhere that is best practice to use promise's methods over backbone success and error callbacks but here is the thing. I have override the parse method on the Location collection to return the array, but it appears that using the promises methods the parse method isn't called at all. So for example:
var Locations = new Backbone.Collection.extend({...})
var locations = new Locations()
locations.fetch().then(function(response){
console.log(response)
})
returns an Object literal with property locations which has the value of the Array of locations. But if I use
locations.fetch({
success: function(response){
console.log(response)
}
})
I get the wanted behavior, that is the object with constructor Locations and all the models in it.
Plus if I remove the root title of the JSON response on the backend and remove the parse method override on the collection, with the promise methods I'm getting an object with constructor Array, while with the success callback I'm getting an object with constructor Locations.
So my question is, if it is better to use the promise's methods how to adopt them with the similar behavior as the success and error callbacks?
Requsted update:
Here is the parse function in the Locations collections
var Locations = new Backbone.Collection.extend({
parse: function(response){
return response['locations']
}
})
Use the collection directly:
locations.fetch().then(function(){
console.log(locations);
})
The fetch method returns the jqXHR promise that makes the request, so it returns the raw response received from the server. The promise doesn't know about the parsing of the response.
The reason that passing a success callback as an option to fetch worked for you is: (See Collection.fetch documentation)
The options hash takes success and error callbacks which will both be passed (collection, response, options) as arguments.
So if use pass a success callback to fetch, the first argument is actually collection, not response.

Send response from action method liferay

I have an actionURL in my jsp from which I am calling a method called "updateDB" in my java file.
whenever I submit the form through an AJAX request using A.io.request , this udpateDB function in my java code is being called, where I am doing some database CRUD operations.
I want to know how can I send some values(either success/failure status of database insertion) back to my jsp from java code to the success callback of my A.io.request ajax call.
You can find below my Ajax request :
Liferay.provide(window,‘submitForm’,
function() {
var A = AUI();
A.io.request(‘${”formsubmissionURL”}’,{
method: ‘POST’,
form: { id: ‘<portlet:namespace />fm’ },
on: {
success: function(){
alert(form submitted”);
// I WANT DATABASE SUCCESS OR FAILURE STATUS HERE FROM JAVA CODE
}
}
});
});
Thanks
You can pass data values by writing it to resourceResponse.
response.getWriter().write(String/int/char[])
Here, response can be servletResponse or portletResponse(resourceResponse)
You can get data in javascript like
this.get('responseData') inside success method.
EDIT:
As you are calling action method via ajax call, below code may be helpful.
PortalUtil.getHttpServletResponse(actionResponse)
Get httpServletResponse from code above and then you can use response.getWriter().write method.

Unable to consume an Angular service from a Controller

So I've done extensive research and read many tutorials but I can't find a straightforward answer to what I'm trying to accomplish.
I'm simply trying to access a JSON object stored at JSON-Generator.com and stick it in a table and repeat it. Sounds simple enough but it seems there many different ways to do this and all the sources leave out the one piece of info I need.
if I console.log eventsService inside the controller it returns a constructor, if I console.log eventsService.data it returns undefined.
How do I access the data returned from $http in my controller?
// CONTROLLERS
app.controller('currentTradeshowsController', ['$scope', 'eventsService', function($scope, eventsService){
$scope.events = eventsService.data;
}]);
// SERVICES
app.service('eventsService',function($http){
var eventsUrl = 'http://www.json-generator.com/j/bVWJaYaWoO?indent=4';
$http({method: 'GET', url: eventsUrl}).
success(function(data){
// not sure what to write here....
return data;
})
.error(function(){
console.log('ah shit');
})
});
first of all, $http call is asynchronous, so you probably want to use promises to load the data correctly into scope variable
second - you need to return something from the service to make it work outside of the service declaration function
controller
app.controller('currentTradeshowsController', function($scope, eventsService){
eventsService.getData().then(function(data) {
$scope.events = data;
});
});
service
app.service('eventsService',function($http){
var eventsUrl = 'http://www.json-generator.com/j/bVWJaYaWoO?indent=4';
return {
getData: function() {
return $http.get(eventsUrl);
}
}
});
$http.get is a shorthand for GET request, and it returns a promise, so you can simply use it with .then in the controller

Ajax call return json to model I can use data from in my own function

New to Backbone, so I may be over/under complicating things. (built spa's with my own functions in the past)
Psudo code of what I used to do:
AjaxCall(
url: "get json result"
success:
parse json
call Update(json.a, json.b)
)
function Update(a, b){
//do something with a/b var's
}
For a more abstract idea of what I am envisioning atm. If I click an update button, I want it to hit the server and return a success/fail status along with an Id and a message (imagining all in json format).
Found a few examples, but none seem to fit so far.
To do that, you'd use a Backbone model:
var Message = Backbone.Model.extend({
urlRoot: "messages"
});
var myMessage = new Message();
myMessage.save({}, {
success: function(model, response, options){
// code...
},
error: function(model, xhr, options){
// code...
}
});
Basically: the model configures the API call, and save will use backbone's sync layer to handle the actual AJAX. You can pass success and error callbacks to the `save function.
The first parameter to the save function are the attributes which are to be saved (see http://backbonejs.org/#Model-save), which seem to need to be empty according to your question.
Since the model instance has no id attribute, the save call will trigger a POST request to the API. If by any chance you actually need to provide an id (so that a PUT call gets triggered instead), simply do
myMessage.save({id: 15}, {
success: function(model, response, options){
// code...
},
error: function(model, xhr, options){
// code...
}
});

Resources