Ajax Response from CakePHP Controller returning null - ajax

I'm tryin to validate an input field with an ajax call to a cakephp controller
My Ajax is:
$("#UserAlphaCode").change(function () {
$.ajax({
type: "post",
url: '<?php echo $this->webroot ?>' + "/alpha_users/checkCode",
data: ({code : $(this).val()}),
dataType: "json",
success: function(data){
alert (data);
},
error: function(data){
alert("epic fail");
}
});
});
My controller code
function checkCode() {
Configure::write('debug', 0);
$this->autoRender = false;
$codePassed = $this->params['form']['code'];
$isCodeValid = $this->find('count',array('conditions'=> array('AlphaUser.code' => $codePassed)));
if ($isCodeValid == 0){
$codeResponse = false;
} else {
$codeResponse = true;
}
echo json_encode ($codeResponse);
}
I'm pretty sure I'm using $this->params wrong here to access the data sent from the ajax request. What should I be doing instead?

Try something like:
$codePassed = $_POST['code']
you might also try putting:
$this->log($codePassed,LOG_DEBUG);
somewhere in there and examine the output in tmp/logs/debug.log
Using firebug will help debug the transport.

Don't know why it would be returning null, but I normally use $this->data to fetch form data.
And did you try debug($this->params)? If you don't have a non-AJAX form to test the request from, use Firebug or Wireshark to see what is being return by the server for the debug() call—since it will break jQuery's AJAX handler by not being in JSON.

Related

How to display the corresponding table value of the response in AJAX

I have an ajax response that is equal to 1. And,in my success function, I want to display not the 1 to my view but the corresponding column_name which is 'brands_name' in the brands table which is 'Apple' in this case. I want to display this after a successful post request. Any ideas?
You need to send your response from your controller (json)
// controller
$data['ajax_response'] = 1;
$data['brands_name'] = $brands_name;
return json_encode($data);
You need to catch the success function to get the variable you want from php
// javascript
$.ajax({
url:link,
dataType:"json",
data:data,
type:"post",
success: function(data)
{
if(data.ajax_response == 1)
{
console.log(data.brands_name);
}
},
error: function()
{
}
});

Returning values in Magento

Following is the function in controller which returns the values of a product
public function productsAction()
{
$sku=$this->getRequest()->getparam('subvalue');
$_product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
$upsell_product_collection = $_product->getUpSellProductCollection();
$upsel=$upsell_product_collection->addAttributeToSelect('product_type')
->addAttributeToFilter('product_type', 133);
$products1 = $_product->getData();
return $products1;
}
Below is the ajax request for fetching the values at the frontend
$.ajax
({
type: "POST",
url: "<?php echo $this->getUrl('finder/index/products');?>",
data:"subvalue="+subval,
success: function(response)
{
alert(response);
$("#responseproducts").html(response);
};
});
I m not able to fetch the values in the front end ..Please tell me ways to fetch the values at the front end
Decode as JSON in php:
return json_encode($products1);
and decode it in javascript:
JSON.parse(response);
This should work. You can test it afterwards with:
console.log(response);
if your ajax request is sent successfully then add this code in you controller action.
$response['prodcutdata'] = $products1;
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
return;
After that in ajax request success access it like below:
alert(response.prodcutdata);

CakePHP includes "<!-- xxx.s -->" in AJAX response?

Im just trying to send a simple jquery ajax request but always get the response like this:
""ok""< !--" 16.7154s "-->"
Why: < !-- 16.7154s -->?
My js:
jQuery.ajax({
type:"POST",
url: 'controller/action/' + $('#nickname').val() ,
success: function(data) {
alert( data ==='ok' );
}
}); return;
My controller:
function verifynick(){
$this->layout='ajax';
$this->autoRender = false;
return ('ok');
}
Thanks in advance
You just have to put the debug mode at 0.
You can do it on the fly in your action like this
Configure::write('debug', 0);

ajax response to refresh url rather than append?

I have a question regarding ajax, I'm quite new to it so not sure of the best procedure. Anyways I have incorporated ajax in to my CodeIgniter app but I have the possibility of 2 different responses and I'm not quite sure how to deal with this in my ajax.
Instead of appending my result to a div can I not just refresh the url?
In my controller I have form validation, when it is false I want to refresh to display my errors, but if it returns true I want to show the new page, if that makes sense?
view
$.post("<?php echo base_url(); ?>part-one",
$("form").serialize(),
function(result){
// if errors show this
$("#error").html(result);
// if there are no errors how do I check the response to refresh the page to a new url?
}, "html"
);
controller
if($this->form_validation->run() == FALSE){
$data['content'] = "part_one";
$this->load->view('template', $data);
} else {
$data['content'] = "part_two";
$this->load->view('template', $data);
}
If you want to reload the page you can do;
$.ajax({
url: url,
type: 'post',
data: data,
success: function(data) {
location.reload();
}
});
If i understand you right then this code may help you ...
$.post("<?php echo base_url(); ?>part-one",
$("form").serialize(),
function(result){
// if errors show this
$("#error").html(result);
if(result =='false condition response')
{
window.location.reload()
}
if(result == 'True Conditon response')
{
window.location.href('URL of the page')
}
// if there are no errors how do I check the response to refresh the page to a new url?
}, "html"
);

Ajax in Wordpress plugin

I am creating a simple wordpress plugin and trying to use AJAX, but I always get 0 in ajax response.
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
action: 'my_action',
whatever: '1234'
};
jQuery.post("http://localhost/taichi/wp-admin/admin-ajax.php", data, function(response) {
alert(response);
});
});
</script>
<?php
add_action('wp_ajax_my_action', 'my_action_callback');
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
function my_action_callback() {
echo "test";
die();
}
what am I doing wrong?
You have to put the add_action at the complete bottom of your file or else it won't find the callback function
Try to change :
jQuery.post("http://localhost/taichi/wp-admin/admin-ajax.php", data, function(response)
To :
jQuery.post(ajaxurl, data, function(response)
And check if it is working on the admin side first. It should work fine.
Error Return Values
If the AJAX request fails when the request url is wp-admin/admin-ajax.php, it will return either -1 or 0 depending on the reason it failed.
Read this
Edit
admin-ajax always return default '0' as output.so while you alerting response you will 0 only.using die() in callback function will terminate that.
Had the same problem, it turned out that my callback was inside a php file which was only included to my "Theme Options" page.
To check if the function is able to trigger trougth admin-ajax.php try to add var_dump(function_exists("your_callback_name")); to the bottom of the wp-admin/admin-ajax.php (before die( '0' );) and then have a look to your ajax output.
Try the following code in your plugin file. or in function.php
jQuery(document).ready(function($){
var ajaxURL = 'http://localhost/taichi/wp-admin/admin-ajax.php';
var dataString = 'action=mnd_news';
$.ajax({
type: "POST",
url: ajaxURL,
data: dataString,
cache: false,
success: function(response){
if(response != 'error') {
alert(response);
}
}
});
});
add_action('wp_ajax_mnd_news', 'get_mnd_ajax');
add_action( 'wp_ajax_nopriv_mnd_news', 'get_mnd_ajax' );
function get_mnd_ajax() {
echo "test";
die();
}

Resources