jquery ajax not inserting data in mysql table - codeigniter

I am new to jquery-ajax. My payment_gateway_1.php is:
<script>
var cst_dta = {
'name' : 'amar',
'total_bill' : '550',
'phone' : '3612303957'
};
$(document).ready(function(){
//alert(cst_dta['name']); alerts amar
$.ajax({
'url': 'http://localhost/nitish/paymentgatewayverify.php',
'type': 'POST',
'data': cst_dta,
'cache' : false,
success: success,
dataType: dataType
});
});
</script>
And paymentgatewayverify.php is :
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'democart';
$name = $_POST['name'];
$bill = $_POST['total_bill'];
$phone = $_POST['phone'];
try
{
$conn = new PDO('mysql:host=$host;dbname=$db',$username,$password);
}catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$stmt = $conn->prepare("INSERT INTO data_table(name,bill,phone) VALUES(:name,:bill,:phone)");
$stmt->bindParam(":name",$name);
$stmt->bindParam(":bill",$bill);
$stmt->bindParam(":phone",$phone);
$stmt->execute();
$trans_id = 123444;
$trans_status = 1;
header('Location:http://localhost/cishop/index.php/checkout/payment_status/?status='.$trans_status.'&trans_id='.$trans_id);
?>
I was expecting the datas will be inserted to my mysql table, but they are not ! Whats wrong with my code ?

Related

Cakephp 4 giving 403 error while using ajax

