Zend Json render data into views - php

Hi i have an Zend Framework apps, the following code are popularAction controller
public function popularAction()
{
$type = $this->_getParam('ref',1);
if($type == 'reviews'){
$businessReviewMapper = new Application_Model_Mapper_BusinessReviewsMapper();
$result = $businessReviewMapper->getTotalVote();
$rotd = $businessReviewMapper->getROTD($result['review_id']);
$rotd[0]['u_img'] = $this->view->getLoginUserImage($rotd[0]['social_id'],$rotd[0]['login_type'],null,null,square);
$rotd[0]['rating'] = $this->view->getRatingImg($rotd[0]['rating']);
$rotd[0]['business_name_url'] = preg_replace("![^a-z0-9]+!i","-", $rotd[0]['business_name']);
$this->render('reviews');
$this->_helper->json($rotd);
} elseif($type == 'openings') {
$this->view->text = "New Openings";
} else {
$this->_helper->redirector('index', 'index', 'default');
}
}
When a user browse to http://localhost/business/popular?ref=reviews the above controller code would render reviews.phtml template. Now inside the template itself there is ajax request for a data as follow:
function getPopular()
{
var count=1;
$.ajax({
url:"<?=$this->baseUrl('business/popular?ref=reviews')?>",
data:{'count':count},
dataType:"json"
type:"POST",
success:function(data){
alert('ok')
}
});
unfortunately the $this->_helper->json($rotd); doesn't pass data to the reviews.phtml,but display json data which is returned by zend db model, where i might be wrong?Thanks

If your Goal is to, to send JSON instead of the .phtml File on an Ajax Request, try to implement this:
if ($this->getRequest()->isXmlHttpRequest()) {
if ($this->getRequest()-isPost()) {
$this->_helper->json($rotd);
}
}
This part checks if the request is, lets call it: ajax based..

Related

CakePHP 4 Return data from controller to AJAX render issue

I am submitting data to a controller function via AJAX, doing what I need to do with the data, and trying to echo it back out to the ajax function.
The issue I am having, is the controller is dumping out the error message and trying to redirect me to the actual function. Obviously the function doesn't have a view, which results in a blank white screen with the response echoed out in the top left corner.
Here is the ajax:
$('#submit_new_split_promo').on('click',function(e){
e.preventDefault();
var id = $(this).data('id');
$('#d_overlay').show();
form = {};
$.each($('#promo-mail-split-add-'+id).serializeArray(),function(k,v){
form[this.name] = this.value;
});
$.ajax({
url:$('#promo-mail-split-add-'+id).attr('action'),
type:"POST",
dataType: "json",
data: form
}).done(function(result){
var res = JSON.parse(result);
if (res == 'Duplicate') {
$('#ms-promo').css('border','3px solid red');
$('#ms-promo').effect('shake');
$('#dynamodal-unique-title').text('That code has been used. Please enter a new Promo Code.');
$('#dynamodal-unique-title').text('That code has been used. Please enter a new Promo Code.').css('color','red').delay(2000).queue(function(next){
$('#dynamodal-unique-title').text('Create Mail Split Promo');
next();
});
return false;
}
$('#mail_split_promo_'+id).modal('toggle');
if (res == false) {
alert('Mail Split Promo did not save. Please try again.');
} else {
$('#add-promo-to-split-'+id).prop('disabled',true);
$('#promo-view-abled-'+id).hide();
$('#promo-view-disabled-'+id).show();
$('#promo-view-disabled-'+id).prop('disabled',false);
}
}).fail(function(){
}).always(function(){
$('#d_overlay').hide();
});
});
Here is the Controllers code
public function addpromo() {
$this->Authorization->skipAuthorization();
$this->request->allowMethod(['get','post']);
$this->autoRender = false;
$data = $this->request->getData();
$mail_split_id = $data['mail_split_id'];
$code = $data['code'];
$result = false;
$doesExist = $this->Promos->findByCode($code)->toArray();
if ($doesExist) {
$result = 'Duplicate';
}
if ($result !== 'Duplicate') {
$MailSplits = $this->getTableLocator()->get('MailSplits');
$mailSplit = $MailSplits->get($mail_split_id);
$entity = $this->Promos->newEmptyEntity();
foreach ($data as $key => $val) {
$entity->$key = $val;
}
$entity->record_count = $mailSplit->record_count;
$result = $this->Promos->save($entity);
if ($this->get_property($result,'id')) {
$promo_id = $result->id;
$MailSplits = $this->loadModel('MailSplits');
$mentity = $MailSplits->get($mail_split_id);
$mentity->promo_id = $promo_id;
$updated = $MailSplits->save($mentity);
if ($this->get_property($updated,'id')) {
$result = true;
} else {
$result = false;
}
$output = [];
exec(EXEC_PATH.'AddPromoToRecordSplits '.$promo_id,$output);
} else {
$result = false;
}
}
ob_flush();
echo json_encode($result);
exit(0);
}
The URL it is trying to redirect me to is: /promos/addpromo when I really just need to stay on the same page, which would be /mail-jobs/view
Response dumped to browser
A couple of things to note:
I have tried adding the function to the controllers policy, and actually authorizing an initialized entity. This has no effect and does not change the issue I am facing.
Something that is more frustrating, I have essentially the same code (ajax structure and controller structure) for other forms on the page, and they work just fine. The only difference seems to be any form that utilizes ajax that is on the page on render, works just fine. The ajax functions I am having an issue with, all seem to be from the forms rendered in Modals, which are different elements. Every form in a modal / element, gives me this issue and that's really the only pattern I have noticed.
Any help is greatly appreciated, I know it's an odd and vague issue.
Thank you!

How can we pass result data from CodeIgniter controller to AngularJS controller?

How can we pass result data from CodeIgniter controller to AngularJS controller? In CodeIgniter controller using jsonSuccess code here I'm passing data to AngularJS but I would like to pass different 3 variables
How do I need to pass them and how can I get data?
codeigniter controller code:
$siteName = $CI->config->item('siteName');
$siteURL = site_url();
if($data['status'] == 'success')
{
$result = $this->LowCredit_model->info($data['data']);
jsonSuccess($result,$siteName ,$siteURL,$result['succ_code'],$siteName,$siteURL);
}
Angular Controller code:
$scope.init = function() {
alert('init');
gdiztunnel.post(
'order/LowCredit', {
id: $configId
}
).then(
function success (response) {
response = response.data;
if(response.status == 'success') {
$scope.lowcreditCtrl.data = response.data;
I already gave you the solution this is Repeated Question
$data['siteName'] = $CI->config->item('siteName');
$data['siteURL'] = site_url();
if($data['status'] == 'success') {
$data['result'] = $this->LowCredit_model->info($data['data']);
jsonSuccess($data);
}

Use codeiginiter and ajax following the rules codeigniter

I'm struggeling to use codeigniter the way it was created. I'm opening an edit page (order). I want to change data on the page which will be dynamically saved after leaving a field. But when I'm not succeeding in the way codeigniter works or with other words on a "nice way". I don't want to be depending on the uri structure and get the data with uri segment, like the code is now. I want to improve the code beneath but i'm not succeeding...
This is the code to open my view
public function edit($id = NULL) {
// Fetch a page or set a new one
$this->load->model('shop_m');
$this->load->model('details_m');
$this->data['subtitle'] = 'incoming';
if ($id) {
if($this->transfer_m->get_permission($id) > 0){
$this->data['transfer'] = $this->transfer_m->get_rec($id);
// $this->data['transfer'] = $this->transfer_m->get($id,true);
count($this->data['transfer']) || $this->data['errors'][] = 'page could not be found';
$this->data['details'] = $this->details_m->get_by(array('doc_no' => $id),FALSE);
}
else{
redirect('admin/Dashboard', 'refresh');
}
} else {
$this->data['transfer'] = $this->transfer_m->get_new();
}
$this->data['shop_from'] = $this->shop_m->get($this->data['transfer']->from_customer,TRUE);
$this->data['shop_to'] = $this->shop_m->get($this->data['transfer']->to_customer,TRUE);
// Load the view
$this->data['subview'] = 'pages/details/transfer_edit';
$this->load->view('pages/main', $this->data);
}
My ajax call
function add_shop(shop){
var id = $('#doc_no').text();
$.ajax({
url: base_url+"/admin/transfer/add_shop/"+id+"/"+shop,
async: false,
type: "POST",
data: "",
dataType: "html",
success: function(data) {
$('#ajax-content-container').hide();
}
})
}
my controller function to add a shop
public function add_shop($id){
$data = array('to_customer' => $this->uri->segment(5));
$this->transfer_m->save($data,$id);
}
Any help will be appreciated!!
You can use post. Modify your ajax call and pass the data like below. See the document here https://api.jquery.com/jquery.post/
data: { id: id, shop: shop }
This data can be accessed $this->input->post('id'); $this->input->post('shop');

POST data from knockout.js to CakePHP controller

I'm posting data from a knockout.js page to a controller in cakephp and it says the data was successfully posted, however, my controller doesn't seem to be responding and I don't get an alert back...not even a null response. I even checked the network tab in chrome and it shows the correct data being POSTED
Here's the data being posted from my knockout viewmodel file
var JSON_order = JSON.stringify({"orderInfo":[{"itemNumber":"1","quantity":"1","price":1.00,"productName":"test"}]});
$.post("/orders/submit_order", JSON_order,
function(data){
alert(data.check); //alert doesn't appear
}, "json");
Here's my controller
function submit_order(){
$this->layout = false;
$this->autoRender = false;
if ($this->request->is('post')) {
$order = $this->request->data;
$order = json_decode($order, true);
$finalize_order = new submit;
$finalize_order->display_submitted_order_success($order);
}
}
Here's the code for display_submitted_order_success (I also tried this on a php file outside of CakePHP but it didn't work either)
function display_submitted_order_success($order = null){
$this->layout = false;
$this->autoRender = false;
//I'm just trying to display the order as-is so that I know it's even being posted to begin with
echo json_encode(array("check" => "success","order_num" => $order)); //the values passed the price check, display the result
}
You have to assign the value of JSON_order to a var:
var JSON_order = JSON.stringify({"orderInfo":[{"itemNumber":"1","quantity":"1","price":1.00,"productName":"test"}]});
$.post("/orders/submit_order", {order:JSON_order},
function(data){
alert(data.check); //alert doesn't appear
}, "json");
So that your controller would receive it like this:
$data['order'] = '{"orderInfo":[{"itemNumber":"1","quantity":"1","price":1,"productName":"test"}]}'

codeigniter and ajax cannot access the post

On my website I am using ajax post request to show content around my site, this is done using this code,
$("a.contentlink").click(function(ev) {
ev.preventDefault();
$('#main_menu').hide();
var url = $(this).attr("href");
var data = "calltype=full&url="+url;
$.ajax({
url:url,
type: "POST",
data: data,
success : function (html) {
$('#left-content-holder').html(html);
}
})
});
as you can see I am passing the url into the `$_POST' and I can access this in the method the javascript calls, this method is called get_content_abstract and looks like this,
public function get_content_abstract() {
$this->load->model('content_model');
if($this->input->post('calltype') == "abstract"){
if($query = $this->content_model->get_content_by_id($this->uri->segment(3))) {
$data['abstract'] = $query;
}
$this->load->view('template/abstract', $data);
}
elseif($this->input->post('calltype') == "full") {
if($query = $this->content_model->get_content_by_id($this->uri->segment(3))) {
$data['full'] = $query;
}
$this->load->view('template/full-content', $data);
}
}
How ever I have no added a new function that will allow the user to save the content to 'bookmarking system', however in my method I cannot access the post using codeigniters $this->input-post('url') (where URL is the one of peices of data passed in the javascript), it says that the post is empty when I var dump it, this is done using this method,
public function love_this() {
die(var_dump($this->post->input('url')));
}
can anyone help as to why the post is empty in this love_this method?
Shouldn't:
public function love_this() {
die(var_dump($this->post->input('url')));
}
Actually be
public function love_this() {
die(var_dump($this->input->post('url')));
}
See:
http://codeigniter.com/user_guide/libraries/input.html

Categories