Saving an ajax datatable back to the database with php - php

So I'm working with datatables and where I can edit the values in the datatables. I ran into a problem with actually saving the changes, at first this method worked but when I came back the next day it just didn't want to work anymore.
Is there anything obvious I'm missing here? Or is there something more to the story?
Server side code:
case 'form_save': {
$form_id = !empty($post['form_id']) ? $post['form_id'] : false;
$data = array();
$where = array('id'=>$this->db->escape($post['id']));
if(!empty($form_id)) {
switch($form_id) {
case 'translations': {
$data['value'] = $this->db->escape($post['value']);
$rc['success'] = $this->db->update('translations',$data,$where);
break;
}
case 'carousel': {
$data['title'] = $this->db->escape($post['title']);
$data['src'] = $this->db->escape($post['src']);
$data['alt'] = $this->db->escape($post['alt']);
$data['slide_url'] = $this->db->escape($post['slide_url']);
$data['slide_order'] = $this->db->escape($post['slide_order']);
$rc['success'] = $this->db->update('carousel',$data,$where);
break;
}
}
}
JQuery code:
$(document).on('submit','form',function(){
var $form = $(this);
var $error = $form.find('div.error');
var form_id = $form.attr('id');
var $modal = $(document).find('.modal');
var data = $form.serializeArray();
data.form_id = form_id;
data.type = 'form_save';
$.post('/admin_get/',data,function(rc){
if(rc.success) {
$modal.modal('hide');
$modal.find('modal-title').html('');
$modal.find('modal-body').html('');
} else {
$error.html(rc.error).show();
$error.html('').hide();
}
},'json');
});
});
EDIT: forgot to add the edit form jquery side :
$(document).on("click", ".edit", function(){
var id = $(this).data('id');
var table = $(this).closest('table').attr('id');
var $modal = $(document).find('.modal');
$.post('/admin_get/', {id:id, type:'get_form', table:table}, function(data){
$modal.find('.modal-title').html(data.title);
$modal.find('.modal-body').html(data.html);
$modal.find('.modal-body').find('#summernote').summernote();
$modal.find('.modal-body').find('.select2').select2();
$modal.modal('show');
},'json');
});

Related

Ajax response return undefined

Hi I have been using ajax for many times. But I can't figure out whats the problem with my code this time. My head is blowing up since 2 days. I am using pusher for the realtime notification in CodeIgniter. Here's my code.
$(document).on("click", ".myonoffswitch", function () {
if (confirm("Sure!!! You want to Change the post status?"))
{
var thiss = $(this);
var prod_id = $(this).attr('id');
var status = $(this).attr('value');
var tdid = $(this).parent().prev().attr('class');
var td = $(this).parent().prev();
var adsstatus = $.ajax({type: "POST", dataType: "json", url: base_url + 'init/ads_status', data: {'prod_id': prod_id, 'status': status}});
$.when(adsstatus).done(function (adsstatuss) {
var msg;
msg = adsstatuss;
alert(msg.length);
var updated_status = msg[0].post_status;
alert(updated_status);
//alert(updated_status);
if (updated_status == "0" && tdid == prod_id) {
td.css("background", "#ccffcc");
td.text("On");
thiss.val(updated_status);
}
if (updated_status == "1" && tdid == prod_id) {
td.css("background", "#ffcccc");
td.text("Off");
thiss.val(updated_status);
}
});
}
});
ads_status (method in CodeIgniter)
public function ads_status() {
$prod_id = $_POST['prod_id'];
$status = $_POST['status'];
if ($status == "1") {
$new_status = "0";
$this->cmsdbmodel->ads_status($prod_id, $new_status);
$dat = $this->cmsdbmodel->get_updated_status($prod_id);
$ads_type = "product";
$emailreturn = $this->send_email_ads_status($prod_id, $ads_type);
//send user alert of product//
if ($dat[0]->post_status == "0") {
$lastInsertedId = $prod_id;
$modelNBrandId = $this->dbmodel->checkProductContainsAlert($lastInsertedId);
$getAlertEmail = $this->dbmodel->getAlertEmailFromBrandNModelId($modelNBrandId);
if (!empty($getAlertEmail)) {
foreach ($getAlertEmail as $alerts) {
$alertsEmail = $alerts->email;
}
}
$alertsPost = $this->dbmodel->getPostAlerts($lastInsertedId);
$sendPostAlerts = json_encode($alertsPost);
$encrytpEmail = hash('sha256', $alertsEmail);
$this->pusher->trigger($encrytpEmail, 'alerts', $sendPostAlerts);
}
//send user alert of product//
$realtime = $this->realTime_charts();
$realtime["post_status"] = $dat[0]->post_status;
$realtime["emailres"] = $emailreturn;
$data = $realtime;
$this->pusher->trigger('recent_activity', 'new_event1', $data);
echo json_encode($data);
}
}
Here I want to trigger event in pusher as well as echo json object. But in ajax, response is undefined. Also in console I can see json but when alerting the reponse it says undefined. Wheres problem in my code. Please help me.

