yii Ajax call not going to correct action - ajax

I have the following link to make my ajax call in yii2:
echo Html::a('Load more','ajaxShowMoreProducts', [
'onclick'=>"console.log('Load more');
$.ajax({
type:'POST',
cache: false,
url: 'ajaxShowMoreProducts',
success: function(response) {
console.log('suc');
}
});return false;",
]);
Then I have an action in my SiteController:
/**
* #return string|\yii\web\Response
*/
public function actionAjaxShowMoreProducts() {
var_dump('in');die;
$params = [];
$productModel = new Product();
$params['products'] = $productModel->getAll();
$this->renderPartial('partialProductItem', $params);
}
However when I click the link,the correct controller action does not seem to be called. Its still calling site/index. Any ideas what I have to do to get this working? Have i forgotten some sort of annotation or maybe I have to define my new action somewhere?
When I look in the console, it looks correct:
Request URL: http://localhost:8080/site/ajaxShowMoreProducts

In yii2 you should use the proper notation for action url (in url calling si not used the camelNotation but the words are separated by - (minus)
echo Html::a('Load more','ajax-show-more-products', [
and in ajax url too
url: 'ajax-show-more-products',
or try using Url Helper
use yii\helpers\Url;
....
echo Html::a('Load more', Url::to(['/site/ajax-show-more-products']), [
'onclick'=>"console.log('Load more');
$.ajax({
type:'POST',
cache: false,
url: '" . Url::to(['/site/ajax-show-more-products']) . "',
success: function(response) {
console.log('suc');
}
});return false;",
]);

Related

Yii2 Grid View Filtering using ajax not Pjax

How to get the value of the attribute in yii2 using ajax not Pjax to filter the Gridview ?
easily you can do your own you want by sending Ajax request to any controller you want and return data as Json to read it by javasscript .
here is a sample file (you can put in any .js file and bind in from your layout or jsRegister function )
test.js:
$.ajax({
type: 'GET',
url : '/site/countor?id='+pathArray[2],
crossDomain: true,
success: function(output) {
alert(output);
},
contentType:'application/json; charset=utf-8',
dataType: 'json'
});}}
siteController counter action :
public function actionCountor($id) {
$p1 = new View();
$p1->ip = Yii::$app->request->getUserIP();
$p1->post_id = $id;
if ($p1->save()) {
$arr = array('id'=>$p1->id;
return json_encode($arr);
}
}

pass an array to action using ajax YII

Hi i'm really new with YII, please help me to solve a simple problem.
I'm trying to pass some values from js to action and then to put them into database.
Most of this code i got from tutorial
public function actionInsert(){
$post = file_get_contents("php://input");
$data = CJSON::decode($post, true);
$read = new Read();
$read->attributes = $data;
$response = array();
$read->save();
}
Then i send:
$.ajax({
type: "POST",
url: "/read/insert/",
data: "name=imja&short_desc=korotkoe&author=avtor&image=photo",
error: function (){
alert('Error');
},
success: function(data){
alert('success');
}
});
But i get an 'error' alert and nothing goes to DB.
The values from .ajax don't get submitted as a JSON array, the values should simply be in the $_POST array. Also I like to return something like 'complete'. Try changing your code to this:
public function actionInsert(){
$read = new Read();
$read->attributes = $_POST;
$response = array();
$read->save();
echo 'complete';
die();
}
Or you can send it as a JSON array from the javascript side:
var data = {
name: 'imja',
short_desc: 'korotkoe',
author: 'avtor',
image: 'photo'
};
$.ajax({
type: "POST",
url: "/read/insert/",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
error: function (){
alert('Error');
},
success: function(data){
alert('success');
}
});
However even if you do this apache will see the header type and still populate the $_POST array correctly. So it really isn't needed.
Also if you haven't already install Firebug onto Chrome or Firefox so you can see that actual ajax calls in the console. See what error you are getting from your action function in your controller.

CodeIgniter - Nothing is shown in the view

I don’t know what the problem is. I have an ajax which sends username to the controller:
function my_profile(username){
$.ajax({
url: "member/my_profile",
type: "get",
data: "username="+username,
success: function(){
window.location.href = 'member/my_profile';
}
});
}
And this is my controller:
function my_profile(){
$username = $this->input->get('username');
$data['username'] = $username;
$this->load->view('my_profile' , $data);
}
I have already echo the $username to test that it can alert(msg) from the ajax. It works just find. Problem is nothing is shown in my view:
<h1>My Profile</h1>
<?php
echo $username;
?>
I don’t know why. I tried initialized $data['username'] = 'adam' and this works.
The problem is your window.location.href = 'member/my_profile';. This will redirect you to the profile page without any username value.
You probably want to do:
window.location.href = 'member/my_profile?username='+username;
Though, I still don't understand why you have that AJAX call there. Couldn't you just do:
function my_profile(username){
window.location.href = 'member/my_profile?username='+username;
}
Your AJAX call is loading the page then discarding the contents, I don't think you need it here.
$.ajax({
url: "member/my_profile",
type: "get",
data: "username="+username,
success: function(){
window.location.href = 'member/my_profile';
}
});
Should be :
$.ajax({
url: "member/my_profile?username=" + username,
type: "get",
success: function(){
window.location.href = 'member/my_profile';
}
});

Ajax not reciving data. Symfony2

The idea is when i click on a button it calls sendeRequest() and the controller receives the petition. But I'm not receiving anything.
I wan't to send a request to the controller. (I have set a redirection in the controller, to check that I'm receiving the data). I've tried doing:
function sendRequest(){
$.ajax({
type: "POST",
url: "{{ path('login') }}" ,
cache: "false",
dataType: "html",
success: function(result){ $("div#box").append(result);}
});
}
And in the controller
$request = $this->getRequest();
if($request->isXmlHttpRequest()){
return $this->render('mainBundle:Register:register.html.twig');
}
I'm using jquery 1.7.2
You can do this:
if($this->getRequest()->isXmlHttpRequest()){
return new Response(json_encode(array(
'form'=>$this->render('mainBundle:Register:register.html.twig')->getContent()))
);
}

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