use foreach loop in json format in codeigniter - ajax

I want to loop a table in json,
my return value is
Array(
[0]Array(
[m_id]=>2
[event_id]=>37
[activity_id]=>20
)
[1]Array(
[m_id]=>20
[event_id]=>3
[activity_id]=>2
)
)
my script is
function get_out_mail(user_name){
var datastring = 'user_name=' + user_name;
alert(datastring);
var a = false;
$.ajax({
type: "POST",
async: false,
url: "<?php echo site_url(); ?>admin/get_out_mails",
data: datastring,
cache: false,
success: function (result) {
alert(result);
var result = $.parseJSON(result);
console.log(result.from);
$('#myTable').html('');
$("#myTable").append('<tbody><?php foreach ($get_all_mail as $get_all_mails) { ?><tr id="target-list"><td><input type="checkbox" id="mail-checkbox-1" class="custom-checkbox"></td><input type="hidden" name="mid" value="<?php echo $get_all_mails['m_id']; ?>"/><td><i class="glyph-icon icon-star"></i></td><td class="email-title" ><?php echo $get_all_mails['from']; ?></td><td class="email-body" ><?php echo $get_all_mails['subject'] ?></td><td><i class="glyph-icon icon-paperclip"></i></td><td>17 Jan 2014</td></tr><?php } ?></tbody>');
}
});
return a;
}
my controller
public function get_out_mails(){
if ($this->session->userdata('admin_logged_in')) {
$user_name = $this->input->post('user_name');
$result['out_mail'] = $this->admin_model->get_out_mailss($user_name);
print_r($result['out_mail']);
}
Here I want to append my return array value in json using foreach loop, how can I do this.

It is ajax request It is better to return complete html part in controller instead of appending in the View page :
Example controller :
echo $values ="<body>
<tr> test</tr>
</body>";
View : Success : function(data){
$('#id').html(data);
}
With that you will hide the complete loop from the view page and get the code in controller

Replace your controller function with this:
public function get_out_mails(){
if ($this->session->userdata('admin_logged_in')) {
$user_name = $this->input->post('user_name');
$result['out_mail'] = $this->admin_model->get_out_mailss($user_name);
$data = '<tbody>';
foreach ($get_all_mail as $get_all_mails) {
$data .= '<tr id="target-list"><td><input type="checkbox" id="mail-checkbox-1" class="custom-checkbox"></td><input type="hidden" name="mid" value="'.$get_all_mails['m_id'].'"/><td><i class="glyph-icon icon-star"></i></td><td class="email-title" >'.$get_all_mails['from'].'</td><td class="email-body" >'.$get_all_mails['subject'].'</td><td><i class="glyph-icon icon-paperclip"></i></td><td>17 Jan 2014</td></tr>';
}
$data .= '</tbody>';
echo $data;
}
And, replace your script with this:
function get_out_mail(user_name){
alert(datastring);
var a = false;
$.ajax({
type: "POST",
async: false,
url: "<?php echo site_url(); ?>admin/get_out_mails",
data: {'user_name': user_name},
cache: false,
success: function (result) {
alert(result);
var result = $.parseJSON(result);
console.log(result.from);
$('#myTable').html(result);
}
});
return a;
}

Related

Ajax POST request not working - in dependency dropdown menue in laravel blade

Here I have a dropdown menu is like - countryName->CityName->ThanaName (ThanaName depends on CityName and CityName depends on countryName)
First of all I fetch country name from database table.
I passed country name through ajax as like as below.
$(document).on('change', '[name=country]', function() {
var country = $(this).val();
get_city(country);
});
function get_city(country) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{route('get-city')}}",
type: 'POST',
data: {
country_name: country
},
success: function (response) {
var obj = JSON.parse(response);
if(obj != '') {
$('[name="city"]').html(obj);
AIZ.plugins.bootstrapSelect('refresh');
}
}
});
}
And the route in web.php is like Route::post('/get-city', 'CityController#get_city')->name('get-city');
And in CityController , the get_city method is like
public function get_city(Request $request) {
$country_info = Country::where('status',1)->where('name', $request->country_name)->first();
$cities = City::where('country_id', $country_info->id)->get();
$html = '';
foreach ($cities as $row) {
// $val = $row->id . ' | ' . $row->name;
$html .= '<option value="' . $row->name . '">' . $row->getTranslation('name') . '</option>';
}
echo json_encode($html);
}
And this is working absolutely fine and it returns cityname according to its country name. But the problem is for thanaName that depends on cityName. For this my route is like Route::post('/get-thana', 'ThanaController#get_thana')->name('get-thana');
In ThanaController, the get_thana method is like
public function get_thana(Request $request) {
$city_info = City::where('name', $request->city_name)->first();
$thanas = Thana::where('city_id', $city_info->id)->get();
$html = '';
foreach ($thanas as $row) {
// $val = $row->id . ' | ' . $row->name;
$html .= '<option value="' . $row->name . '">' . $row->getTranslation('name') . '</option>';
}
echo json_encode($html);
}
and the ajax code is like
$(document).on('change', '[name=city]', function() {
var city = $(this).val();
console.log(city);
console.log('Here');
get_thana(city);
});
function get_thana(city) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{route('get-thana')}}",
type: 'POST',
data: {
city_name: city
},
success: function (response) {
var obj = JSON.parse(response);
if(obj != '') {
$('[name="thana"]').html(obj);
AIZ.plugins.bootstrapSelect('refresh');
}
}
});
}
But it show
POST http://localhost/rul/ecom/get-thana 500 (Internal Server Error)
Here is my ajax full code.
<script type="text/javascript">
$(document).on('change', '[name=country]', function() {
var country = $(this).val();
console.log(country);
console.log('country');
get_city(country);
});
function get_city(country) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{route('get-city')}}",
type: 'POST',
data: {
country_name: country
},
success: function (response) {
var obj = JSON.parse(response);
if(obj != '') {
$('[name="city"]').html(obj);
AIZ.plugins.bootstrapSelect('refresh');
}
}
});
}
//start another
$(document).on('change', '[name=city]', function() {
var city = $(this).val();
console.log(city);
console.log('Here');
get_thana(city);
});
function get_thana(city) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{route('get-thana')}}",
type: 'POST',
data: {
city_name: city
},
success: function (response) {
var obj = JSON.parse(response);
if(obj != '') {
$('[name="thana"]').html(obj);
AIZ.plugins.bootstrapSelect('refresh');
}
}
});
}
</script>
In browser network tab the error show like the below image when I change city.
enter image description here
Browser console tab: enter image description here