saving data from csv to php and mysql

I am trying to import all the data from csv to the database.
Below code is ajax request that is sent to a php file.
$('#upload_location_csv').click(function(e){
e.preventDefault();
var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]});
fi = document.getElementById("csv_file_input").files[0];
reader = new FileReader;
reader.onload = function(){
csv_data = reader.result;
$.ajax({
type:"post",
url:ajax_root_path+'fend.php',
data:{
location_id:queryDict['id'],
csv_data:csv_data,
perform_action:"save_delivery_csv_data"
},
success:function(resObj){
window.location.reload();
},
error:function(resObj){
}
});
};
reader.readAsText(fi);
});
This is the action that is performed, where here is, save_delivery_csv_data .
When I click on import csv, the page reloads and no request is sent to fend.php.
case 'save_delivery_csv_data':
{
$location_id = $param_array['location_id'];
$csv_data = $param_array['csv_data'];
$csv_data_rows = explode("\n",$csv_data);
unset($csv_data_rows[0]);
$csv_data_rows = array_values($csv_data_rows);
debug($csv_data_rows);
$csv_data_array = array();
foreach ($csv_data_rows as $csv_row_key => $csv_row_value)
{
$csv_row_value_array = explode(",",$csv_row_value);
debug($csv_row_value_array);
if(count($csv_row_value_array) == 5)
{
/*$csv_data_array[$csv_row_key] = array();
$csv_data_array[$csv_row_key]['locality_id'] = $csv_row_value_array[0];
$csv_data_array[$csv_row_key]['locality_name'] = $csv_row_value_array[1];
$csv_data_array[$csv_row_key]['minimum_order_amount'] = $csv_row_value_array[2];
$csv_data_array[$csv_row_key]['delivery_time'] = $csv_row_value_array[3];
$csv_data_array[$csv_row_key]['delivery_charge'] = $csv_row_value_array[4];*/
//debug($csv_row_value_array);
if(isset_empty($csv_row_value_array[3]))
{
//debug($csv_row_value_array);
$locality_id = $csv_row_value_array[0];
$location_outletValues = array();
$location_outletValues['cloud_site_id'] = $cloud_site_id;
$location_outletValues['location_id'] = $location_id;
$location_outletValues['locality_id'] = $locality_id;
$location_outletValues['minimum_order'] = $csv_row_value_array[2];
$location_outletValues['delivery_time'] = $csv_row_value_array[3];
$location_outletValues['delivery_charge'] = $csv_row_value_array[4];
$sql = "SELECT outlet_locality_id FROM ".PLATFORM_OUTLET_LOCALITIES."
WHERE location_id='".$location_id."' AND locality_id='".$locality_id."'";
$outlet_locality_array = $DB->query($sql);
//debug($outlet_locality_array);
if(count($outlet_locality_array) > 0)
{
$condition_array = array();
$condition_array['outlet_locality_id'] = $outlet_locality_array[0]->outlet_locality_id;
//debug($condition_array);
debug($location_outletValues);
$DB->update(PLATFORM_OUTLET_LOCALITIES,$location_outletValues,$condition_array);
}
else
{
$DB->insert(PLATFORM_OUTLET_LOCALITIES,$location_outletValues);
}
}
}
}
break;
//debug($csv_data_array);
}
What am I missing out here?? I also tried debugging variables values, but no request was sent to fend.php, whereas other request on the same page are being successfully sent.

YUI-2 Datatable : Dynamic column definition with Server side AJAX pagination sorting

