How to add "route action" into response content with Ajax Zend2? - ajax

I am new to zend framework and trying to test my first app about ajax with zend2.
I want to show a link when I return a response from my controller ! I try anyways but cann't view !
I try this:
Here my HTML:
<select id="my_list" onChange="showlist(this.value);" name="my_list">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
Here my Ajax Script:
function showlist(id){
$.post("user/list", {
content: id
},function(data){
if(data.response == true){
$('#div_show').html(data['html']);
}
}, 'json');
}
And my controller:
public function listAction()
{
$request = $this->getRequest();
$response = $this->getResponse();
if ($request->isPost()) {
$post_data = $request->getPost();
$id = $post_data['content'];
if($id){
/* $html = $group; It's Ok ! I can view group value !*/
$html = 'Test !';
$response->setContent(\Zend\Json\Json::encode(array('response' => true,'html'=>$html)));
}
else{
$response->setContent(\Zend\Json\Json::encode(array('response' => false)));
}
}
return $response;
}
I can view group value when I select listbox, but I cann't see the link when I want to view its detail !
It's my first question ! Please help me.

var url = '<?php echo $this->url('user', array('action' => 'list')); ?>';
function showlist(id){
$.post(url, {
content: id
},function(data){
if(data.response == true){
$('#div_show').html(data['html']);
}
}, 'json');
}

Related

Insert fields after success payment

Hope you all have a good day..
At first i have a form that user should fill before redirect to PayTabs page for payment
But i don't need the form to be inserted in database before success payment
public function index(Request $request): RedirectResponse
{
$response = $this->request(
url: 'https://secure-global.paytabs.com/payment/request',
payload: $this->transactionPayload(
amount: 0
)
);
Transaction::create([
'paytabs_transaction_reference' => $response->json()['tran_ref'] ?? null
]);
Cart::where('opened', '=', 0)->where('user_id', Auth::id())->update(['paytabs_transaction_reference' => $response->json()['tran_ref'] ?? null]);
$cart_id = Cart::latest()->first()->id;
$payment = new Payment;
$payment->cart_id = $cart_id;
$payment->country_id = $request->input('country_id');
$payment->delivery_id = $request->input('delivery_id');
$payment->address = $request->input('address');
$payment->street = $request->input('street');
$payment->home = $request->input('home');
$payment->email = $request->input('email');
$payment->save();
return redirect()->away($response['redirect_url']);
}
public function return(Request $request): string
{
$category = Category::all();
$products = Product::all();
$validSignature = $this->validateSignature($request->all());
if ($validSignature) {
if ($request->respStatus == 'A') {
$transaction = Transaction::where('paytabs_transaction_reference', $request->tranRef)->first();
$transaction->paid = true;
$transaction->save();
DB::table('carts')->where('user_id', Auth::id())->where('opened', 0 )->update(['opened' => 1]);
return view('index', compact('category', 'products'))->with('success', 'Payment has been done successfully. Thank you!') . $request->respMessage;
}
return view('index', compact('category', 'products')) . $request->respMessage;
} else {
return 'Invalid Transaction Signature';
}
}
Here the form will be inserted even if he back from the next page
<form role="form" action="{{ route('index') }}" method="post">
#csrf
.......
</form>
That's my form should be to INDEX function to redirect to payment page
You Need To Make A Validation To Your Form

CakePHP-2.4 : subcategories according to categories by ajax