I am trying to implement cascading drop down box in cakephp 4 using ajax.
I'm getting an 403 error has tried many solutions from google and stack overflow from htaccess till syntax error and logical error can anyone please help trying since long.
Here is my code:
Add.php
<?php echo $this->Form->control('groups',['options' => $groups],array('id'=>'GroupId'));
echo $this->Form->input('user_id',array('id'=>'UsersId'));
?>
<?= $this->Form->button(__('Submit'),array('id'=>'post')) ?>
<?= $this->Form->end() ?>
<?php echo $this->Html->script('//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js');?>
<script type="text/javascript" >
$(document).ready(function(){
$("#groups").change(function(){
var deptid = $(this).val();
//var path="<?php echo $this->Url->webroot ?>/Users/getbygroup";
$.ajax({
url: '../Users/getbygroup',
type: 'POST',
data: deptid,
dataType: 'json',
cache: false,
contentType: false,
success:function(response){
var len = response.length;
$("#UserId").empty();
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['name'];
$("#UserId").append("<option value='"+id+"'>"+name+"</option>");
}
}
});
});
});
</script>
Add action in files controller:
public function add()
{
$this->loadModel('Users');
$this->loadModel('Groups');
$this->set('groups', $this->Groups->find('list'));
$result = $this->Users->find('all'); // returns query object
$data = $result->toArray(); // converts query object to key value array
$file = $this->Files->newEmptyEntity();
if ($this->request->is('post')) {
$file = $this->Files->patchEntity($file, $this->request->getData());
if ($this->Files->save($file)) {
$this->Flash->success(__('The file has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The file could not be saved. Please, try again.'));
}
$this->set(compact('file'));
}
getbygroup function in users controller:
public function getbygroup() {
$fname= $this->request->getData('deptid');
$this->viewbuilder()->layout = 'ajax';
$users = $this->Users->find('list', array(
'conditions' => array('Users.group_id' => $fname),
'recursive' => -1));
$this->set('users', $users);
}

Getting 400 Bad Request when calls ajax function using datatables server side scripting Wordpress

I'm creating one plugin to get data from custom table using datatable server side scripting.
In query i'm getting right response but in ajax function call getting 400 bad request
Request URL: http://localhost/Project_name/wp-admin/admin-ajax.php
Request Method: POST
Status Code: 400 Bad Request
Remote Address: [::1]:80
my ajax js file
$(document).ready(function() {
var dataTable = $('#employee-grid').DataTable( {
"processing": true,
"serverSide": true,
dataType: "json",
contentType: "application/json",
"ajax":{
"url" : 'admin-ajax.php',
"type": "POST",
"data": {action: 'my_action'},
error: function(){ // error handling
$(".employee-grid-error").html("");
$("#employee-grid").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#employee-grid_processing").css("display","none");},
success: function(data){
alert(data);
}
},
"columns": [
{"data": "employee_name"},
{"data": "employee_salary"},
{"data": "employee_age"}
], "columnDefs": [
//{"orderable": false, "targets": 12}
]
} );
} );
in ajax file also adding wp_ajax_my_action and wp_ajax_nopriv_my_action action.
ajaxfile function file
add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
function my_action() {
global $wpdb;
## Read value
$draw = $_POST['draw'];
$row = $_POST['start'];
$rowperpage = $_POST['length']; // Rows display per page
$columnIndex = $_POST['order'][0]['column']; // Column index
$columnName = $_POST['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
$searchValue = $_POST['search']['value']; // Search value
## Search
$searchQuery = " ";
if($searchValue != ''){
$searchQuery = " and (reportNo like '%".$searchValue."%' or ) ";
}
$totalRecordwithFilter = $records['allcount'];
## Total number of records without filtering
$sel = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'employee');
$totalRecords = count($sel);
## Total number of records with filtering
/* $sel = mysqli_query($con,"select count(*) as allcount from employee WHERE 1 ".$searchQuery);
$records = mysqli_fetch_assoc($sel); */
$resultCount = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'employee where '.$searchQuery);
$totalRecordwithFilter = count($resultCount);
## Fetch records
//$empQuery = "select * from employee WHERE 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;
$empRecords = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'employee where '.$searchQuery.' order by ' . $columnName . ' ' . $columnSortOrder . ' limit ' . $row . ',' . $rowperpage);
$empRecords = mysqli_query($con, $empQuery);
$data = array();
foreach ($sel as $row) {
$data[] = array(
"emp_name"=>$row->employee_name,
"salary"=>$row->employee_salary,
"age"=>$row->employee_age
);
}
## Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data
);
echo json_encode($response);
exit();
}
UPDATE
As I checked you use parameters that don't exist in your POST method, you need to add them and also check that they are exist
you should pass you POST parameters with your ajax function like this
data: {
action: 'search_enrollment_by_scode',
draw : 'draw',
row : 'start',
rowperpage : 'length',
columnIndex : 'order',
columnName : 'columns',
columnSortOrder : 'order',
searchValue : 'search',
}
NOTE: you should add your valid data or variable
Your PHP file
<?php
add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
function my_action() {
global $wpdb;
## Read value
// you need to check that you have this data or not
// you just add action data not any of bellow list
if ($_POST['draw']) {
$draw = $_POST['draw'];
.
.
.
.
.
.
.
echo json_encode($response);
}
else
{
echo json_encode('Data is invalid or not complete');
}
exit();
}
?>
Try this and then replace the ajaxurl variable in your "url" : 'admin-ajax.php',
<script type="text/javascript">
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
As is described in the Wordpress AJAX documentation, you have two different hooks - wp_ajax_(action), and wp_ajax_nopriv_(action). The difference between these is:
wp_ajax_(action): This is fired if the ajax call is made from inside the admin panel.
wp_ajax_nopriv_(action): This is fired if the ajax call is made from the front end of the website.

Set bootstrap selected option with ajax value

I try to display data on the bootstrap select option with ajax, but after I run the data do not want to appear what is wrong?
function get_value() {
$id = 5;
$q = $this->db->select('*')
->from('tbl_v')
->where('id', $id)
->order_by('id', 'ASC')
->get();
$result = $q->result();
echo json_encode($result );
}
$(".change").change(function(){
var value=$(this).val();
if(value>0){
$.ajax({
url: base_url+"get_value",
type:"POST",
dataType: 'json',
cache: false,
data:{id:value},
success: function(respond){
$(".get-change").html(respond).selectpicker('refresh');
}
})
}
});
Try this...
function OnChangeValue()
{
var pdrp = document.getElementById("yourControlIDHere");
getvalue= pdrp.options[pdrp.selectedIndex].value;
alert(getvalue);
}
The Control
<select id="yourControlIDHere" onchange="OnChangeValue(this)" name="companyname" style="width:100%">
Jquery Code
$(".change").change(function(){
var value=$(this).val();
if(value>0){
$.ajax({
url: base_url+"get_value",
type:"POST",
cache: false,
data:{id:value},
success: function(respond){
$(".get-change").html(respond);
}
})
}
});
Modal Code:
function get_records() {
$id = 5;
$q = $this->db->select('*')
->from('tbl_v')
->where('id', $id)
->order_by('id', 'ASC')
->get();
$result = $q->result();
}
Controller Code:
function get_value(){
$ido = $this->input->post('id');
$data = $this->your-model-name->get_records($ido);
$option = "";
foreach($data as $row){
$option .= "<option value='".$value['ID']."'>".$row[0]->name."</option>";
}
echo $option;
}
You need not have to use JSON encoding. Records will be directly appended to the select box. Hope this can help you.

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

