POST data from knockout.js to CakePHP controller - php

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"}]}'

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!

posting array using ajax to the controller in cakePHP

I am relatively new to cake and I am struggling with a custom filter that im making in order to display products based on which checkboxes have been ticked. The checkboxes get populated based on which attributes the user creates in the backend, i then collect all the values of the selected boxes into an array with javascript and post it to the controller, but for some reason I cannot access the controller variable named '$find_tags' in my view, it throughs undefined variable.
Here is my javascript and ajax which collects and posts correctly (when i firebug it 'data' in my controller has array values which im posting) so thats fine
$("#clickme").click(function(event){
event.preventDefault();
var searchIDs = $("#checkboxes input:checkbox:checked").map(function(){
return $(this).val();
}).get();
var contentType = "application/x-www-form-urlencoded";
var data = 'data[ID]='+searchIDs;
$.post("",data,function(data){
console.log(data);
});
});
Here is my controller code which im assuming is where the fault lies
if ($this->request->is('post') ) {
$data = $this->request->data['ID'];
$find_tags = array();
$selected_tags = $data;
foreach($selected_tags as $tag)
{
array_push($find_tags,$this->Product->findByTag($tag));
$this->set('find_tags', _($find_tags));
}
}
And here is my view code where i get Undefined variable: find_tags
foreach($find_tags as $all_tag)
{
echo $all_tag['Product']['name'];
echo '</br>';
}
Any help or suggestions would really be appreciated been struggling with this for a while now
If searchIDs is array of ids you just need to make the json of array and then send to your controller
$("#clickme").click(function(event){
event.preventDefault();
var searchIDs = $("#checkboxes input:checkbox:checked").map(function(){
return $(this).val();
}).get();
var contentType = "application/x-www-form-urlencoded";
var data = 'ids='+JSON.stringify(searchIDs);
$.post("controller url",data,function(data){
console.log(data);
});
});
On php side you are getting wrong variable
if ($this->request->is('post') ) {
$data = $this->request->data['ids'];
$find_tags = array();
$selected_tags = $data;
foreach($selected_tags as $tag)
{
array_push($find_tags,$this->Product->findByTag($tag));
}
$this->set('find_tags', _($find_tags));
}

Zend Json render data into views

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..

CakePHP 2.1 Ajax validation errors

I'm trying to get validation errors with Ajax and jQuery working in CakePHP 2.1 for a contact form. On blur of the name field a js function is called:
$(document).ready(function(){
$('#name').blur(function(){
$.post(
'/Cake_ajax/Contacts/validate_form',
{ field: $(this).attr('id'), value: $(this).val() },
handleNameValidation
);
});
function handleNameValidation(error){
if(error.length > 0){
if($('#name-notEmpty').length == 0){
$('#name').after($('<div id="name-notEmpty" class="error-message">' + error + '</div>'));
}
}else{
$('#name-notEmpty').remove();
}
}
});
The javascript calls the validate_form function in my controller:
public function validate_form(){
if($this->RequestHandler->isAjax()){
$this->request->data['Contact'][$this->request->params['form']['field']] = $this->request->params['form']['value'];
$this->Contact->set($this->request->data);
if($this->Contact->validates()){
$this->autorender = FALSE; // don't render a view
}else{
$error = $this->validateErrors($this->Contact);
$this->set('error', $error[$this->request->params['form']['field']]);
}
}
}
In my view I'm getting a couple of errors when the error is called:
Undefined index: form [APP\Controller\ContactsController.php
Undefined index: form [APP\Controller\ContactsController.php
I'm at my wits end, and I'm fairly new to CakePHP. Any help would be greatly appreciated.
In your controller you should have something like below. Cake 2.0 replaces many features in RequestHandlerComponent and Controller. It also replaces $this->params array in all places and the old $this->data to $this->request->data, something like that. You can visit the migration guide.
public function validate_form(){
if($this->RequestHandler->isAjax()){
$this->request->data['Contact'][$this->request['form']['field']] = $this->request['form']['value'];
$this->Contact->set($this->request->data);
if($this->Contact->validates()){
$this->autorender = FALSE; // don't render a view
}else{
$error = $this->validateErrors($this->Contact);
// didn't validate logic
$this->set('error',$this->Contact->validationErrors[$this->request['data']['field']][0]);
}
}
}
Try $this->request->params['field'] instead of $this->request->params['form']['field'].
Or right after you check to isAjax(), try doing a var_dump on $this->request->params. From the error you are getting, the form index does not exist in $this->request->params.
If you want to simulate a POST like done when using a standard form and the Cake FormHelper, you could also simply name the posted parameters the same way the FormHelper names the input fields.
$j.post(
'/Cake_ajax/Contacts/validate_form',
{ "data[Contact][" + $(this).attr('id') + "]": $(this).val() },
handleNameValidation
);
This would automatically populate $this->request->data['Contact']['name'] and you could just comment this line:
//$this->request->data['Contact'][$this->request->params['form']['field']] = $this->request->params['form']['value'];

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