Zend Controller Ajax call facing error - zend-framework

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.

Related

How to use the login credentials with php in ionic project

I want to authenticate the user_name and password field. the user_name and password field is stored in database with php. how to get the data from the server in ionic project.
Thanks in advance.
You can create a service script that can send post data to PHP and receive a JSON response.
Post data should be sent as an object containing element name and values in the following format:
var myObj = {username: 'username', password:'password'};
Below is a service example:
yourApp.service('YourService', function ($q, $http) {
return {
login: function (data) {
var deferred = $q.defer(),
promise = deferred.promise;
$http({
url: 'http://www.example.com/yourPHPScript.php',
method: "POST",
data: data,
headers: {'Content-Type': 'application/json'}
})
.then(function (response) {
if (response.data.error.code === "000") {
deferred.resolve(response.data.appointments);
} else {
deferred.reject(response.data);
}
}, function (error) {
deferred.reject(error);
});
promise.success = function (fn) {
promise.then(fn);
return promise;
};
promise.error = function (fn) {
promise.then(null, fn);
return promise;
};
return promise;
}
};
});
From your login controller you call the following code to use the service (make sure you add the name of the service to your controller declaration)
YourService.login(loginData)
.then(function (data) {
// on success do sthg
}, function (data) {
//log in failed
// show error msg
});

java util list as jquery ajax response on spring mvc

Controller
#RequestMapping(value = Array("getPatternId.html"), method = Array(RequestMethod.GET))
#ResponseBody def getPattern(model:ModelMap,#RequestParam patternId: Long):List[Question] = {
var list: List[Question] = questionService.findQuestionByQuestionPattern(patternId)
var questions: java.util.List[Question] = ListBuffer(list: _*)
questions
}
script
function getPattern(id) {
$.ajax({
type : 'GET',
url : " /learnware/getPatternId.html ",
data : ({
patternId : id
}),
success : function(response) {
// we have the response
$('#info').html(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
}
When i send response as string it display it on html page
but when i return a list it does no show the data
<div id="info" style="color:green;"></div>
current response will be add to div witn id info

Decoding response error in extjs

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

How to declare the url in a jQuery ajax request to execute an action from a zend controller?

I'm trying to implement an ajax request using jQuery in the Zend Framework. I created a controller with a test action as represented on the code below:
class CompareController extends Zend_Controller_Action {
public function init() {
/* Initialize action controller here */
}
public function indexAction() {
}
public function testAction() {
}
}
My ajax request using jQuery looks like this:
$.ajax({
type: "POST",
url:"<?php echo $this->url(array('controller' => 'compare', 'action' => 'test')); ?>",
data: dataString,
success: function(msg) {
}
How should I declare the url to execute the test action from the zend controller upon receipt of the request?
Any help will be greatly appreciated!
You can also use baseUrl() function like :
$.ajax({
type: "POST",
url:"<?php echo $this->baseUrl(); ?>/compare/test",
data: dataString,
success: function(msg) {
}
});

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.