Ajax script not working - php

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

Related

Saving an ajax datatable back to the database with 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');
});

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.

Pagination algorithm with javascript

I have a javascript function which makes an ajax request to php controller method which returns a JSON encoded array.
function initGallery(offset) {
if(offset === undefined)
{
var request_url = url+'avatar/gallery';
} else {
var request_url = url+'avatar/gallery/'+offset;
}
$('#avatar_gallery').html('')
$.get(request_url,function(data) {
var dat = jQuery.parseJSON(data);
//Build gallery
$('#avatar_gallery').html('<div class="gallery_box"></div>');
$('.gallery_box').append('<div class="gallery_header">Your Avatar Gallery</div>');
$('.gallery_box').append('<div class="gallery_container"></div>');
$.each(dat.avatars,function(index,item)
{
$('.gallery_container').append(
'<div class="gallery_item">'+
'<img src="'+item.avatar_src+'" id="'+item.avatar_id+'" onclick="avatar.view_avatar(this.id)"/>'+
'</div>'
);
});
$('.gallery_box').append('<div class="gallery_footer"></div>');
$('.gallery_footer').html('<div class="gallery_pagination"><div>');
});
}
And this is my controller method
function gallery($offset= 0)
{
$limit = 12;
$user_id = $this->session->userdata('user_id');
$data = $this->avatar_model->user_avatars($user_id,$limit,$offset);
$avatars = array();
$count = $this->avatar_model->count_user_avatars($user_id);
$pages = ceil($count/$limit);
foreach($data as $key => $avatar)
{
$dat['avatar_id'] = $avatar->avatar_id;
$dat['avatar_src'] = $avatar->avatar_small;
$dat['create_date'] = time("d-m-Y",$avatar->create_date);
$avatars[] = $dat;
}
$server_response['avatar_count'] = $count;
$server_response['avatars'] = $avatars;
echo json_encode($server_response);
}
I dont really have an idea on how to paginate the data returned from the reques.
Please point me in the right direction
It's easy. Add a class to your pagination link (you can use full_tag_open and full_tag_close config variable: <p class="pagination> and </p>).
After that you can redefine the .pagination a click event (I'm using JQuery):
function () {
$(".pagination a").click(function(event){
event.preventDefault();
YourJSFunction($(this).attr("href"));
});
}
I hope this helps you.

Categories