Make an Ajax request in Yii 2.0? - ajax

Right, i only want a very simple ajax request to get this working. im new with yii 2.0 framework you see.
in my view index.php:
function sendFirstCategory(){
var test = "this is an ajax test";
$.ajax({
url: '<?php echo \Yii::$app->getUrlManager()->createUrl('cases/ajax') ?>',
type: 'POST',
data: { test: test },
success: function(data) {
alert(data);
}
});
}
Now when i call this i assume that it should go to my CasesController to an action called actionAjax.
public function actionAjax()
{
if(isset($_POST['test'])){
$test = "Ajax Worked!";
}else{
$test = "Ajax failed";
}
return $test;
}
EDIT::
Ok great, so this works up to here. I get back the alert that pops up with the new value for $test. However i want to be able to access this value in php as ultimately i will be accessing data from a database and ill be wanting to query and do various other things.
So how do i now use this variable in php instead of just the pop up alert()?

Here is how you can access the post data in controller:
public function actionAjax()
{
if(isset(Yii::$app->request->post('test'))){
$test = "Ajax Worked!";
// do your query stuff here
}else{
$test = "Ajax failed";
// do your query stuff here
}
// return Json
return \yii\helpers\Json::encode($test);
}

//Controller file code
public function actionAjax()
{
$data = Yii::$app->request->post('test');
if (isset($data)) {
$test = "Ajax Worked!";
} else {
$test = "Ajax failed";
}
return \yii\helpers\Json::encode($test);
}
//_form.php code
<script>
$(document).ready(function () {
$("#mausers-user_email").focusout(function () {
sendFirstCategory();
});
});
function sendFirstCategory() {
var test = "this is an ajax test";
$.ajax({
type: "POST",
url: "<?php echo Yii::$app->getUrlManager()->createUrl('cases/ajax') ; ?>",
data: {test: test},
success: function (test) {
alert(test);
},
error: function (exception) {
alert(exception);
}
})
;
}
</script>

You can include js this way in your view file:
$script = <<< JS
$('#el').on('click', function(e) {
sendFirstCategory();
});
JS;
$this->registerJs($script, $position);
// where $position can be View::POS_READY (the default),
// or View::POS_HEAD, View::POS_BEGIN, View::POS_END
function sendFirstCategory(){
var test = "this is an ajax test";
$.ajax({
url: "<?php echo \Yii::$app->getUrlManager()->createUrl('cases/ajax') ?>",
data: {test: test},
success: function(data) {
alert(data)
}
});
}

Related

Ajax alert inside function not works

First alert : alert('<?php echo t_lang('M_FRM_PLEASE_WAIT_WHILE_FILE_OR_IMAGE_IS_BEING_UPLOADED_._IF_FILE_SIZE_IS_BIG_IT_CAN_TAKE_SOME_TIME_._PLEASE_DO_NOT_CLOSE_TAB');?>'); does not work unless I put second alert out of function call: alert();
$('input[name="btn_submit"]').click(function second(){
var step = <?php echo $_REQUEST['step']?>;
var dealid= <?php echo $_GET['edit']?>;
var ur="imagecheck.php?dealid="+dealid;
if (step == 1) {
$.ajax({
url: ur,
type: "GET",
header: {'Access-Control-Allow-Origin': '*'},
success: function(y) {
if(y=='true'){
alert('<?php echo t_lang('M_FRM_PLEASE_WAIT_WHILE_FILE_OR_IMAGE_IS_BEING_UPLOADED_._IF_FILE_SIZE_IS_BIG_IT_CAN_TAKE_SOME_TIME_._PLEASE_DO_NOT_CLOSE_TAB');?>');
} else {
alert(dealid);
}
}
});
alert(); // if I don't add this first alert is not showed up.
}
});
I tried almost everything but still can not understand why first alert relies on second alert. Any help would be highly appreciated.
I am adding the codes below which is all about ajax in my file.
<script type="text/javascript">
$(document).ready(function(){
$('input[name="btn_submit"]').click(function first(){
var com_id=<?php echo $_SESSION['logged_user']['company_id']?>;
var co_type=$('#co_type').val();
var ur="check_no_of_deals.php?company_id="+com_id;
if(co_type==0){
$.ajax({
url: ur,
type: "GET",
header: {'Access-Control-Allow-Origin': '*'},
success: function(t) {
if(t == 'true'){
} else {
alert('<?php echo t_lang('M_FRM_YOU_HAVE_ALREADY_ADDED_DEAL_TODAY');?>');
window.location.href='http://deals.az/merchant/company-deals.php';
}
}
});
}
});
//bizim kod basladi
$('input[name="btn_submit"]').click(function second(){
var step = <?php echo $_REQUEST['step']?>;
var dealid= <?php echo $_GET['edit']?>;
var ur="imagecheck.php?dealid="+dealid;
if (step == 1) {
$.ajax({
url: ur,
type: "GET",
header: {'Access-Control-Allow-Origin': '*'},
success: function(t)(y) => {
if(t=='true'){
alert('<?php echo t_lang('M_FRM_PLEASE_WAIT_WHILE_FILE_OR_IMAGE_IS_BEING_UPLOADED_._IF_FILE_SIZE_IS_BIG_IT_CAN_TAKE_SOME_TIME_._PLEASE_DO_NOT_CLOSE_TAB');?>');
} else {
alert(dealid);
}
}
});
// alert();
}
});
//bizim kod bitti
});
</script>
try replacing to arrow function
$.ajax({
...
success: (y) => {
if(y=='true'){
...
}
}
...
})
the difference between an arrow function and a regular function is by their this
so when you pass the regular function it becomes part of the ajax call or the Jquery object.
but the arrow function stays where you see it.