How does Codeigniter receive the ajax post data in controller without input type text and input post

Here's code for Controller :
public function Update()
{
$id_form = $this->input->post('id_form');
$no_request = $this->input->post('no_request');
$data = {
"no_request" => $no_request,
"date_ps" => date('d M Y')
}
return $this->db->where('id_form', $id_form);
return $this->db->update('table', $data);
}
Here's code for View :
<input type="hidden" name="id_form" id="id_form"></br>
<input type="text" name"no_request" id="no_request"></br>
Edit
Here's code for Ajax :
$('#btn_update').on('click', function() {
var id_form = $('#id_form').val();
var no_request = $('#no_request').val();
var date_ps = $(date_ps).val();
$.ajax({
type: "POST",
url: "<?= site_url('Controller/Update') ?>",
dataType: "JSON",
data: {
id_form: id_form,
no_request: no_request,
date_ps: date_ps
},
success: function(data) {
console.log(date_ps);
}
})
}
But The result for date_ps is undefined, How can I get the date_ps value without having to undefined

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?
}

WooCommerce programmatically deleting from cart

How do I programmatically remove an item from the Woocommerce cart using AJAX? I tried putting a function in my functions.php file and accessing that but nothing gets deleted. I tried hard-coding product 299 but it doesn't delete. Here's what I did:
functions.php
function remove_item_from_cart() {
$cart = WC()->instance()->cart;
$id = 299;
$cart_id = $cart->generate_cart_id($id);
$cart_item_id = $cart->find_product_in_cart($cart_id);
if($cart_item_id){
$cart->set_quantity($cart_item_id, 0);
}
return true;
}
themes/mine/main.js
$.ajax({
type: 'POST',
dataType: 'text',
url: "http://www.../wp/wp-content/themes/mine/functions.php",
data: {
action: 'remove_item_from_cart'
},
success: function( data ) {
console.log(data);
}
});
Use proper ajax method of wordpress like this: This worked fine for me.
//functions.php
function remove_item_from_cart() {
$cart = WC()->instance()->cart;
$id = $_POST['product_id'];
$cart_id = $cart->generate_cart_id($id);
$cart_item_id = $cart->find_product_in_cart($cart_id);
if($cart_item_id){
$cart->set_quantity($cart_item_id, 0);
return true;
}
return false;
}
add_action('wp_ajax_remove_item_from_cart', 'remove_item_from_cart');
add_action('wp_ajax_nopriv_remove_item_from_cart', 'remove_item_from_cart');
//main.js
$.ajax({
type: "POST",
url: 'http://localhost/your_site/wp-admin/admin-ajax.php',
data: {action : 'remove_item_from_cart','product_id' : '4'},
success: function (res) {
if (res) {
alert('Removed Successfully');
}
}
});
This seems to work.
HTML:
<?php
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ){
?<
<button class="remove-item" data-cart-item-key="<?=$cart_item_key;?>">
remove item
</button>
<?
}
?>
Javascript:
$('.remove-item').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: ajaxurl,
data: {
action: 'remove_item_from_cart',
'cart_item_key': String($(this).data('cart-item-key'))
}
});
});
In functions.php, inside the template folder:
function remove_item_from_cart() {
$cart_item_key = $_POST['cart_item_key'];
if($cart_item_key){
WC()->cart->remove_cart_item($cart_item_key);
return true;
}
return false;
}
add_action('wp_ajax_remove_item_from_cart', 'remove_item_from_cart');
add_action('wp_ajax_nopriv_remove_item_from_cart', 'remove_item_from_cart');
For WooCommerce 3.0+ you can do it using the built-in remove_cart_item() function
function findCartItemKey($cartItems, $productId){
foreach($cartItems as $cartKey => $item){
$product = $item['data'];
if($product->get_id() == $productId){
return $cartKey;
}
return false;
}
}
global $woocommerce;
$cartItemKey = findCartItemKey($woocommerce->cart->get_cart())
$woocommerce->cart->remove_cart_item($cartItemKey);

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