I am trying to get subcategories according to categories by ajax.So I have sent data in controller by ajax get method like bellow code in add.ctp
$('document').ready(function(){
$( "#division" ).change(function() {
var value=$('#division').val();
$.get("<?php echo Router::url(array('controller'=>'userStoreSelections','action'=>'add'));?>",{list:value},function(data){
$('.districts').html(data);
alert(data);
});
});
});
In controller in find methods when I am writing bellow code It's working fine.
$madDistricts = $this->UserStoreSelection->MadDistricts->find('list',array(
'conditions'=>array('mad_divisions_id'=>3)
));
But when I give the value that I have sent by ajax it's not working.I have written like this
$madDistricts = $this->UserStoreSelection->MadDistricts->find('list',array(
'conditions'=>array('mad_divisions_id'=>"$list")
));
It showing the query like this
SELECT `MadDistricts`.`id`, `MadDistricts`.`name` FROM `store`.`mad_districts` AS `MadDistricts` WHERE `mad_divisions_id` IS NULL
After select categories nothing change in query.I have tested ajax code there is no problem to send value.
For more specific this is the add action code
public function add() {
if(isset($this->request->query['list'])){
$search = $this->request->query['list'];
echo $search;
}
else{
$search = '';
}
if ($this->request->is('post')) {
$this->UserStoreSelection->create();
if ($this->UserStoreSelection->save($this->request->data)) {
$this->Session->setFlash(__('The user store selection has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user store selection could not be saved. Please, try again.'));
}
}
$madDivisions = $this->UserStoreSelection->MadDivisions->find('list');
$madDistricts = $this->UserStoreSelection->MadDistricts->find('list',array(
'conditions'=>array('mad_divisions_id'=>"$list")
));
$madAreas = $this->UserStoreSelection->MadAreas->find('list');
$users = $this->UserStoreSelection->Users->find('list',array('fields' => array('id','username')));
$madStores = $this->UserStoreSelection->MadStores->find('list',array('fields' => array('id','store_name')));
$this->set(compact('madDivisions', 'madDistricts', 'madAreas', 'users','madStores'));
}
You need to change your add.ctp file code like as :
$('document').ready(function () {
$("#division").change(function () {
var value = $(this).val();
$.ajax({
url: '<?php echo Router::url(' / ',true);?>userStoreSelections/subcategories',
type: "POST",
dataType: 'json',
data: 'category=' + id,
success: function (res) {
var html = '<option>Sub Category</option>';
if (res.flage == true) {
html = res.data;
}
$('.districts').html(html);
}
});
});
});
Than create a function in your userStoreSelections for get sub categories as
public function subcategories() {
$response = array('flage' => false);
$madDistricts = $this->UserStoreSelection->MadDistricts->find('list', array(
'conditions' => array('mad_divisions_id' => $this->request->data['category'])
));
$options = "<option>Subcategories</option>";
if ($states) {
$response['flage'] = true;
foreach ($madDistricts as $id => $name) {
$options .= "<option value='" . $id . "'>" . $name . "</option>";
}
$response['data'] = $options;
}
echo json_encode($response);
exit;
}

Calling another view page through ajax in codeigniter view page

I have a view page, from that page I want to call another view page through ajax. This is the code i'm using, but I'm not getting the response.
This is my code
var dataString = 'product_name='+product_name+'&qty='+qty+'&cost='+price;
$.ajax({
url:'myCart.php',
type:"get",
data: dataString,
success:function(data)
{
alert(data);
}
});
This is my myCart.php. In this I have get all the values passed from that page though url.
<?php
session_start();
if (!isset($_SESSION['SHOPPING_CART'])){
$_SESSION['SHOPPING_CART'] = array();
}
$session = $_SESSION['SHOPPING_CART'];
function inMultiArray($name,$session) {
if (array_key_exists($name,$session) or in_array($name,$session)) {
return true;
} else {
$return = false;
foreach (array_values($session) as $value) {
if (is_array($value) and !$return) {
$return = inMultiArray($name,$value);
}
}
return $return;
}
}
$name = 'Test' ;
$result = inMultiArray($name,$session);
if($result){
echo 'Yes';
}
// else, add the item to the array
else{
$ITEM = array(
//Item name
'product_name' => $_GET['product_name'],
//Item Price
'cost' => $_GET['cost'],
//Qty wanted of item
'qty' => $_GET['qty']
);
//Add this item to the shopping cart
$_SESSION['SHOPPING_CART'][] = $ITEM;
$total=0;
foreach ($_SESSION['SHOPPING_CART'] as $itemNumber => $items) {
$total = $total + $items['cost'];
// print $items['cost'];
// print $items['qty'];
}
echo $total;
}
?>
As I now clearly understood your question, it is wrong to call a view. Instead call your controller which will call the model to perform some operation and return the result you want