ajax is not sending data to controller

ajax is not sending data to controller
var url = "<?php echo base_url(); ?>";
function allowip() {
var url = "<?php echo base_url(); ?>"
var id = $('#path').attr('value');
$.ajax({
type: "POST",
url: url+"client/home/get_ip",
//dataType: 'text',
data: {'id': id},
//cache: false,
success: function(abc) {
alert(abc);
},
error:function(data) {
alert('no working');
}
});
}
alert is showing with data but not sending data to controller
controller is empty
public function get_ip($id)
{
$day = $this->input->post('id');
echo $day;
}
As your get_ip function have argument $id so it must need to pass on it, url keyword might be conflicting so use different variable name and get the value from #path with val() function.
It might help:
function allowip() {
var id = $('#path').val();
var request_url = "<?php echo base_url(); ?>"+"client/home/get_ip/"+id;
$.ajax({
type: "POST",
url: request_url,
data: {'id': id},
success: function(abc) {
alert(abc);
},
error:function(data) {
alert('no working');
}
});
}
public function get_ip($id)
{
echo $id;
}
or you can do is to post $id in data as you're already doing it but only have to change some lines:
function allowip() {
var id = $('#path').val();
var request_url = "<?php echo base_url(); ?>"+"client/home/get_ip/";
$.ajax({
type: "POST",
url: request_url,
data: {'id': id},
success: function(abc) {
alert(abc);
},
error:function(data) {
alert('no working');
}
});
}
public function get_ip()
{
$day = $this->input->post('id');
echo $day;
}
You are sending a parameter to a function so you can change your code like this
function allowip() {
var id = $('#path').attr('value');
var url = "<?php echo base_url(); ?>"+"client/home/get_ip/"+id
$.ajax({
type: "GET",
url: url,
dataType: "html",
success: function(abc) {
alert(abc);
},
error:function(data) {
alert('no working');
}
});
}
and your action will be
public function get_ip($id)
{
echo $id;
}
I think it is probably the way you are getting the value. It's hard to tell without seeing the view code, but I will assume that $('#path') is an <input...> element of some sort. If that is correct then try getting the value like this
var id = $('#path').val();
Forget about using an argument with the get_ip() function. You are posting to the controller not creating a URL with argument values. Try this.
public function get_ip()
{
$day = $this->input->post('id');
echo !empty($day) ? $day : "No Input"; //or, an empty string instead?
}

how to retrieve data sent by Ajax in Cakephp?