CakePHP - Update Dropdown list

I know you guys may have already answered loads of questions like this but I really need some help in my situation.
I couldn't find any answer that suits me.
I have 2 dropdown lists in a form (form id MapInitForm) :
Zone : a list of my zones (id : zoneSelect), already populated
Territory : a list of my territories (id : territorySelect)
I do have a zone_id in my Territories table.
So when I select one Zone, I need to get all associated Territories. And when I select one territory, I'll need to do some PHP stuff;
EDITED thanks to Mark's answer.
$('#MapInitForm #zoneSelect').change(function(){
var zone_id = $(this).val();
var zone_id = $(this).val();
var targeturl = $(this).attr('rel') + '?id=' + zone_id;
$.ajax({
type: 'get',
url: targeturl,
beforeSend: function(xhr) {
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
},
success: function(response) {
if (response.content) {
$('#territorySelect').html(response.content);
}
else {
console.log(response.content);
}
},
error: function(e) {
alert("An error occurred: " + e.responseText.message);
console.log(e);
}
});
});
In my controller :
public function zone_territories_ajax() {
$this->request->onlyAllow('ajax');
$id = $this->request->query('id');
if (!$id) {
throw new NotFoundException();
}
$this->loadModel('Territory');
$data = $this->paginate('Territory', array('Territory.zone_id =' => $id));
// $data = $this->Territory->find('all', array('condition' => array('Territory.zone_id =' => $id)));
$this->set('zoneTerritories', $data);
}
In my view :
$url = $this->Html->url(array('controller' => 'zones', 'action' => 'zone_territories_ajax'));
echo $this->Form->create('Map');
echo $this->Form->input('zone_id', array(
'options' => $zones,
'empty' => '--- Select one ---',
'id' => 'zoneSelect',
'rel' => $url
));
echo $this->Form->input('zone_territory_id', array(
'empty' => '--- Select one zone ---',
'id' => 'territorySelect',
));
echo $this->Form->end();
And finally in my zone_territories_ajax.ctp :
if (!empty($zoneTerritories)) {
$k = 0;
foreach($zoneTerritories as $zoneTerritory):
echo '<option value="' . $k . '">' . $zoneTerritory['Territory']['name'] . '</option>';
$k++;
endforeach;
}
else {
echo '<option value="0">' . __('noOptionAvailable') . '</option>';
}
In my console, I'm getting undefined for console.log(response.content);
But I'm getting the correct values for the selected zone (I see those in my console again) but nothing happens on the second dropdown list.
What did I do wrong ?
You are lucky, just a while back I wrote something about AJAX and CakePHP:
http://www.dereuromark.de/2014/01/09/ajax-and-cakephp
And in particular, you can see a full blown example of exactly that functionality here:
http://sandbox.dereuromark.de/sandbox/ajax_examples/chained_dropdowns
The code is linked at the bottom - see github
Basically:
$('#source').change(function() {
var selectedValue = $(this).val();
var targeturl = $(this).attr('rel') + '?id=' + selectedValue;
$.ajax({
type: 'get',
url: targeturl,
beforeSend: function(xhr) {
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
},
success: function(response) {
if (response.content) {
$('#target').html(response.content);
}
},
error: function(e) {
alert("An error occurred: " + e.responseText.message);
console.log(e);
}
});
});

Resources