I am using the below code to create a YUI datatable with dynamic data(columns). But am facing a issue in server side pagination. As of now it is working fine with client side pagination, but I need server side pagination, so that my page loading time will get reduced. Can you help me on this to fix the issue. Since I'm struggling in this area for past 2 days.Server side pagination with AJAX to render the data is my expectation.
Here is the code I Used
DataProvider.prototype = {
url:null,
data:null,
ds:null,
getData:function() {return this.data},
initialize:function(){
var str = generateRequest();
var newUrl = this.url+str;
YAHOO.util.Connect.asyncRequest('GET', newUrl, this);
},
success:function(response){
var responseVal = YAHOO.lang.JSON.parse(response.responseText);
var columnList = responseVal.columnList;
var sortedBy = responseVal.sortedBy;
this.data = responseVal.results;
if(this.data == '') {
$('#dynamicdata').html('<font style="color:red;"> No Data Found!</font>');
} else {
this.ds = new YAHOO.util.FunctionDataSource(function(){return this.dataProvider.getData()});
this.ds.responseSchema = {
resultsList:"results",
fields:columnList,
// Access to values in the server response
metaFields: {
totalRecords: "totalRecords",
startIndex: "startIndex"
}
}
this.ds.dataProvider = this;
// DataTable configuration
var myConfigs = {
paginator: new YAHOO.widget.Paginator({ rowsPerPage:20 }), // Enables pagination
width:"80%", height:"auto"
};
// FORMATTING CELL COLOUR BASED ON THEIR VALUES
var myCustomFormatter = function(elLiner, oRecord, oColumn, oData) {
var columnKey = oColumn.getKey();
var frmCurrentPeroid = $('#from').val();
//var frmCurrentPeroid = '2013-03-13';
var defaultLabels = ['Product type','Total 1','Total 2','Change'];
if (isDate(columnKey) && $.inArray(columnKey, defaultLabels) === -1) {
if(columnKey < frmCurrentPeroid) {
YAHOO.util.Dom.addClass(elLiner.parentNode,'orange');
elLiner.innerHTML = oData;
//alert('blue');
} else {
YAHOO.util.Dom.addClass(elLiner.parentNode,'blue');
elLiner.innerHTML = oData;
}
} else {
if(columnKey == 'Total 1') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'orange');
elLiner.innerHTML = oData;
//alert('blue');
}
else if(columnKey == 'Total 2') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'blue');
elLiner.innerHTML = oData;
//alert('blue');
}
else if(columnKey == 'Change') {
split_data = oData.toString().split('_');
var fieldData = null;
var fieldFormatter = null;
fieldData = split_data[0];
fieldFormatter = split_data[1];
if(fieldFormatter == 'green') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'green');
elLiner.innerHTML = fieldData;
}
if(fieldFormatter == 'red') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'red');
elLiner.innerHTML = fieldData;
}
}
else if(columnKey == 'Product Name') {
var filterStr = oData.substring(0,30);
elLiner.innerHTML = ''+filterStr+'';
//alert('blue');
}
else {
elLiner.innerHTML = oData;
}
}
};
// Add the custom formatter to the shortcuts
YAHOO.widget.DataTable.Formatter.myCustom = myCustomFormatter;
//YAHOO.widget.DataTable.formatLink = formatLink;
/* make call to initialize your table using the data set */
var myDataTable = new YAHOO.widget.DataTable("dynamicdata", columnList, this.ds, myConfigs);
}
}
}
Followed the code posted in this page
Click here
Thanks in Advance,
Raja
I haven't been doing YUI2 for quite some time so I am no longer able to help you directly. Perhaps this example can help: http://www.satyam.com.ar/yui/#ServerDriven . I do remember that there were big changes in 2.6 and this examples are marked 2.4, perhaps they no longer work.

Ajax script not working

