I have a GirdView which includes checkbox. Now I have a button which i routed to another action controller. Below is my code
<?= GridView::widget([
'dataProvider' => $dataProvider,
/*'filterModel' => $searchModel,*/
'id'=>'grid',
'columns' => [
['class' => 'yii\grid\CheckboxColumn'],
'Meter Serial Number',
'Issued To',
'Store',
],
]); ?>
Set PDF
$(document).ready(function () {
$('#myid').click(function() {
var keys = $('#grid').yiiGridView('getSelectedRows');
// alert(keys);
$.post({
url: 'ogpheader/viewsetpdf',
dataType: 'json',
data:{keylist: keys},
success:function(data) {
alert('Done')
}
});
}) });
Then in my controller
public function actionViewsetpdf()
{
/*$model = $this->findModel($id);
print_r($model);*/
if(isset($_POST['keylist']))
{
$keys = json_decode($_POST['keylist']);
print_r($keys);
}
exit();
}
When I click on the button i get empty view. I followed this tutorialI don't know what is the problem. I am stuck to it.
Update1
While checking it in network
Update 2
As suggested I have tried with $.ajax and below is the result
Update 3
After changing the JS
$('#myid').click(function(e) {
e.preventDefault();
var keys = $('#grid').yiiGridView('getSelectedRows');
// alert(keys);
$.ajax({
url: '<?= URL::toRoute(["ogpheader/viewsetpdf"])?>',
dataType: 'json',
data:{keylist: keys},
type: 'post',
success:function(data) {
alert('Done')
}
});
The result is
Any help would be highly appreciated.
Change the controller and see what return, probably csrf token missing that why you got empty output
public function actionViewsetpdf()
{
if(isset($_POST['keylist']))
{
$keys = json_decode($_POST['keylist']);
print_r($keys);
}
else{
echo 'no data';
}
exit();
}
POST method required csrf token so you have to pass _csrf token as a parameter
$.ajax({
url: 'ogpheader/viewsetpdf',
type: 'post',
dataType: 'json',
data: {
keylist: keys,
_csrf: '<?=Yii::$app->request->getCsrfToken()?>'
},
success: function(data) {
console.log(data);
}
});
Or you can disable csrf valdation by adding this to your controller
public function beforeAction()
{
if ($this->action->id == 'viewsetpdf') {
Yii::$app->controller->enableCsrfValidation = false;
}
return true;
}
Or simplest way just change POST to GET
$.post() has limited parameter to pass. Use $.ajax(). Also you need to add e.preventDefault() to stop redirection from a tag
$(document).ready(function () {
$('#myid').click(function(e) {
e.preventDefault();
var keys = $('#grid').yiiGridView('getSelectedRows');
// alert(keys);
$.ajax({
url: '<?php echo URL::toRoute(["ogpheader/viewsetpdf"]); ?>',
dataType: 'json',
data:{keylist: keys},
type: 'post',
success:function(data) {
alert('Done')
}
});
}) });
Use below js
<?php
$url = Url::toRoute(['ogpheader/viewsetpdf']);
$this->registerJs(<<< JS
$(document).ready(function () {
$('#myid').click(function() {
var keys = $('#grid').yiiGridView('getSelectedRows');
$.ajax({
url: '$url',
data: {keylist: keys},
type: "POST",
dataType: 'json',
success:function(data) {
alert('Done');
}
});
});
});
JS
); ?>
Related
I'm currently learning basic php and jQuery.
I've created script which is getting url on mouse hover, and sends it to php.
The problem is, if I want to pass this data to php variable, it seems like it doesn't work because it echos only "'This is our JS Variable :'"
Script:
<script type="text/javascript">
var hrefValue;
jQuery(document).ready(function($) {
$('#bio-box').find('a').mouseover(function() {
hrefValue = ($(this).attr('href'))
console.log(hrefValue)
});
$.ajax({
url: 'jakubtrz-portfolio/wp-admin/admin-ajax.php',
data: {
'action': 'php_tutorial',
'php_test': hrefValue
},
success: function(data){
console.log("happy")
}
});
});
</script>
functions.php:
function our_tutorial(){
if(isset($_REQUEST)){
$testing = $_REQUEST['php_test'];
echo 'This is our JS Variable :'.$testing;
global $wpdb;
$wpdb->insert(
$wpdb->prefix.'lms_enroll',
[
'ID' => $testing
]
);
}
die();
}
add_action('wp_ajax_php_tutorial', 'our_tutorial');
Solution:
$.ajax({
url: 'jakubtrz-portfolio/wp-admin/admin-ajax.php',
type: 'post', // define type
data: {
'action': 'php_tutorial',
'php_test': hrefValue
},
success: function(data){
console.log("happy")
}
});
functions.php:
// post to et value
$test = $_POST['php_test'];
The problem was - when page loaded, value of a variable was empty. So solution is to call ajax in the moment of mouseover.
var hrefValue;
jQuery(document).ready(function($) {
$('#bio-box').find('a').mouseover(function() {
hrefValue = ($(this).attr('href'))
//console.log(hrefValue)
$.ajax({
url: frontendajax.ajaxurl,
type: 'POST',
data: {
'action': 'image',
'php_test': hrefValue
},
success: function(data){
$('#featured-image').html(data);
//console.log(data);
}
});
});
});
I tried to load a view in my codeigniter controller and also i pass a status to my ajax function. In the ajax function i wrote a sweetalert popup in the sucess function when my status is 1. now my actual problem is when i load a view in the controller the status is not passing to my ajax function.can anyone figureout what the problem is any help is appreciable.
controller
$query = $this->package_view_model->enquiry_history();
if (isset($query))
{
$status = 1;
$this->load->view('packages/enquiry');
}
echo json_encode (array("status"=>$status));
ajax function
function sendMail(package_url)
{
var formData = $("#enqform").serialize();
jQuery.ajax({
type: 'POST',
url: '<?php echo base_url() ?>tour-package/send-mail',
data: formData,
dataType: 'json',
success: function(data){
if(data.status == 1){
swal({
title:'Thankyou for your interest!!!',
text: "Our excecutives will contact you soon.",
html: true,
type: "success",
showCancelButton: false,
showConfirmButton:false
});
window.setTimeout(function() {
window.location.href = '<?php echo base_url() ?>tour-packages';
}, 1000000);
}
}
});
return false;
e.preventDefault();
}
Hope this will help you :
$query = $this->package_view_model->enquiry_history();
$status = 1;
if (! empty($query))
{
$this->load->view('packages/enquiry');
}
echo json_encode(array("status" => $status));
exit;
I think there is a problem with the ending slash in the baseurl. So, change the way you're generating the url.
function sendMail(package_url)
{
var formData = $("#enqform").serialize();
jQuery.ajax({
type: 'POST',
url: '<?php echo base_url("tour-package/send-mail") ?>',
data: formData,
dataType: 'json',
success: function(data){
if(data.status == 1){
swal({
title:'Thankyou for your interest!!!',
text: "Our excecutives will contact you soon.",
html: true,
type: "success",
showCancelButton: false,
showConfirmButton:false
});
window.setTimeout(function() {
window.location.href = '<?php echo base_url() ?>tour-packages';
}, 1000000);
}
}
});
return false;
e.preventDefault();
}
I want to pass value of text box to my controller, i can pass that but i cant retrieve it at controller. Help me to identify my mistake.
Form.php (dept_name is a id of my textbox)
<script>
$(document).ready(function() {
$("#submitbutton").click(function(e) {
var deptname=$('#dept_name').val();
$.ajax({
url: 'http://localhost/finalProjectWork/admin_department_controller/adddept/',
type: 'POST',
method: 'POST',
headers: {'Cache-Control': 'no-cache'},
data: {name:deptname},
contentType: false,
processData: false,
success: function(test) {
alert(test);
},
error: function() {
alert("Already Exists");
}
});
e.preventDefault();
});
});</script>
controller :
public function adddept()
{
$deptname=$this->input->post('name');
$this->load->model('admin_department_model');
$this->admin_department_model->insertdept($deptname);
echo "Successfully inserted";
}
Try this
<script>
$(document).ready(function() {
$("#submitbutton").click(function(e) {
var deptname=$('#dept_name').val();
$.ajax({
url: 'http://localhost/finalProjectWork/admin_department_controller/adddept/',
type: 'POST',
method: 'POST',
headers: {'Cache-Control': 'no-cache'},
data: {name:deptname},
success: function(test) {
alert(test);
},
error: function() {
alert("Already Exists");
}
});
e.preventDefault();
});
});</script>
Here's my ajax call:
$("#yes, #no").click(function(){
var upOrDown = $(this).attr('id');
$.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
action: "updateVote",
data: {upOrDown: upOrDown},
dataType: "json",
success: function(data) {
console.log(data.output);
}
});
return false;
});
Here's the function in functions.php
function updateVote() {
echo json_encode(array(
'output' => 'hello!'
));
die();
}
add_action('wp_ajax_updateVote', 'updateVote');
add_action('wp_ajax_nopriv_updateVote', 'updateVote');
Why does this keep returning "0". It should return "hello!"
Thanks.
i have a div that shows the total sum of some products:
<div class="total-price"><?php echo (!empty($cart)) ? $cart['total'] : '0'; ?> $</div>
with ajax, i'm adding products to cart ... se the page is not reloading.
How to refresh the div after I add the product to cart?
The ajax that i'm using:
<script>
$('#order-to-cart').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/tdt/order',
data: $(this).serialize(),
success: function () {
$(".success-message").slideDown().delay(5000).slideUp();
$(".total-price").something...;
}
});
})
</script>
Thank you!
You can do something like this:
<script>
$('#order-to-cart').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/tdt/order',
data: $(this).serialize(),
success: function () {
$(".success-message").slideDown().delay(5000).slideUp();
var oldPrice = $('.total-price').text() * 1;
var itemPrice = "15"; //the price that should be added
$('.total-price').text(oldPrice + itemPrice);
}
});
})
</script>
You should be returning a total basket value from your /tdt/order path.
In the PHP script you should echo some JSON data with all the required information, for example
echo json_encode(array("totalPrice" => "£10.01"));
Then you need to parse this information into your Javascript and update the pages elements;
<script>
$('#order-to-cart').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/tdt/order',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
$(".success-message").slideDown().delay(5000).slideUp();
$('.total-price').val(data.totalPrice);
}
});
})
</script>
The above ajax request will expect the data returned to be JSON, you will then use this to update the total-price element.
You can use something like angularjs or knockoutjs - for angular you would update your model - for knockout you would use the self.object.push(value) i.e.,
function OrderViewModel() {
var self = this;
self.myOrder = ko.observableArray([]);
self.addOrderItem = function () {
$.ajax({
type: "post",
url: "yourURL",
data: $("#YOURFORMFIELDID").serialize(),
dataType: "json",
success: function (value) {
self.myOrder.push(value);
},
headers: {
'RequestVerificationToken': '#TokenHeaderValue()'
}
});
}
}
ko.applyBindings(new orderViewModel());
</script>
</pre>