Codeigniter Form Helper - How to add additional parameters to "select" control?

I need to modify a site that was written in Codeigniter but I'm no expert.
One thing I'd like to do is modify a select control in a form to use ms-dropdown for a drop-down list including pictures.
However, I can't work out how to make the Codeigniter form helper render parameters other than ID and Value in each option. In this case, to make ms-dropdown work, it would need to also render data-image="..." in each option.
The current code looks like:
$dropdown = array(
'name'=>'MyDropDown',
'options' => array('Op1'=>'First Option', 'Op2' =>'Second Option')
);
echo form_dropdown($dropdown['name'],$dropdown['options']);
This renders as
<select name="MyDropDown">
<option value='Op1'>First Option</option>
<option value='Op2'>Second Option</option>
</select>
Is there a way for me to make Codeigniter render
<select name="MyDropDown">
<option value='Op1' data-image="filepath1">First Option</option>
<option value='Op2' data-image="filepath2">Second Option</option>
</select>
You can't. You would need to extend CI's Form Helper and modify
form_dropdown to accept other attributes like ID's
you will have to extend the helper .
to extend the native Form Helper you'll create a file named
application/helpers/MY_form_helper.php, and add or override
functions:
if you want to override function form_dropdown
simply write the function the way you want in MY_form_helper.php
here is the base function
if ( ! function_exists('form_dropdown'))
{
function form_dropdown($name = '', $options = array(), $selected = array(), $extra = '')
{
if ( ! is_array($selected))
{
$selected = array($selected);
}
// If no selected state was submitted we will attempt to set it automatically
if (count($selected) === 0)
{
// If the form name appears in the $_POST array we have a winner!
if (isset($_POST[$name]))
{
$selected = array($_POST[$name]);
}
}
if ($extra != '') $extra = ' '.$extra;
$multiple = (count($selected) > 1 && strpos($extra, 'multiple') === FALSE) ? ' multiple="multiple"' : '';
$form = '<select name="'.$name.'"'.$extra.$multiple.">\n";
foreach ($options as $key => $val)
{
$key = (string) $key;
if (is_array($val) && ! empty($val))
{
$form .= '<optgroup label="'.$key.'">'."\n";
foreach ($val as $optgroup_key => $optgroup_val)
{
$sel = (in_array($optgroup_key, $selected)) ? ' selected="selected"' : '';
$form .= '<option value="'.$optgroup_key.'"'.$sel.'>'.(string) $optgroup_val."</option>\n";
}
$form .= '</optgroup>'."\n";
}
else
{
$sel = (in_array($key, $selected)) ? ' selected="selected"' : '';
$form .= '<option value="'.$key.'"'.$sel.'>'.(string) $val."</option>\n";
}
}
$form .= '</select>';
return $form;
}
}
you have to edit this part ,
foreach ($options as $key => $val)
{
$key = (string) $key;
if (is_array($val) && ! empty($val))
{
$form .= '<optgroup label="'.$key.'">'."\n";
foreach ($val as $optgroup_key => $optgroup_val)
{
$sel = (in_array($optgroup_key, $selected)) ? ' selected="selected"' : '';
$form .= '<option value="'.$optgroup_key.'"'.$sel.'>'.(string) $optgroup_val."</option>\n";
}
$form .= '</optgroup>'."\n";
}
else
{
$sel = (in_array($key, $selected)) ? ' selected="selected"' : '';
$form .= '<option value="'.$key.'"'.$sel.'>'.(string) $val."</option>\n";
}
}
as you can see , only the option's value attribute is set by the function , you can edit this code and
do the thing you want ,
try it , if you could not do it , tell me i ll help you , but first give it a try :)
Consider doing something like this:
<script type="text/javascript">
var filepath = <?=json_encode($dropdown['filepath'])?>;
</script>
$dropdown['filepath'] would use the option value as keys and store the filepath as the value. Then you can simply access filepath[$(this).val()] upon change event.
Example output:
<script type="text/javascript">
var filepath = { 'Op1' : 'filepath1', 'Op2' : 'filepath2' };
$('select').bind('change', function() {
console.log(filepath[$(this).val()]);
});
</script>
As much as I love using data- attributes, one must not forget other ways to achieve their goals.
In case it helps anyone, I found a work-around using JQuery.
I made a javascript function that applied the data-image attribute to each option field once the page was ready, then called the msDropdown function afterwards.
function PiccifyShowDropdown(){
var Diagrams = new Array(
"/assets/images/icons/SixtyToHundredPercent.png",
"/assets/images/icons/LessThanThirtyPercent.png",
"/assets/images/icons/ThirtyToSixtyPercent.png",
"/assets/images/icons/SixtyToHundredPercent.png"
);
$("#Show > option").each(
function() {
$(this).attr("data-image",Diagrams[this.index]);
}
);
$("#Show").msDropdown({visibleRows:2});
}
This seems to have worked, so now I just need someone to solve the same problem as this guy...