I know I should be more specific about the problem but I don't know what it is but once I have an answer I fix the post.
Here is the problem simple ajax script but somehow it isn't working. I can't see any error on the code =/
jQuery part:
$(document).ready(function()
{
var addFavPhp = '../functions/addfav.php';
var orange = 'orange';
var favLinkError = false;
var favNameError = false;
$('#addFavButton').click(function()
{
var favLink = $('.favLinkInput').val();
var favName = $('.favNameInput').val();
var fileName = $('.file').val();
if(favLink=="")
{
$('.favLinkInput').css('border-color',orange);
favLinkError = true;
}
if(favName=="")
{
$('.favNameInput').css('border-color',orange);
favNameError = true;
}
if((favLinkError==false) && (favNameError==false))
{
$.post(addFavPhp,{favLink:favLink,favName:favName,fileName:fileName},function(addFav)
{
$('.favLinkInput,.favNameInput').val('').css('border-color','');
$('.file option[value=""]').attr("selected", "selected");
location.reload();
});
}
});
});
and php part:
<?php session_start();
include('../functions/connect.php');
if(!empty($_SESSION['username']))
{
$username = $_SESSION['username'];
}else
if(!empty($_COOKIE['PHPCOOKID']))
{
$cookie = htmlspecialchars(trim($_COOKIE['PHPCOOKID']));
$explode = explode('-', $cookie);
$username = $explode['0'];
}
$favLink = htmlspecialchars(trim($_POST['favLink']));
$favName = htmlspecialchars(trim($_POST['favName']));
$fileName = htmlspecialchars(trim($_POST['fileName']));
$d = array($username,$favLink,$favName,$fileName);
$req = $DB->prepare('INSERT INTO favs (username,favLink,favName,favFile) VALUE (? , ? , ? , ?)');
$req->execute($d);
?>
What I figure out is that it stop working around $.post but I can't figure out why. And it works find on local server.
Thanks for any help.
looks like the line var addFavPhp = '../functions/addfav.php'; is wrong. you have to use http urls when doing ajax. somthing like /path/to/addfav.php

delete link with js confirm + php

