Debugging Ajax requests in a Symfony environment - debugging

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.

Related

How to prevent server call for empty string in Select2 with remote data?

I noticed that the Select2 widget serving options with remote data was making a call even when I enter just empty spaces. This usually returns me an empty array, but I would like to eliminate this call altogether.
So here is what I did.
The Select2 plugin allows us to define our own AJAX call handler via the transport option.
From the docs :
Select2 uses the transport method defined in ajax.transport to send requests to your API. By default, this transport method is jQuery.ajax but this can be changed
So here is how you can eliminate the unnecessary call altogether.
$('select').select2({
...
ajax: {
transport: function (params, success, failure) {
if (!params.data.q.trim().length) {
return false;
}
var $request = $.ajax(params);
$request.then(success);
$request.fail(failure);
return $request;
}
}
...
})
A more detailed snippet at my blog.
Select2 has a minimumInputLength option which will handle this for you. It will display a notice when the user needs to enter more characters, and then send the request out when enough have been entered.

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.

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!

JSON data From phpFox ajax call?

How to return JSON data in phpFox, ajaxCall?
In phpFox i am using $.ajaxCall('samplemodule.function' 'data=test');
How to return JSON data? and how to process on that data inside any js function.
In the file /module/samplemodule/component/ajax/ajax.class.php, create a function named function (per your example).
Inside that function, use this to return data back to the JS you're making your ajax call in:
$this->call('var myJSONObject=' . json_encode('Your Data Here'));
Or send something more interesting, instead of data=test, lets do userId= (their user ID) like this:
$iUserId = Phpfox::getLib('request')->getInt('userId');
$aUser = $aUser = Phpfox::getService('user')->getUser($iUserId);
$this->call('var aUser =' . json_encode($aUser));
Now you have aUser set up as a JSON object with the user's info loaded in to it.
I think the problem is that you are confused as to how an ajax call works. In an ajax call your JS code will send a request to the server and continue executing the remaining javascript code, regardless of what happens in the server. So what you do is to return code from the ajax call:
JS Code -> Ajax Call -> Process in server -> JS Code
In that logic aboce, the last JS Code would call a javascript function with info taken from the "Process in server" stage, you can call a function and pass params to that functions, these params may be JSON objects if you wish.
I made a sample of how to do this in phpfox (ajax call + call JS function with JSON param) here, hope it helps

Testing Ajax Request in Cakephp 2.0

I have an action in my controller which does something only if the request is an XmlHttpRequest, like this:
function myAction() {
if( $this->request->is('ajax') ) {
doSomething();
}
}
What would a TestCase for this action look like? Is there a way to mock up the CakeRequest instance to appear as an Ajax request?
I don't know if it is a good way or not, but adding
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
at the top of the test method will do the job. In this case we send data as Ajax so not need to check any more.
we use a trick to solve ajax unit test for cake2.0
as cake supoprts .json extention, we create a function in AppModel to cheat ajax call. like
public function isAjax() {
return $this->request->isAjax() || $this->request->ext == 'json';
}
Then in controller, instead of calling $this->request->isAjax(), $this->isAjax() is used.
When testing action with ajax call, we simply add suffix .json to the action call, For example,
$this->testAction('/users/register');
This might not be the ultimate solution for ajax call test, but could be a workaround

Resources