Web Decade Dallas | Arlington | Fort Worth | Irving TX Zend Framework and Ajax Json Jquery PHP Techniques that are helpful
I have been developing a lead tracking application using zend frame work I like this framework the most but It basically almost the same as other mvc frameworks that I have worked with. It follow the same structure since it is a mvc framework like asp.net mvc and code igniter. Well lets not get off track I tried to research on the internet and tried to find solutions on how to do ajax request using the zend framework and jquery library and found little or no documentation on how to do this especially with json.
So in this blog post I will explain the way I did this.
Step one create a controller called chat or what ever controller name you want. In my case I will use chat here is the code example below. I will try to explain it in the code comments
Now look at the addchatAction this is where I process my ajax request.
Notice the section //ajax request
if ($this->getRequest()->isXmlHttpRequest()) { } else {}
So first I detect if it a ajax request if it is I basically write my logic to do whatever and read in the post request sent by the jquery ajax json function and send the data back in json format I use the json helper to do this
$return['error'] = true;
$return['msg'] = 'Your chat message has been posted';
//encode your data into JSON and send the response
$this->_helper->json($return);
That all you have to do in your controller to process a jquery json ajax php request. Next I will show you the view file that handle the ajax request and response.
<?php
class ChatController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
//load the systems model class for cat option
Zend_Loader::loadClass('Systemsdatavalue');
//create a instance of the table referencing the model
$SystemsdatavalueTable = new Systemsdatavalue();
$select = $SystemsdatavalueTable->select()
->where('sid=?',"1")
->order('id');
$results = $SystemsdatavalueTable->fetchAll($select);
//load the user model class for recipient list option
Zend_Loader::loadClass('Users');
//create a instance of the table referencing the model
$UsersTable = new Users();
$select = $UsersTable->select()
->from(array('u' => 'users'),
array('user_id','first_name','last_name'));
$results2 = $UsersTable->fetchAll($select);
$this->view->assign('cat',$results);
$this->view->assign('recipient',$results2);
}
public function addchatAction()
{
//ajax request
if ($this->getRequest()->isXmlHttpRequest()) {
//load the model class
Zend_Loader::loadClass('Chats');
//create a instance of the table referencing the model
$chatsTable = new Chats();
//load up the data pass by ajax thru json into array
$data = array(
'message_title' => $_POST["message_title"],
'message' => $_POST["message"],
'ip' => $_SERVER['REMOTE_ADDR'],
'cat_id' => $_POST["category"]
);
//insert into db and get the last insert id so we can insert records. into the chat routes
$lastInsertId = $chatsTable->insert($data);
for($i = 0; $i< (count($_POST["recipients"]) - 2);$i++){
//load the model class
Zend_Loader::loadClass('Chatsroutes');
//create a instance of the table referencing the model
$chatsroutesTable = new Chatsroutes();
//load up the data pass by ajax thru json into array
$data = array(
'chat_id' => $lastInsertId,
'from_id' => $_POST["sender"],
'to_id' => $_POST["recipients"][$i]
);
$chatsroutesTable->insert($data);
// do the handling of your ajax request
// action body
}
$return['error'] = true;
$return['msg'] = 'Your chat message has been posted';
//encode your data into JSON and send the response
$this->_helper->json($return);
//nothing else will get executed after the line above
}
else {
// if it's not an ajax request then do regular handling here
}
}
public function showchatAction()
{
//ajax request
if ($this->getRequest()->isXmlHttpRequest()) {
//load the model class
Zend_Loader::loadClass('Chats');
//create a instance of the table referencing the model
$chatsTable = new Chats();
if(isset($_POST["category"])){
$select = $chatsTable->select()
->where('cat_id=?',$_POST["category"])
->order('date desc');
}else{
$select = $chatsTable->select()->order('date desc');
}
$results = $chatsTable->fetchAll($select);
// do the handling of your ajax request
// action body
$return['error'] = true;
$data2 = $results;
$m2 ="";
for($i = 0; $i< count($data2);$i++){
//split date and time separate
$datetime = explode(" ", $data2[$i]["date"]);
$d1m = substr($datetime[0],5,2);
$d1d = substr($datetime[0],8,2);
$d1y = substr($datetime[0],0,4);
//load the model class
Zend_Loader::loadClass('Systemsdatavalue');
//create a instance of the table referencing the model
$systemsvalueTable = new Systemsdatavalue();
$select = $systemsvalueTable->select()
->where('id=?',$data2[$i]["cat_id"]);
$results2 = $systemsvalueTable->fetchAll($select);
// do the handling of your ajax request
// action body
$m2= $m2." Date: ".$d1m."/".$d1d."/".$d1y." Time: ".$datetime[1].
"".$data2[$i]["message_title"].
"".$data2[$i]["message"]."Posted ByIn Category: ".$results2[0]["data_value"]."";
}
$return['results'] = $m2;
//encode your data into JSON and send the response
$this->_helper->json($return);
//nothing else will get executed after the line above
}
else {
// if it's not an ajax request then do regular handling here
}
}
}
?>
I will show you the view file next so this file basically get the element id from the form and when the submit element is click it fires off the ajax request and post the request to the url below /chat/addchat and post the following fields message, recipient, sender and so on on the controller will check for those post. and if succesful it will out put the json format back to the view
Hope this helps..
$(document).ready(function(){
$('#submit').click(function() {
$('#waiting').show(800);
$('#demoForm').hide(0);
$('#message').hide(0);
$.ajax({
type : 'POST',
url : '/chat/addchat/',
dataType : 'json',
data: {
message_title: $('#message_title').val(),
message: $('#messagetext').val(),
recipients: $('#recipients').val(),
sender: $('#sender').val(),
category: $('#category').val()
},
success : function(data){
$('#waiting').hide(800);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(800);
if (data.error === true) {
$('#demoForm').show(800);
showmessages();
}
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(800);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(800);
$('#demoForm').show(800);
}
});
return false;
});
});




















