Send response from action method liferay - ajax

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.

Related

AspNetBoilerplate Ajax repose error despite 200 response code

Im having some unexpected problems with a ajax call within the aspnetboilerplate system.
I want to return an array to populate a select list,
The ajax call fires correctly and hits the controller. The controller returns the results as a model successfully, except it continually hits an error.
here is my controller action:
public async Task<List<DialectDto>> GetAllDialects(int Id)
{
var language = await _languageAppService.GetLanguage(Id);
return language.Dialects;
}
Here is my ajax call
var languageId = $(this).val();
abp.ui.setBusy('#textContainer');
$.ajax({
url: abp.appPath + 'Language/GetAllDialects?Id=' + languageId,
type: 'POST',
contentType: 'application/json',
success: function (content) {
abp.ui.clearBusy('#textContainer');
},
error: function (e) {
abp.ui.clearBusy('#textContainer');
}
});
Inspecting the return object in javascript clearly shows a 200 result with all the data in the responsetext property.
Other posts suggest that the content type isnt specified correctly and this is likely the a json parse error. Ive tried setting the dataType property to both 'json' and 'text' but still get the same response
I just had the same problem in one project. I'm using AspNet Boilerplate on a web .NET5 project.
Just like in your case I had a call to a controller method in my JavaScript code that returned 200 code, while in JS I had a parse error and then the "success" code was not executed. To solve the problem I changed the return value of my controller method. I used to return an IActionResult value (i.e. the Ok() value for ASP.NET). Then I changed the return value to another object (a DTO in my case) and everything went right afterwards. For reference:
Before (not working):
[HttpPost]
public async Task<IActionResult> Method([FromBody] YourClass input)
{
// method logic
return Ok();
}
After (working):
[HttpPost]
public async Task<DtoClass> Method([FromBody] YourClass input)
{
// method logic
return dtoClass;
}
I also tested that returning a JsonResult class works with the framework just like this (e.g. return new JsonResult(result)).
Hope this helps somebody else in the future :)

how to get request data in ajax success callback method

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.

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...
}
});

How to handle application errors for json api calls using CakePHP?

I am using CakePHP 2.4.
I want my frontend make api calls to my CakePHP backend using ajax.
Suppose this is to change passwords.
Change password action can throw the following application errors:
old password wrong
new password and confirm new passwords do not match
In my frontend, I have a success callback handler and a error callback handler.
The error callback handler handles all the non 200 request calls such as when I throw NotFoundException or UnAuthorizedAccessException in my action.
The success callback handler handles all the 200 request calls including of course, the above 2 scenarios.
My questions are:
Should I continue to do it this way? Meaning to say, inside all success callback handler, I need to watch out for application success and application error scenarios.
Should I send application errors back with actual HTTP error codes?
if I should do 2, how do I implement this in CakePHP?
Thank you.
Don't use http error codes for system errors like:
old password wrong
new password and confirm new passwords do not match
etc etc...
Now using success handler you can show messages and code flow as:
Create Ajax post or get to submit the form, I am showing you post example
var passwordValue = $('#password').val();
$.post( "/updatePassword", { passwordText: passwordValue })
.done(function(response) {
if(response.status === 'Success'){
// Success msg
// whatever
}else{
// Error msg
// whatever
}
});
json response would like:
{
"status": "Failed/Success",
"message": "old password wrong."
}
Create one function in controller
public function updatePassword() {
$myModel = $this->MyModel->find('first' // YOUR CODE LOGIC);
if($this->request->is('ajax') {
$this->layout=null;
// What else?
echo json_encode($myModel);
exit;
// What else?
}
}
Do something like this, hope it will solve your query!

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