I have been stuck at this problem for a whole day. What im trying to do is to send 2 values from view to controller using Ajax.
This is my code in hot_products view:
<script>
$(function(){
$('#btnSubmit').click(function() {
var from = $('#from').val();
var to = $('#to').val();
alert(from+" "+to);
$.ajax({
url: "/orders/hot_products",
type: 'POST',
data: {"start_time": from, "end_time": to,
success: function(data){
alert("success");
}
}
});
});
});
and my hot_products controller:
public function hot_products()
{
if( $this->request->is('ajax') ) {
$this->autoRender = false;
//code to get data and process it here
}
}
I dont know how to get 2 values which are start_time and end_time.
Please help me. Thanks in advance.
PS: im using cakephp 2.3
$this->request->data gives you the post data in your controller.
public function hottest_products()
{
if( $this->request->is('ajax') ) {
$this->autoRender = false;
}
if ($this->request->isPost()) {
// get values here
echo $this->request->data['start_time'];
echo $this->request->data['end_time'];
}
}
Update
you've an error in your ajax,
$.ajax({
url: "/orders/hot_products",
type: 'POST',
data: {"start_time": from, "end_time": to },
success: function(data){
alert("success");
}
});
If you method is POST:
if($this->request->is('ajax'){
$this->request->data['start_time'];
$this->layout = 'ajax';
}
OR
public function somefunction(){
$this->request->data['start_time'];
$this->autoRender = false;
ANd if method is GET:
if($this->request->is('ajax'){
$this->request->query('start_time');
$this->layout = 'ajax';
}
OR
public function somefunction(){
$this->request->query('start_time');
$this->autoRender = false;

how to get the value from codeigniter to ajax?

i have an ajax which I don't know if it is correct. I want to get the value from the controller and pass it to ajax.
ajax:
$.ajax({
type: "GET",
url: swoosh(id, path+'swoosh_employee/swoosh_delete_child', 'childdv'),
success: function(response) {
if (response != "Error")
{
$('#success-delete').modal('show');
}
else
{
alert("Error");
}
}
});
event.preventDefault();
and in the controller:
public function swoosh_delete_child()
{
$P1 = $this->session->userdata('id');
parse_str($_SERVER['QUERY_STRING'],$_GET);
$id = $_GET['h'];
$response = $this->emp->delete_children($id);
}
model
public function delete_chilren($id){
.......//codes here.. etc. etc.
if success //
return "success";
else
return "Error";
}
i just want to pass/get the value of $reponse and pass it to the ajax and check if the value is error or not..
Just echo in the controller:
$response = $this->emp->delete_children($id);
And alert the response:
alert(response); //output: success / Error
in your controller:
you should have something like this
public function swoosh_delete_child(){
$P1 = $this->session->userdata('id');
parse_str($_SERVER['QUERY_STRING'],$_GET);
$id = $_GET['h'];
$response['status'] = $this->emp->delete_children($id);
echo json_encode($response);
}
then in your ajax, to access the response
$.ajax({
type: 'POST',
url: url: swoosh(id, path+'swoosh_employee/swoosh_delete_child', 'childdv'),,
dataType: 'json',
success: function(response){
if (response.status)
{
$('#success-delete').modal('show');
}
else
{
alert("Error");
}
}
});

Yii: get result for ajax request

I have a anchor;
When I click on it, the following code executes:
<script>
$('.viewcnp').click(function() {
event.preventDefault();
var r = prompt("Enter your password:");
if (r) {
$.ajax({
type: "POST",
url: '<?php echo Yii::app()->baseUrl; ?>' + '/index.php/admin/user/viewCnp/id/' + '<?php echo $model->id; ?>',
data: {'password': r},
success: function(data) {
$('.cnpdecrypted').text(data);
},
dataType: 'text'
});
}
});
</script>
this code makes a request to this action:
public function actionViewCnp($id) {
$model = User::model()->findByPk($id);
if ($model) {
return '{"data":"' . Utils::decrypt_cnp($model->cnp) . '"}';
}
else
return false;
}
If in the action I echo the cnp decripted, its there, but i can't set the value because I don't receive it on success.
You should simply use echo instead of return :
if ($model) {
echo Utils::decrypt_cnp($model->cnp);
}

Resources