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

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

Related

The jquery ajax function is not giving any output but is throwing a 403 error

I have an ajax function in jquery caling a cakephp4 function. The function doesnt work as it is giving a 403 forbidden error. The error is about headers but i cant find what I need to fix this exactly.
This code runs and it does get the var (alert verifies this). Nothing works ?
jquery
///
var freeassessmentid = "<?=$testid?>";
$.ajax({
url: "/freeassessments/freeasssesmenFinaltResult", //path is correct and it can be tested on its own
method: "POST",
dataType: "html",
data: { freeassessmentid:freeassessmentid },
success: function(response) {
//console.log(response);
$('#display-area').append(response); //no output
}
});
public function freeasssesmenFinaltResult($freeassessmentid=0)
{
//debug('test');
$html .= '<li class="listyle" style="height: auto;">hi<br/></li>';
$html .= '</ul>';
//no output
//https://stackoverflow.com/questions/36666256/jquery-ajax-call-results-in-error-status-403
The Ajax url should be:
url: "/freeassessments/freeasssesmen-finalt-result",
Use the kebab case for actions/methods in urls and the camel case for them in the controllers
You have to pass CSRF token in header during ajax call.
You can get CSRF token in many ways.
One of the simplest way is:
You can add bellow code to your head tag of parent layout or inside any of your template file.
<?php echo $this->Html->meta("csrfToken", $this->request->getAttribute("csrfToken")); ?>
At the time of ajax call you will have to get this csrf token and pass it to the ajax header.
Here is the example:
var token = $("meta[name='csrfToken']").attr("content");
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': token
}
});
$.ajax({
url: "path/to/controller/method",
method: "POST",
data: { pram1:val },
success: function(response) {
//console.log(response);
}
});
I hope it may help :)

How to add value in a $.ajax url in CakePHP 2

Im trying to use ajax to sent request. I have CartsController and a method add. Please help!
<?php
echo $this->Html->link('Add', array('controller'=>'carts',
'action'=>'add', 'product_id'=>$product['Product']['id']),
array('class'=>'btn btn-primary col-md-offset-4',
'data-product-id'=>$product['Product']['id']));
?>
$('a.btn').on('click', function(e){
var this = $(this);
var product_id = this.data('product-id');
this.html('Item Added');
$.ajax({
url: '/cartphp_cart/carts/add/',
type: 'POST',
data: {product_id: product_id},
success: function(count) {
$('#number-of-items').text(' ' + count);
console.log(count);
}
});
e.preventDefault();
});
If the ajax request is OK, than in your add method of CartsController
you can get it by
if ($this->request->is('post') || $this->request->is('put')) {
debug($this->request->data['product_id'])
}
You should be able to access the data you've put in your ajax request by
if( $this->request->is('ajax') ) {
pr($this->request->data['product_id']);
// Or try printing the whole $this->request->data if you need other items.
}

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

jQuery.ajax() sequential calls

Hey. I need some help with jQuery Ajax calls. In javascript I have to generste ajax calls to the controller, which retrieves a value from the model. I am then checking the value that is returned and making further ajax calls if necessary, say if the value reaches a particular threshold I can stop the ajax calls.
This requires ajax calls that need to be processes one after the other. I tried using async:false, but it freezes up the browser and any jQuery changes i make at the frontend are not reflected. Is there any way around this??
Thanks in advance.
You should make the next ajax call after the first one has finished like this for example:
function getResult(value) {
$.ajax({
url: 'server/url',
data: { value: value },
success: function(data) {
getResult(data.newValue);
}
});
}
I used array of steps and callback function to continue executing where async started. Works perfect for me.
var tasks = [];
for(i=0;i<20;i++){
tasks.push(i); //can be replaced with list of steps, url and so on
}
var current = 0;
function doAjax(callback) {
//check to make sure there are more requests to make
if (current < tasks.length -1 ) {
var uploadURL ="http://localhost/someSequentialToDo";
//and
var myData = tasks[current];
current++;
//make the AJAX request with the given data
$.ajax({
type: 'GET',
url : uploadURL,
data: {index: current},
dataType : 'json',
success : function (serverResponse) {
doAjax(callback);
}
});
}
else
{
callback();
console.log("this is end");
}
}
function sth(){
var datum = Date();
doAjax( function(){
console.log(datum); //displays time when ajax started
console.log(Date()); //when ajax finished
});
}
console.log("start");
sth();
In the success callback function, just make another $.ajax request if necessary. (Setting async: false causes the browser to run the request as the same thread as everything else; that's why it freezes up.)
Use a callback function, there are two: success and error.
From the jQuery ajax page:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
// Do processing, call function for next ajax
}
});
A (very) simplified example:
function doAjax() {
// get url and parameters
var myurl = /* somethingsomething */;
$.ajax({
url: myurl,
context: document.body,
success: function(data){
if(data < threshold) {
doAjax();
}
}
});
}
Try using $.when() (available since 1.5) you can have a single callback that triggers once all calls are made, its cleaner and much more elegant. It ends up looking something like this:
$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1, a2){
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively
var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
alert( jqXHR.responseText )
});

Ajax Response from CakePHP Controller returning null

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.

Resources