Decoding response error in extjs - extjs3

I am doing the following stuff when a form is submitted. But I get this error:
Error decoding response: SyntaxError: syntax error
Here is my onSubmit success function:
onSubmit: function() {
var vals = this.form.getValues();
Ext.Ajax.request({
url: 'ticketSession.php',
jsonData: {
"function": "sessionTicket",
"parameters": {
"ticket": vals['ticket']
}
},
success: function( result, request ) {
var obj = Ext.decode( result.responseText );
if( obj.success ) {
//alert ('got here');
th.ticketWindow.hide();
Web.Dashboard.loadDefault();
}
},
Here is my ticketSession.php
<?php
function sessionTicket($ticket) {
if( $_REQUEST['ticket'] ) {
session_start();
$ticket = $_REQUEST['ticket'];
$_SESSION['ticket'] = $ticket;
echo("{'success':'true'}");
}
echo "{'failure':'true', 'Error':'No ticket Number found'}");
}
?>
I also modified my onsubmit function but didnt work:
Ext.Ajax.request({
url: 'ticketSession.php',
method: 'POST',
params: {
ticket: vals['ticket']
},
i am simply echoing this but I still get that error
echo("{'success':'true'}");

Maybe this can help you. It's a working example of an ajax-request which is nested in a handler.
var deleteFoldersUrl = '<?php echo $html->url('/trees/delete/') ?>';
function(){
var n = tree.getSelectionModel().getSelectedNode();
//FolderID
var params = {'folder_id':n['id']};
Ext.Ajax.request({
url:deleteFoldersUrl,
params:params,
success:function(response, request) {
if (response.responseText == '{success:false}'){
request.failure();
} else {
Ext.Msg.alert('Success);
}
},
failure:function() {
Ext.Msg.alert('Error');
}
});
}

Related

Facing issue as 404 while Ajax call in typo3

I am new in typo3 and used the ajaxselectlist extension but while the time usage I am facing 404 not found an error.
Below code is fetch from ajaxselectlist/Resources/Templates/OptionRecord/List.html
<script>
jQuery(document).ready(function ($) {
var form = $('#ajaxselectlist-form');
var selectForm = $('.ajaxFormOption');
var controllerpath = $("#uri_hidden").val();
var resultContainer = $('#ajaxCallResult');
var service = {
ajaxCall: function (data) {
console.log("---->"+data.serialize());
$.ajax({
url: controllerpath,
cache: false,
data: {'uid':'1'},
success: function (result) {
resultContainer.html(result).fadeIn('slow');
},
error: function (jqXHR, textStatus, errorThrow) {
resultContainer.html('Ajax request - ' + textStatus + ': ' + errorThrow).fadeIn('fast');
}
});
}
};
form.submit(function (ev) {
ev.preventDefault();
service.ajaxCall($(this));
});
selectForm.change(function () {
resultContainer.fadeOut('slow');
form.submit();
});
selectForm.trigger('change');
});
</script>

Mapping List with Knockout Mapping

I have created view model
var catalog = ko.observableArray();
$.ajax({
type: "GET",
url: "http://localhost:8080/ticket-service/rest/ticket/list",
success: function(msg) {
catalog.push.apply(catalog, $.map(msg, function(data) {
return new Ticket(data)
}));
return catalog;
},
error: function(msg) {
console.log(msg)
}
});
and the model
function Ticket(data) {
this.ticketId = ko.observable(data.ticketId);
this.ticketNo = ko.observable(data.ticketNo);
this.ticketTitle = ko.observable(data.ticketTitle);
this.longDescription = ko.observable(data.longDescription);
this.createdBy = ko.observable(data.createdBy);
this.createdOn= ko.observable(data.createdOn);
this.assignTo = ko.observable(data.assignTo);
this.priority = ko.observable(data.priority);
this.dueDate = ko.observable(data.dueDate);
this.status = ko.observable(data.status);
this.projectId = ko.observable(data.projectId);
}
with at the end viewmodel like this
return {
ticket: newTicket,
searchTerm: searchTerm,
catalog: filteredCatalog,
newTicket: newTicket,
addTicket: addTicket,
delTicket: delTicket
};
})();
console.log(vm);
ko.applyBindings(vm);
produce list,add, and delete form.The question is how can i use knockout mapping that can list from get methode.
you need to do something like this
Demonstrated taking a single entity from your code .
view:
Output Preview :
<pre data-bind="text:ko.toJSON($data,null,2)"></pre>
viewModel:
function Ticket(data) {
this.ticketId = ko.observable(data.ticketId);
}
var mapping = {
create: function (options) {
return new Ticket(options.data);
}
};
var ViewModel = function () {
var self = this;
self.catalog = ko.observableArray();
var data = [{
'ticketId': 1
}, {
'ticketId': 2
}]
//under ajax call do the same but pass 'msg' in place of data
self.catalog(ko.mapping.fromJS(data, mapping)())
console.log(self.catalog()); // check console for output
};
ko.applyBindings(new ViewModel());
sample working fiddle here

Angularjs RESTul Resource Request

I am trying to make the request
....port/trimService/fragments/?fragment_name=:fragmentName
However if I try to make the "?fragment_name" a parameter, it breaks. As I am going to have more requests, my action with change so I cannot leave it in the url portion of the resource.
angular.module(foo).factory('FragmentService', ['$resource',
function ($resource)
{
var FragmentService = $resource('.../fragments/:action:fragmentName',
{},
{
'getFragments':
{
method: 'GET',
isArray: true,
params:
{
fragmentName: "#fragmentName",
action: "?fragment_name="
}
}
});
return FragmentService;
}
]);
As of right now, I have no idea what my URL is actually outputting.
EDIT: I changed my resource as /u/akonsu had mentioned below. I also added my controller as it is still not working correctly.
angular.module(foo).factory('FragmentService', ['$resource',
function ($resource)
{
var FragmentService = $resource('.../fragments/',
{},
{
'getFragments':
{
method: 'GET',
isArray: true,
params:
{
fragmentName: "#fragmentName",
}
}
});
return FragmentService;
}
]);
angular.module(foo).controller('FragmentController', ['$scope', 'FragmentService',
function ($scope, FragmentService)
{
$scope.fragmentQuery = {
fragmentName: 'a',
};
$scope.fragmentQuery.execute = function ()
{
if ($scope.fragmentQuery.fragmentName == '')
{
$scope.fragments = {};
}
else
{
$scope.fragments = FragmentService.getFragments(
{
fragmentName: $scope.fragmentQuery.fragmentName,
});
}
};
$scope.fragmentQuery.execute();
}
]);
Try omitting the query string altogether in the resource URL and just supply your fragmentName as a parameter to the action call. It should add it to the query string if it is not in the list of URL parameters.
$resource(".../port/trimService/fragments/").get({fragmentName: 'blah'})

Zend Controller Ajax call facing error

My Zend controller is like below:
public function deleteAction()
{
$this->_helper->layout->disableLayout();
$id = (int)$this->_request->getPost('id');
$costs = new Application_Model_DbTable_Costs();
if($costs->deleteCosts($id)){
$this->view->success = "deleted";
}
}
And ajax call I ma using to post data is :
$.ajax({
dataType: 'json',
url: 'index/delete',
type: 'POST',
data:id,
success: function () {
alert("success");
},
timeout: 13*60*1000,
error: function(){
console.log("Error");
}
});
And in my delete.phtml the code is like:
<?php
if($this->delete === true):
echo 'true';
else:
echo 'Sorry! we couldn\'t remove the source. Please try again.';
endif;
?>
The response is returning the html.
Its my first project with Zend Framework.
Thanks in advance.
Your controller action is returning HTML, not JSON.
You should consider using the AjaxContext action helper
public function init()
{
$this->_helper->ajaxContext->addActionContext('delete', 'json')
->initContext();
}
public function deleteAction()
{
$id = (int)$this->_request->getPost('id');
$costs = new Application_Model_DbTable_Costs();
try {
$costs->deleteCosts($id));
$this->view->success = "deleted";
} catch (Exception $ex) {
$this->view->error = $ex->getMessage();
}
}
The only other thing you need to do here is supply a format parameter of json in the AJAX request, eg
$.post('index/delete', { "id": id, "format": "json" }, function(data) {
if (data.error) alert("Error: " + data.error);
if (data.success) alert("Success: " + data.success);
}, "json");
You may want to handle the response differently but that should give you an idea.

Zend application jQuery ajax call getting error

I am trying to work with jQuery in Zend Framework. And the use case I am facing problem is when I am trying to save data to the db. Always receiving ajax error though the data is being saved in the database.
The controller that I am using to add data is like below:
public function addAction()
{
// action body
$form = new Application_Form_Costs();
$form->submit->setLabel('Add');
$this->view->form = $form;
if($this->getRequest()->isPost())
{
$formData = $this->getRequest()->getPost();
{
if ($form->isValid($formData))
{
$costTitle = $this->_request->getPost('costTitle');
$costAmount = $this->_request->getPost('costAmount');
$costs = new Application_Model_DbTable_Costs();
if($costs->addCosts($costTitle, $costAmount))
{
echo "suces";
}
// $this->_helper->redirector('index');
}
else
{
$form->populate($formData);
}
}
}
}
And the jQuery that is passing data is as follows:
$('#cost').submit(function (){
data = {
"cost_title":"cost_title",
"cost_amount":"cost_amount"
};
$.ajax({
dataType: 'json',
url: '/index/add',
type: 'POST',
data: data,
success: function (response) {
alert(response);
},
timeout: 13*60*1000,
error: function(){
alert("error!");
}
});
});
I am getting always error.
What is the problem in this code?
Thanks in advance.
I would strongly recommend you implement the newest Zend/AJAX methods.
// Inside your php controller
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('add', 'json')
->initContext();
}
public function addAction()
{
// action body
$form = new Application_Form_Costs();
$form->submit->setLabel('Add');
$this->view->form = $form;
if($this->getRequest()->isPost())
{
$formData = $this->getRequest()->getPost();
{
if ($form->isValid($formData))
{
$costTitle = $this->_request->getPost('costTitle');
$costAmount = $this->_request->getPost('costAmount');
$costs = new Application_Model_DbTable_Costs();
if($costs->addCosts($costTitle, $costAmount))
{
// The view variables are returned as JSON.
$this->view->success = "success";
}
}
else
{
$form->populate($formData);
}
}
}
// Inside your javascript file
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.get("/index/add/format/json", function(data) {
alert(data);
})
.error(function() { alert("error"); });
For more information:
AjaxContext (ctrl+f)
jQuery.get()
I think you are getting an error on Session output. Why don't you disable the view-renderer, since you just need an answer for the request echo "suces" which is more than enough for your AJAX.