this was the delete link
<div class="artworkdelete">
Delete
</div>
apparently, when that link is clicked, the portal deletes the data automatically, i think it's an ajax thing because the page doesn't refresh. so i was ask to add a confirm pop up to ask the user to click yes or no if he wants to delete the data or not, and within the confirm box , it should mention the name of the data to be deleted like e.g
"are you sure you want to delete row_title ?"
here's the function of the deleteThisArtWork()
function deleteThisArtWork(artwork_id){
var artwork_id = artwork_id.split('_');
var cat_id=artwork_id[2];
artwork_id = artwork_id[1];
//$('#divStatus').html('processing request, please wait');
//$(".pleaseWait").dialog("open");
openLightBox();
$.ajax({
type: 'POST',
url: '<?php echo BASE_URL;?>ajax/ajax_methods_gallery.php',
data: 'deleteartwork=yes&artwork_id='+artwork_id+'&category_id='+cat_id,
success: function(msg){
//alert(msg);
msg = 'done';
var status=msg;
var deleted='';
if(status == 'done') {
var temp_lid = 'li_'+artwork_id+'_'+cat_id+'_';
//alert(counter);
for(var v=1;v<counter;v++){
var curid = tempIdArr[v];
curid = curid.split('#');
var curlid = curid[0];
if(temp_lid == curlid){
var del_aw_pos = curid[1];
break;
}
}
del_aw = temp_lid+'#'+del_aw_pos;
var i = 1;
var j =0;
var op = false;
var delpoint;
var endpoint;
var delcatid = '';
var artcounter = 0;
var artcounterArr = new Array();
$(".sortli").each(function (){
var atid = this.id.split('_');
//if(atid[2]!=cat_id)return;
if(this.id == del_aw){
deleted = 'yes';
delcatid = atid[2];
$(this).remove();
op = true;
i=i+1;
delpoint=i-1;
//alert('D'+delpoint);
//return;
}
if(atid[2]==cat_id){endpoint = i-1;artcounter=artcounter+1;}
else if(j==0 && artcounter > 0){
if(artcounter>0)artcounter = artcounter-1;
//else artcounterArr[j] = 0;
artcounterArr[j] = artcounter;
j=j+1;
artcounter = 0;
}
i = i + 1;
});
//alert(delpoint)
//alert(endpoint);
//alert(artcounterArr[0]);
if(op){
for(var k=delpoint; k<counter-1;k++){
var orderVal1 = tempOrderArr[k];
if(k<endpoint)document.getElementById('sortvalid_'+(k+1)).innerHTML = orderVal1;
document.getElementById('sortvalid_'+(k+1)).id = 'sortvalid_'+(k);
document.getElementById('sortdn_'+(k+1)).id = 'sortdn_'+(k);
document.getElementById('sortup_'+(k+1)).id = 'sortup_'+(k);
var t = tempIdArr[(k+1)].split('#');
t=t[0];
document.getElementById(tempIdArr[(k+1)]).id = t+'#'+k;
}
$(".rowHead").each(function (){
var taid = this.id;
var sp = this.id.split("^");
var a1 = sp[1];
//alert(a1);
//alert(cat_id);
if(parseInt(a1)>parseInt(cat_id)){
var a2 = sp[2];
var ta = 'lititle^'+a1+'^';
//alert(ta);
document.getElementById(taid).id = ta+(a2-1);
}
});
var a2temp;
var a1temp;
var delcat=null;
var rowHeadLast;
$(".rowHead").each(function (){
//var taid = this.id;
rowHeadLast = this;
var sp = this.id.split("^");
var a1 = sp[1];
var a2 = sp[2];
if(a2temp == a2 && delcat==null){delcat = a2temp; delcatid=a1temp;}
a2temp = a2;
a1temp = a1;
});
var delok = false;
$(".rowHead").each(function (){
//var taid = this.id;
//alert(deleted);
var sp = this.id.split("^");
var a1 = sp[1];
var a2 = sp[2];
if(delcat == a2 && a1==delcatid && deleted==''){delok= true;deleted='yes';$(this).remove();}
});
//alert(delcatid);
//if(!artcounterArr[0])alert('d');
if(!delok){
$(".rowHead").each(function (){
var sp = this.id.split("^");
var cid_t = sp[1];
if(!artcounterArr[0] && delcatid == cid_t)$(this).remove();
//else if(artcounterArr[0]<=0)$(this).remove();
});
}
if(deleted ==''){
$(rowHeadLast).remove();
}
}
setDivsInArray();
//$(".pleaseWait").dialog("close");
closeLightBox();
}
else if(status == 'DBDelete:error'){
//$('#row_'+artwork_id).fadeOut(3500);
$('#divStatus').fadeIn(500);
$('#divStatus').html('<b>Artwork Delete Error</b>');
$('#divStatus').fadeOut(4500);
}
}
});
}
it's quite long , I think I don't need all of those stuff if the requirement is just delete the data when "Yes" was clicked from the confirm pop up box
now here's the delete PHP function
function deleteArtWork($artwork_id,$category_id){
$artwork_cat_lookup_del = "delete from artwork_category_lookup where artwork_id = '$artwork_id' AND category_id='$category_id'";
if(mysql_query($artwork_cat_lookup_del)){
$userObj = new User();
$allArtWorkByCat = $userObj->allArtWorkByCat($category_id);
for($itr = 0; $itr<count($allArtWorkByCat); $itr++){
$ordr = $itr + 1;
$art_id = $allArtWorkByCat[$itr]['artwork_id'];
$updateSQL = "update artwork_category_lookup set artwork_display_order='$ordr' where artwork_id = '$art_id' AND category_id = '$category_id'";
mysql_query($updateSQL);
}
$action = $userObj->userActions('Artwork id: '.$artwork_id.' is deleted', 'Gallery');
$userObj->setActionintoDB($action);
echo 'done';
}
else echo 'DBDelete:error';
return;
I don't think that you want to start changing that code above as that is used to pass the relevant data to the php script via ajax.
What you need is a javascript prompt to intercept the link click and give the user an option to continue or cancel the deletion action. Is this correct?
http://www.tizag.com/javascriptT/javascriptconfirm.php
At the start of the "deleteThisArtWork" javascript function you need to display a prompt.
function deleteThisArtWork(artwork_id){
var answer = confirm("Are you sure you want to delete this record?");
if (answer){
//do the rest of the function as usual, i.e. delete row via ajax.
}else{
return false;
}
}
That should stop the user from accidentally deleting a record without at least having to accidentally click on a confirmation popup as well!
If you want to make the text in the confirm popup dynamic, you would need to either pass in the dynamic text as a variable to the "deleteThisArtwork" method or draw it from another element on the page using some javascript.

Categories