I'm using Yii 2.0 basic version and I need some help.
I created one ajax function like this:
function eliminarColaborador(id) {
$.ajax({
type: "GET",
async: false,
url: "<?= urldecode(Url::toRoute(['colaborador/ajaxEliminarColaborador'])) ?>",
dataType: 'json',
data: {
'id': id
},
complete: function ()
{
},
success: function (data) {
if (data !== null)
{
// SUCCESS
}
else
{
// ERROR
}
}
});
}
My action in controller:
public function actionAjaxEliminarColaborador($id) {
if (Yii::$app->request->isAjax) {
$continuar = false;
if(isset($id) && $id > 0) {
var_dump($model); die;
$continuar = true;
}
echo CJSON::encode(array('continuar'=>$continuar));
Yii::$app->end();
}
}
I'm getting this erro in firebug: Not Found (#404): Page not found.
I tried everything, but i can't figure out what's the problem.
If I change ajax url to urldecode(Url::toRoute(['colaborador/delete'])) the error is gone and all works just fine.
Maybe I need to declare in ColaboradorController my new action ajaxEliminarColaborador, but I don't know how.
What is wrong?
controller
public function actionAjaxEliminarColaborador(){}
ajax
urldecode(Url::toRoute(['colaborador/ajax-eliminar-colaborador']))
It should be <?= urldecode(Url::toRoute(['colaborador/ajax-eliminar-colaborador'])) ?>. Here you can learn why.
Change the ajax response with:
url: '/colaborador/ajaxEliminarColaborador/$id',
data: {id: $id,_csrf: yii.getCsrfToken()},
Try to remove the word 'ajax' on your url.
Related
Okay, so before I ask my question I will explain the flow of things. Form submits data to add() method (localhost/share/add) in the ShareController, from there it is shipped over to the ShareModel method createShare() where the magic is supposed to happen.
My AJAX code:
var formData = $(form).serialize();
var form = $("#add-share");
$(form).submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData,
dataType : "json",
success : function(data) {
if(data == 1) {
alert("Woohoo!");
} else {
alert("Womp!");
}
console.log(data);
}
})
});
ShareController add() method:
public function add() {
ShareModel::createShare(Request::post('share_title'));
Redirect::to('share');
}
ShareModel createShare() method:
public static function createShare($share_title) {
if(strlen($share_title) > 55) {
Session::add('feedback_negative', Text::get('FEEDBACK_SHARE_TITLE_LONG'));
return false;
}
if(strlen($share_title) < 5 || empty($share_title)) {
Session::add('feedback_negative', Text::get('FEEDBACK_SHARE_TITLE_SHORT'));
return false;
}
$data[] = 0;
echo json_encode($data);
}
The issue:
Ajax is returning everything fine "Womp!" when I have the backend PHP validation commented out, however when I have it implemented the AJAX does not work, and the backend validation does not take over. Anyone have an ideas what's going on here?
I have been struggling for days. I am doing ajax callback by assigning an input field but I am unable to too. Below is the code:
Script
$('[name="acccode[]"]').each(function(idx,val){
var acccode = $('[name="acccode[]"]').eq(idx).val();
console.log(acccode);
$.ajax({
url : "<?php echo base_url(); ?>readacccode",
type: "POST",
data:"Acc_Code="+acccode,
dataType: "JSON",
success: function(data)
{
$.each(data.results,function(idx,val){
console.log(val);
$('[name="accname[]"]').val(val);
});
},
error: function (data)
{
swal("Oops", "We couldn't connect to the server!", "error");
}
});
});
I am successfully able to get each acc code. But not the name.
Here is the Controller code:
public function readacccode()
{
if (!$this->ion_auth->logged_in() || $this->ion_auth->is_store())
{
redirect('account/login');
}
$acccode = $this->input->post('acccode');
$data['results']=$this->Setting->get_acccode($acccode);
echo json_encode($data);
}
it is getting the acc name where the acc code matches.
Please advise.
Thanks, everyone the problem is resolved. For those wanting to know here is the thing I change.
public function readacccode()
{
if (!$this->ion_auth->logged_in() || $this->ion_auth->is_store())
{
redirect('account/login');
}
$acccode = $this->input->post('Acc_Code'); //All I did is replace acccode to Acc_Code
$data['results']=$this->Setting->get_acccode($acccode);
echo json_encode($data);
}
I want to create a variable within my controller function that equals the POST value however I am unsure on how to access the POST value.
An answer would be great but any tips for debugging would be great too.
I have tried $_POST['save_id'] as well as $_POST[0]['save_id']
$('#save-file').click(function() {
var fileid = $(this).data('fileid');
$.ajax({
type: "POST",
url: "/files/save",
data: { 'save_id' : fileid },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//do something
console.log(fileid);
alert("working");
},
error: function (errormessage) {
//do something else
alert("not working");
}
});
});
for your url if the code is inside a PHP file i suggest you a proper path eg :
url: <?=Url::to(['/files/save']) ?>,
(Remenber of add use use yii\helpers\Url;)
If not a php refer to the absolute path properly
inside your FilesController in save Action
public function actionSave()
{
if (Yii::$app->request->isAjax) {
$data = Yii::$app->request->post();
//data: { 'save_id' : fileid },
$mySaveId = $data['save_id']
// your logic;
......
}
}
JS:
$(function() {
load_custom_topics()
// load_main()
});
function load_custom_topics(){
$.ajax({
type: "POST",
async: false,
url: 'http://rickymason.net/thebump/index.php/ajax/load_custom_topics',
dataType: 'json',
data: { },
success: function(page){
alert(page);
}
});
event.preventDefault()
}
load_custom_topics
public function load_custom_topics()
{
$check = $this->page_model->check_active_topic();
if ($check == FALSE)
{
$page['content'] = 'TEST equals FALSE';
} else {
$page['content'] = 'TRUE';
}
echo json_encode($page);
}
going to the page index.php/ajax/load_custom_topics returns this:
{"content":"TEST equals FALSE"}
The alert is not firing! Any idea why?
Actually, on inspecting a request to your controller, I found that you weren't setting the proper headers the ajax call expects (text/json).
See codeigniter's Output class.
Using
$this->output->set_content_type('application/json')->set_output(json_encode($page));
instead of
echo json_encode($page);
should do the trick.
I've been stuck with the retrieving of my sent variable trough an ajax POST function. Could you help me out?
My Jquery code:
$.ajaxSetup ({
cache: false
});
var selected = new Array();
$(document).ready(function() {
$('.value').click(function () {
if($(this).hasClass('strong'))
{
selected.splice(selected.indexOf(this.innerHTML), 1);
submitData(selected);
$(this).removeClass('strong');
}
else
{
selected.push(this.innerHTML);
submitData(selected);
$(this).addClass('strong')
}
});
});
function submitData(arDat) {
var arrayData = {"param1" : JSON.stringify(arDat)};
$.ajax({
type: 'POST',
url: 'http://localhost.local/coconut/trunk/challenges/values',
data: arrayData,
dataType: 'json',
success: function(data){
console.log(arrayData);
},
error: function(message){
alert(message);
}
});
}
My CakePHP Controller function:
function values() {
if ($this->RequestHandler->isAjax()) {
$this->autoRender = false;
Configure::write('debug', 0);
$params = json_decode($_POST['param1']);
//$result = json_encode($params);
$this->set('submitValue', $params);
} else {
$this->redirect(array('controller' => 'challenges', 'action' => 'index'));
}
}
And in a view.ctp file:
<?php debug($submitValue); ?>
But I get the following error:
Notice (8): Undefined variable: submitValue
In firebug I see this:
Parametersapplication/x-www-form-urlencoded
param1 ["Business","Life","Health"]
Source
param1=%5B%22Business%22%2C%22Life%22%2C%22Health%22%5D
Does anyone know what I'm doing wrong?
Thanks!
Edit:
A bit more clarification about what I want.. I want to use $this->set('submitValue', $params); (so $submitValue) elsewhere in another view.
The CakePHP function 'isAjax()' checks to see if a request is a Prototype Ajax request.
You aren't using Prototype, you're using jQuery - so presumably it's always returning false, and so submitValue is never set.