Codeigniter. Controller cannot receive session data

I set session successfully as output profiler show me session name and value.
But when I POST data controller cannot receive session data.
Library is loaded, $config['sess_expire_on_close'] = TRUE I've changed TRUE-FALSE without any success. Also tried rewrite code.
And another question I use two PC and on Linux machine I get error "Header already sent...", but on Win machine I don't receive this message. How to enable it on Win PC. Notices and warnings are enabled.
So ...
Controller kmgld:
function authorisation_user()
{
......
$data['set_cookie'] = "Surname";
......
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->output->enable_profiler(TRUE); //show me only session name and value which I set
}
View:
if ($set_cookie!=NULL)
{
$this->session->set_userdata('surname',$set_cookie);
}
<!Doctype...>
<form action="<?php echo base_url()?>index.php/kmgld/update_kmgld" method="post" name="">
And again Controller kmgld
function update_kmgld()
{
...update DB
$test=$this->session->userdata('surname');
echo $test; //it is NULL
$this->output->enable_profiler(TRUE); // show me only now session id, ip, user agent
}
you have to set the userdata in the controller, the view isn't the proper place for it. so you probably would do something like this in your controller:
$surname = "Surname";
$this->session->set_userdata('surname',$surname);
$data['set_cookie'] = $surname;
...
$this->load->view('vheader', $data);
don't know if you autoload the session library. otherwise you have to load it in every function you need it.
remove session setting from view and do it in controller:
function authorisation_user()
{
$data['set_cookie'] = "Surname";
$this->session->set_userdata('surname',$set_cookie);
$this->load->view('vheader', $data);//are you sure here is where $data should go ?
$this->load->view('vuser_kmgld');//not $data here?
$this->output->enable_profiler(TRUE); //show me only session name and value which I set
}
Controller:
<?php
class Kmgld extends CI_Controller {
function index()
{
$data['flag'] = "first";
$this->load->model('Mkmgld');
$this->load->view('vheader');
$this->load->view('vauthorisation',$data);
$this->load->view('vfooter');
}
function get_kmgld()
{
$this->load->model('Mkmgld');
$this->Mkmgld->get_kmgld();
$this->load->view('vheader');
$this->load->view('kmgld');
$this->load->view('vfooter');
}
function authorisation_user()
{
$this->load->model('Mkmgld');
$surname_session = $this->session->userdata('surname');
$data['surname_post'] = mb_convert_case($this->input->post('surname'), MB_CASE_TITLE, "UTF-8");
$data['user_id'] = $this->Mkmgld->valid_user($data['surname_post']);
$surname = (isset($data['user_id'][0]->surname)? $data['user_id'][0]->surname: "");
if(isset($surname) and $surname !=NULL)
{
$data['query'] = $this->Mkmgld->get_kmgld($data['surname_post']);
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$data['set_cookie'] = $data['surname_post'];
$this->session->sess_destroy();
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->load->view('vfooter');
}else if (isset($surname_session) and $surname_session!= NULL)
{
//echo "you are in session";
$data['query'] = $this->Mkmgld->get_kmgld($surname_session);
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->load->view('vfooter');
} else
{
$data['flag'] = "wrong";
$this->load->view('vheader');
$this->load->view('vauthorisation',$data);
$this->load->view('vfooter');
}
//echo "<pre>";
//var_dump($data);
$this->output->enable_profiler(TRUE);
}//end authorisation_user()
function update_kmgld()
{
$this->load->model('Mkmgld');
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$trip_target_id = $data['get_trip_target_id'][0]->Auto_increment;
$this->Mkmgld->update_kmgld($this->input->post('day')
,$this->input->post('mon')
,$this->input->post('year')
,$this->input->post('spd_before')
,$this->input->post('spd_after')
,$this->input->post('total')
,$this->input->post('target')
,$this->input->post('approved')
,$this->input->post('user_id')
,$trip_target_id);
$a=$this->session->userdata('surname');
if ($a==NULL)
{
echo $a;
//redirect('kmgld/authorisation_user');
$this->output->enable_profiler(TRUE);
}
}
}//end class kmgld
?>
Model:
enter code here<?php
Class Mkmgld extends CI_Model {
function __construct()
{
parent::__construct();
}
function get_kmgld($surname){
$query = $this->db->query("SELECT
*
FROM `user`
INNER JOIN `user_has_trip`
ON `user`.`user_id` = `user_has_trip`.`user_id`
INNER JOIN `trip_target`
ON `user_has_trip`.`user_has_trip_id` = `trip_target`.`trip_target_id`
WHERE `user`.`surname` = '$surname'
");
return $query->result();
}
function valid_user($surname)
{
$user_id = $this->db->query("SELECT
*
FROM `user`
WHERE `user`.`surname`='$surname'
");
return $user_id->result();
}
function get_trip_target_id()
{
$get_trip_target_id = $this->db->query("SHOW TABLE STATUS LIKE 'trip_target'");
return $get_trip_target_id->result();
}
function update_kmgld($day, $mon, $year, $spd_before, $spd_after, $total, $target, $approved, $user_id, $trip_target_id)
{
$date = $year."-".$mon."-".$day;
$this->db->query("INSERT INTO `trip_target` (`trip_target_id`
,`date`
,`speedometer_before`
,`speedometer_after`
,`duration`
,`target`
,`approved`)
VALUES (NULL
,'$date'
,'$spd_before'
,'$spd_after'
,'$total'
,'$target'
,'$approved')
");
$this->db->query("INSERT INTO `user_has_trip`
(`user_has_trip_id`
,`user_id`
,`trip_target_id`
)
VALUES (NULL
,'$user_id'
,'$trip_target_id'
)
");
}
}//end class
?>
View vauthorisation:
<?php
$surname_value = $this->session->userdata('surname');
?>
<?php
if ($flag =="wrong")
{
echo "...Bad very bad. Try use another language ";
}
?>
html:
form method="post" action="authorisation_user"
input type="text" name="surname"
View vheader:
<?php
if ($set_cookie!=NULL)
{
$this->session->set_userdata('surname',$set_cookie);
echo "cookie set".$set_cookie;
}
?>
View vuser_kmgld:
html:
form action="update_kmgld"
inputs name=day, name=mon, name=year, name=spd_before...etc. After php code:
if (isset($user_id[0]->user_id))
{
foreach ($query as $row)
{
echo "<tr>
<td>".(isset($row->date)? date("d.m.Y", strtotime($row->date)): "")."</td>
<td>". (isset($row->speedometer_before)? $row->speedometer_before : "")."</td>
<td>". (isset($row->speedometer_after)? $row->speedometer_after : "")."</td>
<td>". (isset($row->duration)? $row->duration : "")."</td>
<td>". (isset($row->target)? $row->target : "")."</td>
<td>". (isset($row->aproved)? $row->aproved : "")."</td>
</tr>";
}
} //else redirect('kmgld/index');
?>

Resources