I did multiple inserts with different qty. when making a transaction, I accommodate it in a temporary or append table. However, only the last qty is stored
this HTML
MODEL
public function simpan_data($data_pickup){
$this->simpan_pickup($data_pickup);
$last_key = $this->db->insert_id();
$tmp = $this->get_temporary();
foreach($tmp as $t){
$data_detail = array(
'id_pickup' => $last_key,
'id_barang' => $t->id_barang,
'qty_pickup' => $this->input->post('qty_pickup')
);
$this->db->insert('pickup_detail', $data_detail);
}
}
public function simpan_pickup($data){
$res = $this->db->insert('pickup', $data);
return $res;
}
CONTROLLER
public function add_tem_pickup(){
$idnya = $this->input->post('id_barang');
$cektmp = $this->M_pickup->cek_temporary($idnya);
if ($cektmp > 0) {
$arr=array(
'sukses' => false,
'pesan' => 'Barang sudah Pickup'
);
//alert
}else{
$data_insert = array(
'jenis' => 'PICK',
'id_barang' => $idnya
);
$this->db->insert('tem_pickup', $data_insert);
$arr = array(
'sukses' => true,
'pesan' => 'berhasil'
);
}
echo json_encode($arr);
}
public function simpan_pickup(){
$data = array(
'kd_pickup' => $this->input->post('kd_pickup'),
'id_cs' => $this->input->post('id_cs')
);
$this->M_pickup->simpan_data($data);
$this->db->delete('tem_pickup', array('jenis' => 'PICK'));
echo $this->session->set_flashdata('message','success');
redirect('backend/pickup');
}
how could this happen ? Please help
You could setup a hidden qty_pickup input after the ajax calls success (using jquery after()), here I renamed this new input to qty_pickup_new[] to differentiate it with the existing qty_pickup input :
// another js codes here...
//
$(".btnadd").click(function(){ //input append
var id_barang = $("input[name='id_barang']").val();
var nama_barang = $("input[name='nama_barang']").val();
var qty_pickup = $("input[name='qty_pickup']").val();
var sisa = $("input[name='qty_pickup']").val();
var harga_jual = $("input[name='harga_jual']").val();
var satuan = $("input[name='satuan']").val();
var kd_pickup = $("input[name='kd_pickup']").val();
// var tgl_pickup = $("input[name='tgl_pickup']").val();
var tipe_dimensi = $("input[name='tipe_dimensi']").val();
var tgl_pickup = $("input[name='tgl_pickup']").val();
$.ajax({
url: '<?php echo base_url();?>backend/pickup/add_tem_pickup',
type: 'POST',
dataType: 'JSON',
data: {
id_barang: id_barang,
qty_pickup: qty_pickup,
sisa: qty_pickup,
harga_jual: harga_jual,
kd_pickup: kd_pickup,
// tgl_pickup: tgl_pickup,
satuan: satuan,
tipe_dimensi: tipe_dimensi,
tgl_pickup: tgl_pickup,
},
error: function() {
},
success: function(data) {
if(data.sukses==false){
alert(data.pesan);
}else{
$('#tbody').append("<tr><td>"+kd_pickup+"</td><td>"+nama_barang+"</td><td>"+qty_pickup+"</td><td>"+harga_jual+"</td><td>"+satuan+"</td><td>"+tipe_dimensi+"</td></tr>");
// added below codes, set array input with id_barang as the key
$('[name="harga_jual"]').after('<input type="hidden" name="qty_pickup_new[' + id_barang + ']" value="' + qty_pickup + '">');
}
}
});
});
Then you could use the qty_pickup_new[] on the model by using the id_barang as the key (as previous javascript codes does) :
public function simpan_data($data_pickup){
$this->simpan_pickup($data_pickup);
$last_key = $this->db->insert_id();
$tmp = $this->get_temporary();
foreach($tmp as $t){
$qty_pickup = $this->input->post('qty_pickup_new')[$t->id_barang]; // using id_barang as qty_pickup_new[] key
$data_detail = array(
'id_pickup' => $last_key,
'id_barang' => $t->id_barang,
'qty_pickup' => !empty($qty_pickup) ? $qty_pickup : '' // sets data as empty if input is empty
);
$this->db->insert('pickup_detail', $data_detail);
}
}
Related
This question has been asked already but it is not solving my specific query. What I am trying to achieve is whenever a user inputs the pincode, via AJAX I am sending the pincode to PHP and returning the results with that pincode. If a single area is mapped to a particular pincode then my code works. But if there are multiple areas with same pincode then my code breaks. I have tried multiple ways. I have even tried this: Link
Here is my code
$('.input-pc').on('keyup change', function(){
PincodeId = $(this).attr('id');
PincodeVal = $("#" + PincodeId).val();
checkPincodeLength = PincodeVal.length;
if(checkPincodeLength == 6){
$('#' + PincodeId).next().next('.invalid-feedback').html('');
$.ajax({
url: "../../auth/regrequest.php",
type: "POST",
data: 'current_pincode='+PincodeVal,
dataType: 'JSON',
cache: false,
success: function(data){
console.log('pc: '+data);
$.each(data, function(index, val) {
console.log(val);
})
}
});
}else{
$('#' + PincodeId).next().next('.invalid-feedback').html('<span><i class="fa fa-exclamation-circle" aria-hidden="true"></i> Pincode must be of 6 digits</span>');
}
});
I have even tried removing the dataType and parsed the data using JSON.parse. This too did not work.
My PHP code looks like this
if(isset($_POST['current_pincode']) && !empty($_POST['current_pincode'])){
$current_pincode = $_POST['current_pincode'];
$query26 = $dbc->prepare("SELECT a.area_id, a.city_id, a.state_id, b.state_name, c.city_name, d.area_name FROM pincodes a, states b, cities c, areas d WHERE a.pincode_code = ? AND a.state_id = b.state_id AND a.city_id = c.city_id AND a.area_id = d.area_id GROUP BY area_id ORDER BY area_id");
$query26->bindParam(1, $current_pincode);
$query26->execute();
$citystate = '';
$city_id = '';
//$citystatearray = array(
// 'CityState' => array(),
//);
//$i = 0;
//while ($getcitystate = $query26->fetch(PDO::FETCH_ASSOC)){
// $citystatearray['CityState'][$i++] = $getcitystate;
// echo json_encode($citystatearray);
// }
foreach($query26 AS $getcitystate){
// $state_id = $getcitystate['state_id'];
// $state_name = $getcitystate['state_name'];
// $city_id = $getcitystate['city_id'];
// $city_name = $getcitystate['city_name'];
// $area_name = $getcitystate['area_name'];
// $rowCount = $query26->rowCount();
// //$citystate .= $area_name.',';
// //$pct = $getcitystate['pincodetime'];if(count($area_name) == 1){echo 'only one';}else{echo 'more than 1';}
if($rowCount == 1){
// $citystate =
// array(
// 'current_pincode' => $current_pincode,
// 'state_id' => $state_id,
// 'state_name' => $state_name,
// 'city_id' => $city_id,
// 'city_name' => $city_name,
// 'area_name' => $area_name,
// 'rowcount' => $rowCount
// );
}else{
$citystate .=
array(
'current_pincode' => $current_pincode,
'state_id' => $state_id,
'state_name' => $state_name,
'city_id' => $city_id,
'city_name' => $city_name,
'area_name' => array('area_name_inner' => $area_name),
'area_name' => $area_name,
'rowcount' => $rowCount
);
}
//echo $citystate;
}echo json_encode(
array(
'citystate' => $citystate
)); //echo json_encode(
// array(
// 'citystate' => $citystate
// ));//echo $citystate;
//echo $city_id;
// echo $citystate1 = $city_id.','.$rowCount.','.$citystate;
}
I have not removed the comments to show the different ways i tried to output the data but in vain. Any help would be highly appreciated. Thanks!
I have a bit of a bug, and I can't tell where the error comes from.
I am building a cart system that will insert multiple data to a database from a cart on submit.
I'm using AJAX for this and I'm have errors, please I need help.
Here are my code snippets:
JavaScript Code
function addSale(payment_type, cash_tendered) {
var cust_name = $("#cust_name").val();
var amt_owed = $("#amt_owed").val();
$.confirm({
title: 'Checkout',
content: '' +
'<form action="" class="formName" role="form">' +
'<div class="form-group">' +
'<label>Payment Type</label>' +
'<select id="eType" class="name form-control">' +
'<option value="cash">Cash</option>' +
'<option value="card">Card</option>' +
'</select>' +
'</div>' +
'<div class="form-group">' +
'<label>Cash Tendered</label>' +
'<input type="number" id="eCash" placeholder="Cash Tendered" class="name form-control">' +
'</div>' +
'</form>',
buttons: {
cancel: function () {
//close
},
formSubmit: {
text: 'Checkout',
btnClass: 'btn-success',
action: function () {
payment_type = this.$content.find('#eType').val();
cash_tendered = this.$content.find('#eCash').val();
if (!payment_type || !cash_tendered) {
$.alert('Please fill all fields.');
return false;
}
$.confirm({
title: 'Do you want to continue?',
type: 'orange',
content: 'Click Ok to add sale',
buttons: {
cancel: function () {
},
proceed: {
text: 'Ok',
btnClass: 'btn btn-success',
action: function () {
var addUrl = "home/addsales";
addUrl += "/" + payment_type;
addUrl += "/" + cash_tendered;
addUrl += "/" + cust_name;
addUrl += "/" + amt_owed;
//
$.ajax({type: 'GET', url: addUrl, data: {},
success: function (result) {
$.alert({
content: result
});
$("#eType").val("");
$("#eCash").val("");
$("#cust_name").val("");
$("#amt_owed").val("");
location.reload();
},
error: function (xhr, status, error) {
$.alert({
content: 'Could not complete the process. ' + error
});
}
});
}
}
}
});
}
}
},
onContentReady: function () {
// bind to events
var jc = this;
this.$content.find('form').on('submit', function (e) {
// if the user submits the form by pressing enter in the field.
e.preventDefault();
jc.$$formSubmit.trigger('click'); // reference the button and click it
});
}
});
}
Here is the Home Controller Code:
private function addsales($payment_type = null, $cash_tendered = null, $cust_name = null, $amt_owed = null) {
if (isset($payment_type, $cash_tendered)) {
$email = $_SESSION[DbStrings::$EMAIL];
$payment_type = $this->test_input($payment_type);
$cash_tendered = $this->test_input($cash_tendered);
$insertedSale = $this->member->insertDailySale($email, $payment_type, $cash_tendered);
$cust_name = $this->test_input($cust_name);
$amt_owed = $this->test_input($amt_owed);
$insertedCredit = 1;
if (isset($cust_name, $amt_owed) && $amt_owed > 0) {
$insertedCredit = $this->member->insertCredit($email, $cust_name, $amt_owed);
}
if ($insertedSale && $insertedCredit) {
$_SESSION['temp_invoice'] = $_SESSION[DbStrings::$INVOICE];
$chars = "003232303232023232023456789";
srand((double) microtime() * 1000000);
$i = 0;
$pass = '';
while ($i <= 7) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
$alpha = 'NM-' . $pass;
$_SESSION[DbStrings::$INVOICE] = $alpha;
echo "Your sale has been inserted succesfully";
} else {
echo "There was a problem inserting your sale. Please try again.";
}
} else {
echo 'Please fill all fields';
}
}
And Here is my Model Code that still fetches other functions:
public function insertDailySale($email, $payment_type, $cash_tendered) {
$invoice = $_SESSION[DbStrings::$INVOICE];
$this->db->from(DbStrings::$SALES_ORDER_TABLE_NAME);
$condition = array(DbStrings::$EMAIL => $email, DbStrings::$INVOICE => $invoice);
$this->db->where($condition);
$query = $this->db->get();
$checks = $query->result_array();
foreach ($checks as $queries) {
$productID = $queries[DbStrings::$PRODUCTID];
$quantity = $queries[DbStrings::$SALES_QUANTITY];
$amount = $queries[DbStrings::$SALES_AMOUNT];
$profit = $queries[DbStrings::$SALES_PROFIT];
$product_code = $queries[DbStrings::$PRODUCT_CODE];
$product_name = $queries[DbStrings::$PRODUCT_NAME];
$product_selling = $queries[DbStrings::$PRODUCT_SELLING];
$this->deductInventory($email, $product_code, $quantity);
$this->updateQuantitySold($email, $product_code, $quantity);
$cost_price = $this->product->getCostPrice($product_code);
$data[] = array(
DbStrings::$EMAIL => $email,
DbStrings::$INVOICE => $invoice,
DbStrings::$PRODUCTID => $productID,
DbStrings::$SALES_QUANTITY => $quantity,
DbStrings::$SALES_AMOUNT => $amount,
DbStrings::$SALES_PROFIT => $profit,
DbStrings::$PRODUCT_CODE => $product_code,
DbStrings::$PRODUCT_NAME => $product_name,
DbStrings::$PRODUCT_CP => $cost_price,
DbStrings::$PRODUCT_SP => $product_selling,
DbStrings::$PAYMENT_TYPE => $payment_type,
DbStrings::$CASH_TENDERED => $cash_tendered,
DbStrings::$DATE_CREATED => time()
);
$inserted = $this->db->insert_batch(DbStrings::$DAILYSALES_TABLE_NAME, $data);
}
return $inserted;
}
With the above, i get flagged this error:
There was a problem inserting your sale. Please try again.
Please I need help on this.
The error came from my database structure. Being an internal server error, it came from the DB.
I realized i deleted a column from my database table, and i was still sending data to the removed column.
Thanks guys for the attempt to help.
I am using ajax to get texts from an input field and check them through php than store them in the database...But somewhere on the line, something is wrong and I am getting Unexpected token s in JSON at position 0 this error...
$(".d-f-sub").on('click',function(e){
e.preventDefault();
resetErrors();
$('.inputTxtError').children('form input').css({'border-color' : '','box-shadow' : ''});
var data = {};
$.each($('form input, form select'), function(i, v) {
if (v.type !== 'submit') {
data[v.name] = v.value;
}
});
$.ajax({
dataType: "JSON",
type: "POST",
data: data,
cache: false,
url: "/ajax/diet/diet-page-error-display.php",
success: function(result){
if(result === "true"){
console.log('raboti do tuk');
$(".d-f-sub").submit();
window.location = "http://www.homepage.co.uk/thankyou";
return false;
}else {
console.log('ne raboti');
$.each(result, function(i, v) {
//console.log(i + " => " + v); // view in console for error messages
var msg = '<label class="diet-error" for="'+i+'" style="background:red;">'+v+'</label>';
$('input[name="' + i + '"], select[name="' + i + '"]').css({'border-color' : '#cc0000','box-shadow' : '0 0 10px #cc0000'}).closest('div').addClass('inputTxtError').after(msg);
});
var keys = Object.keys(result);
$('input[name="'+keys[0]+'"]').focus();
}
return false;
},
error: function(jqXHR, textStatus, errorThrown) {
//console.log(JSON.stringify(result));
alert(jqXHR.status);
alert(textStatus);
alert(errorThrown);
}
});
function resetErrors() {
$('form input, form select').removeClass('inputTxtError');
$('label.diet-error').remove();
}
});
<?php
header('Content-type:application/json;charset=utf-8');
if(isset($_POST)){
if (filter_var($_POST['age'], FILTER_VALIDATE_INT) === false){
$_SESSION['errors']['age'] = 'Моля използвайте само цифри в полето за Вашата възраст!';
}
if (filter_var($_POST['height'], FILTER_VALIDATE_INT) === false){
$_SESSION['errors']['height'] = 'Моля използвайте само цифри в полето за Вашата височина!';
}
if (filter_var($_POST['weight'], FILTER_VALIDATE_INT) === false){
$_SESSION['errors']['weight'] = 'Моля използвайте само цифри в полето за Вашато тегло!';
}
if (filter_var($_POST['budget'], FILTER_VALIDATE_INT) === false){
$_SESSION['errors']['budget'] = 'Моля използвайте само цифри в полето за Вашият бюджет!';
}
if (filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) === false){
$_SESSION['errors']['email'] = 'Моля въведете валиден имейл адрес!';
}
if(empty($_POST['email'])){
$_SESSION['errors']['email'] = 'Моля въведете имейл за връзка';
}
if(empty($_POST['age'])){
$_SESSION['errors']['age'] = 'Моля въведете Вашата възраст!';
}
if(empty($_POST['height'])){
$_SESSION['errors']['height'] = 'Моля въведете Вашата височина!';
}
if(empty($_POST['weight'])){
$_SESSION['errors']['weight'] = 'Моля въведете Вашето тегло!';
}
if(!isset($_POST['sex'])){
$_SESSION['errors']['sex'] = 'Моля изберете пол !';
}
if(!isset($_POST['activity'])){
$_SESSION['errors']['activity'] = 'Моля изберете активност! !';
}
if(!isset($_POST['goal'])){
$_SESSION['errors']['goal'] = 'Моля изберете цел !';
}
}//
if(count($_SESSION['errors']) > 0){
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
echo json_encode($_SESSION['errors']);
unset($_SESSION['errors']);
exit();
}
echo "<ul>";
foreach($_SESSION['errors'] as $key => $value){
echo "<li>" . $value . "</li>";
}
echo "</ul>";
unset($_SESSION['errors']);
exit();
}else{
$age = clean_xss_int($_POST['age']);
$height = clean_xss_int($_POST['height']);
$weight = clean_xss_int($_POST['weight']);
$email = clean_xss($_POST['email']);
$sex = clean_xss($_POST['sex']);
$activity = clean_xss($_POST['activity']);
$goal = clean_xss($_POST['goal']);
$diseases = clean_xss($_POST['diseases']);
$liked_foods = clean_xss($_POST['liked_foods']);
$hated_foods = clean_xss($_POST['hated_foods']);
$budget = clean_xss_int($_POST['budget']);
$intership = clean_xss($_POST['training']);
$description = clean_xss($_POST['eat_usually']);
$data = array(
'age' => $age,
'height' => $height,
'weight' => $weight,
'email' => $email,
'sex' => $sex,
'activity' => $activity,
'goal' => $goal,
'diseases' => $diseases,
'liked_foods' => $liked_foods,
'hated_foods' => $hated_foods,
'budget' => $budget,
'intership' => $intership,
'description' =>$description
);
//Here is the query usually
echo json_encode($data);
?>
No matter what I do it's always returning Unexpected token s in JSON at position 0.For now i have tried to remove DataType: "JSON" used Content-Type header, use json_encode() (there is the result from JSON encode)
Link to network response tab
Also tried utf8_encode() before json,but it require a string not array.
Thank you!
OK so i was on this error whole day, there is the solution which worked for me.
First i checked if JSON is valid in www.jsonlint.com and it was valid.
Second my clean_xss_int function was wrong, i was imploding the input value if it is array, so the end result was strings for number fields and arrays for text fields.
Third (because i am new to ajax) I checked the whole php side, and realized that even if there is empty field a.k.a must return error or return the data array ajax got it both for successful operation.Plus that there is no need to pass the $data array to json again,because i need it only for the insert query. So i wrote array which i am returning as success in ajax which is array('0' => 'true'); And i am making it string in ajax and checking if success is equal to string 'true'.There is how code looks like:
$.ajax({
type: "POST",
data: data,
dataType: "JSON",
url: "/ajax/diet/diet-page-error-display.php",
success: function(result){
JSON.stringify(result);// <---- new ;d
if(result == "true"){ <--- comparing with 2 x = instead of 3
$(".d-f-sub").submit();
window.location = "http://www.musclevale.com/diet";
return false;
}else {
$.each(result, function(i, v) {
var msg = '<label class="diet-error" for="'+i+'" style="background:red;">'+v+'</label>';
$('input[name="' + i + '"], select[name="' + i + '"]').css({'border-color' : '#cc0000','box-shadow' : '0 0 10px #cc0000'}).closest('div').addClass('inputTxtError').after(msg);
});
var keys = Object.keys(result);
$('input[name="'+keys[0]+'"]').focus();
}
return false;
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
alert(textStatus);
alert(errorThrown);
}
});
<?php
$age = clean_xss_int($_POST['age']);
$height = clean_xss_int($_POST['height']);
$weight = clean_xss_int($_POST['weight']);
$email = clean_xss($_POST['email']);
$sex = clean_xss($_POST['sex']);
$activity = clean_xss($_POST['activity']);
$goal = clean_xss($_POST['goal']);
$diseases = clean_xss($_POST['diseases']);
$liked_foods = clean_xss($_POST['liked_foods']);
$hated_foods = clean_xss($_POST['hated_foods']);
$budget = clean_xss_int($_POST['budget']);
$intership = clean_xss($_POST['training']);
$description = clean_xss($_POST['eat_usually']);
$data = array(
'age' => $age,
'height' => $height,
'weight' => $weight,
'email' => $email,
'sex' => $sex,
'activity' => $activity,
'goal' => $goal,
'diseases' => $diseases,
'liked_foods' => $liked_foods,
'hated_foods' => $hated_foods,
'budget' => $budget,
'intership' => $intership,
'description' =>$description
);
$fields = implode(',',array_keys($data));
$values = '\'' . implode('\', \'', $data) . '\'';
$query = mysqli_query($connect,"INSERT INTO buyed_diets ($fields) VALUES ($values)");
echo json_encode(array('0' => 'true'));// <----new ;d
?>
I have this ajax request that iterates through a store and deletes all selected records.
code
Ext.Ajax.request({
url: 'system/index.php',
method: 'POST',
params: {
class: 'LicenseFeatures',
method: 'delete',
data: Ext.encode({
feature_id: ( function(){
var e = "";
var sel = Ext.getCmp('featureGrid').getSelection();
var c = 0;
for( var i in sel ) {
var x = ( c == 0 ) ? e = sel[i].data.feature_id : e += "," + sel[i].data.feature_id;
c++;
}
return e;
})()
})
},
success: function( response ){
Ext.MessageBox.alert( 'Status', 'Record(s) has been deleted.' );
Ext.getStore('LicenseFeaturesStore').reload();
},
failure: function(){
Ext.MessageBox.alert( 'Status', 'Failed to delete records.' );
}
});
Currently the code retrieves 1 id from the grid and deletes it. What I need to do is get two Id's from the grid as I need to run a specific sql to the database. The sql needs two inputs, here is the sql
public function delete( $vars ){
$sql = "DELETE FROM `LicenseFeatures` WHERE feature_id in({$vars->data->feature_id}) AND license_id in({$vars->data->license_id})";
if( $result = $vars->db->query( $sql ) ) {
echo json_encode( array( "success" => true,"sql"=>$sql ) );
} else {
echo json_encode( array( "success" => false ) );
}
}
Try and change the data property to this.
data: Ext.encode(( function(){
var feature_id,
licence_id;
var sel = Ext.getCmp('featureGrid').getSelection();
var c = 0;
for( var i in sel ) {
if (c == 0) {
feature_id = sel[i].data.feature_id;
licence_id = sel[i].data.licence_id;
} else {
feature_id += "," + sel[i].data.feature_id;
licence_id += "," + sel[i].data.licence_id;
}
c++;
}
return {
feature_id: feature_id,
licence_id: licence_id
};
})())
Ok, this has been driving me crazy for the past couple of days.
I have a form:
echo $this->Form->create(FALSE, array('id' => 'AdminGeneralReport', 'class' => 'ReportForm'));
echo '<div class="row">';
echo $this->Form->input('ReportCenter', array(
'type'=>'select', 'div' => 'form-group',
'options' => $centers,
'label' => 'المركز',
'class' => 'form-control report-center',
'selected' => isset($selections['CenterID'])? $selections['CenterID']['value'] : 'default'
));
echo $this->Form->input('ReportYears', array(
'type'=>'select', 'div' => 'form-group',
'options' => $years,
'label' => 'العام الدراسي',
'class' => 'form-control report-year',
'selected' => isset($selections['YearID'])? $selections['YearID']['value'] : 'default'
));
echo $this->Form->end();
Submit jQuery:
$('.ReportForm').off('submit').on('submit', function(e){
e.preventDefault();
var formID = $(this).attr('id');
var data = JSON.stringify($(this).serializeObject());
var url = base_url + "Reports/" + formID;
var targetSelector = $(this).attr('data-target') || '.results-row';
var $target = $(targetSelector);
// Show app loading
$('#AppLoading').show();
$.ajax({
url : url,
type : 'POST',
ContentType : 'application/json',
data : {'data': data}
}).done(function(response){
try{
response = JSON.parse($response);
if(response.status == 'success'){
$target.html(response.html);
}
else{
$('#AppWell').show('slow').children('p').html(response.msg);
}
}
catch (ex) {
var msg = 'عذراً، حدث خطأ في إنشاء التقرير. برجاء المحاولة لاحقاً';
$('#AppWell').show('slow').children('p').html(msg);
console.log('Exception :: ' + ex.toString());
console.log('Response :: ' + response);
}
}).fail(function(request, status, error){
var msg = 'عذراً، حدث خطأ في إنشاء التقرير. برجاء المحاولة لاحقاً';
$('#AppWell').show('slow').children('p').html(msg);
console.log('XXXXX Ajax Failure :: ' + error);
}).always(function(){
// Hide app loading
$('#AppLoading').hide();
});
});
Question/Need: I want to load another view and append it after this form using json or whatever the way it's possible.
This is part of the view I want to load:
<?php if(isset($selections['Filtered']) && $selections['Filtered'] == TRUE ){
echo '<div class="row">';
$Report = '';
if(isset($selections['SexID']) && $selections['SexID']['value'] != 'default'){
$Report .= '<div class="report-info">
<p class="title">الجنس</p>
<p class="value">'.$selections['SexID']['text'].'</p>
</div>';
}
if(isset($selections['GovID']) && $selections['GovID']['value'] != 'default'){
$Report .= '<div class="report-info">
<p class="title">المحافظة</p>
<p class="value">'.$selections['GovID']['text'].'</p>
</div>';
}
echo '</div>';
?>
<div class="cur-report custom-inverse">
<?=$Report;?>
</div>
And this is part of the PHP code:
// This is the function the ajax calls
public function AdminGeneralReport()
{
// Enable automatic view class switching on content types
public $components = array('RequestHandler');
// Disable auto rendering
$this->autoRender = false;
// Create new view to return to ajax request
$view = new View($this, false);
// Define selections array
$selections = array();
// Get AJAX data
$postData = $this->request->data;
// Decode post data to JSON object
$data = json_decode($postData);
// Create response object
$response = new stdClass();
$response->status = 'fail'; // Should be changed by success scenario
// ********* Center Condition ********* //
$centerCond = '';
// Check if Center is set
if($data->ReportCenter != 'default'){
$centerID = $data->ReportCenter;
$selections['CenterID']['value'] = $centerID;
$selections['CenterID']['text'] = $centers[$centerID];
$selections['Filtered'] = TRUE;
$centerCond = array('CenterID' => $centerID);
}
// *********************************************** //
// ********* Year Condition ********* //
$yearCond = '';
// Check if Academic Year is set
if($data->ReportYears != 'default'){
$yearID = $data->ReportYears;
$selections['YearID']['value'] = $yearID;
$selections['YearID']['text'] = $years[$yearID];
$selections['Filtered'] = TRUE;
$yearCond = array('YearID' => $yearID);
$allTerms = $this->Term->find('all', array('conditions' => array('YearID' => $yearID),
'fields' => array('ID', 'TermName')));
// Convert results from 3D array to 1D array
for($i = 0; $i < count($allTerms); $i++){
$terms[$allTerms[$i]['Term']['ID']] = $allTerms[$i]['Term']['TermName'];
}
$terms['default'] = 'الكل';
}
// *********************************************** //
if($selections){
$response->status = 'success';
}
else{
$response->msg = 'لا توجد بيانات لهذه الإختيارات';
}
$view->set(compact('results','selections'));
$view->set('_serialize', array('results', 'selections'));
$html = $view->render('Admin/General', FALSE);
$response->html = $html;
echo json_encode($response);
die();
}
NOTE: I have this configured in Config/router.php
/**
* Enable extensions routing for data views
*/
Router::parseExtensions('json');
FINALLY SOLVED!!!
I was confusing my self by trying to make it a data view json/xml... while all i needed to do was formatting the returned view:
The returned view has a lot of "\r\n\'\""...all the escape sequences that fail to be JSON parsed in jQuery code.
and i don't have to include the Router::parseExtensions('json'); as well as the public $components = array('RequestHandler');
So this is the PHP Code:
$results = array(); // Fill it
$selections = array(); // Fill it
...
// Disable auto rendering
$this->autoRender = false;
// Create new view to return to ajax request
$view = new View($this, false);
$view->set(compact('results','selections'));
$view->set('_serialize', array('results', 'selections'));
$html = stripcslashes( stripslashes( $view->render('Admin/General', FALSE) ) );
$response->html = $html;
echo json_encode($response);
die();
NOTE: stripcslashes() removes the "\r\n" escape sequences, while stripslashes will remove "\'\"" escape sequences
The jQuery Code:
$.ajax({
url : url,
type : 'POST',
ContentType : 'application/json',
data : {'data': data}
}).done(function(response){
try{
response = JSON.parse(response);
if(response.status == 'success'){
$target.html(response.html);
}
else{
// ERROR HANDLING
}
}
catch (ex) {
// ERROR HANDLING
console.log('Exception :: ' + ex.toString());
console.log('Response :: ' + response);
}
}).fail(function(request, status, error){
// ERROR HANDLING
console.log('XXXXX Ajax Failure :: ' + error);
}).always(function(){
// Hide loading
});