I am trying to upload image through ajax so as to see uploaded image in its specific block before save button in clicked. Searching net I found the following code and I tried it. It works fine but when I do upload the image isn't uploaded.
html
<form id="overflow_imgupload" method="post" enctype="multipart/form-data" action="">
<input type="hidden" name="position" value="" class="position"/>
<input type="file" name="imgupload" id="imgupload" value="Upload Image" class="span12"/>
<a id="btn_imgupload" onclick="return ajaxFileUpload();">Upload</a>
<a id="closeimg" >X</a>
</form>
">
function ajaxFileUpload(){
$("#loading")
.ajaxStart(function(){
$(this).show();
})
.ajaxComplete(function(){
$(this).hide();
});
$.ajaxFileUpload({
url:'<?php echo site_url('doajaxfileupload') ?>',
secureuri:false,
fileElementId:'imgupload',
dataType: 'html',
success: function (data, status){
console.log(data);
if(typeof(data.error) != 'undefined'){
if(data.error != ''){
alert(data.error);
}else{
alert(data.msg);
}
}
},
error: function (data, status, e){
alert(e);
}
})
return false;
}
in doajaxfileupload.php
<?php
class Doajaxfileupload extends CI_Controller{
function __construct() {
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
//$this->load->library('upload');
}
function index(){
$error = "";
$msg = "";
$fileElementName = 'imgupload';
if(!empty($_FILES[$fileElementName]['error']))
{
switch($_FILES[$fileElementName]['error'])
{
case '1':
$error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
break;
case '2':
$error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
break;
case '3':
$error = 'The uploaded file was only partially uploaded';
break;
case '4':
$error = 'No file was uploaded.';
break;
case '6':
$error = 'Missing a temporary folder';
break;
case '7':
$error = 'Failed to write file to disk';
break;
case '8':
$error = 'File upload stopped by extension';
break;
case '999':
default:
$error = 'No error code avaiable';
}
}elseif(empty($_FILES[$fileElementName]['tmp_name']) || $_FILES[$fileElementName]['tmp_name'] == 'none')
{
$error = 'No file was uploaded..';
}else
{ //$msg .= $_FILES[$fileElementName]['name'];
$config['allowed_types'] = 'jpg|png|jpeg|bmp|gif';
$config['upload_path'] = './uploaded_files/';
$config['max_width'] = '720';
$config['max_height'] = '240';
$config['min_width'] = '325';
$config['min_height'] = '240';
$this->load->library('upload',$config);
if ($this->upload->do_upload($_FILES[$fileElementName]['name'])) {
$msg .= "Upload success!";
} else {
$msg .= "UPoloadfailes";
}
}
echo "{";
echo "error: '" . $error . "',\n";
echo "msg: '" . $msg . "'\n";
echo "}";
}
}
?>
every time it alerts UPoloadfailes.why??
any help/suggestion is welcome.thanks in advance.
I don't know why but when i use move_uploaded_file it works.
In doajaxfileupload.php else portion
$extension = end(explode('.', $_FILES[$fileElementName]['name']));
$uploaddir = './uploaded_files/temp/';
$file = $uploaddir .'default_'.rand(1,999).'_'.time().'.'.$extension;
if (move_uploaded_file($_FILES[$fileElementName]['tmp_name'], $file)) {
$msg .= $this->input->post('position').','.$file;
} else {
$msg .= "error";
}
Can anyone suggest me why CI upload didn't work and why this PHP move_uploaded_file worked ??
Related
I am new to CodeIgniter and I have been struggling with this error for the past 3 hours.
Call to undefined method Product_filter_model::fetch_data() error in the following code.
You can view the error in Inspect > Network Tab at the following link:
http://admin.millionkidstoschool.org/index.php/product_filter
I have confirmed the names of the model, controller, and functions. I have also tried putting $this->load->model('product_filter_model'); inside the function fetch_data() and it did not help.
Controller
class Product_filter extends CI_Controller{
public function __construct()
{
parent::__construct();
$this->load->model('product_filter_model');
$this->load->helper('url');
}
function fetch_data(){
$minimum_price = $this->input->post('minimum_price');
$maximum_price = $this->input->post('maximum_price');
$brand = $this->input->post('brand');
$ram = $this->input->post('ram');
$storage = $this->input->post('storage');
$output = array(
/*'pagination_link' => $this->pagination->create_links(),*/
'product_list' => $this->product_filter_model->fetch_data($minimum_price, $maximum_price, $brand, $ram, $storage)
);
echo json_encode($output);
}
View
$(document).ready(function(){
filter_data();
function filter_data(){
$('#filter_data').html("<div id='loading'></div>");
var action = 'fetch_data';
var minimum_price = $('#hidden_minimum_price').val();
var maximum_price = $('#hidden_maximum_price').val();
var brand = get_filter('brand');
var ram = get_filter('ram');
var storage = get_filter('storage');
$.ajax({
url:"<?php echo base_url(); ?>index.php/product_filter/fetch_data",
method:"POST",
dataType:"JSON",
data:{action:action, minimum_price:minimum_price,maximum_price:maximum_price, brand:brand, ram:ram, storage:storage},
success:function(data){
$('.filter_data').html(data.product_list);
/*$('#pagination_link').html(data.pagination_link);*/
}
})
}
}
Model
function fetch_data($minimum_price, $maximum_price, $brand, $ram, $storage)
{
$query = $this->make_query($minimum_price, $maximum_price, $brand, $ram, $storage);
/*$query .= ' LIMIT '.$start.', ' . $limit;*/
$data = $this->db->query($query);
$output = '';
if($data->num_rows() > 0)
{
foreach($data->result_array() as $row)
{
$output .= '
some data
';
}
}
else
{
$output = '<h3>No Data Found</h3>';
}
return $output;
}
Thank you for your time.
UPDATE:
I copied both the model methods' code in controller function where ajax request is posted. It worked. But I am unable to understand why the Controller function is unable to access Model Methods?
public function fetch_data(){
$this->load->model('product_filter_model');
$minimum_price = $this->input->post('minimum_price');
$maximum_price = $this->input->post('maximum_price');
$brand = $this->input->post('brand');
$ram = $this->input->post('ram');
$storage = $this->input->post('storage');
//$output = array(
/*'pagination_link' => $this->pagination->create_links(),*/
// 'product_list' => $this->product_filter_model->fetch_data//($minimum_price, $maximum_price, $brand, $ram, $storage)
//);
/*$query = $this->product_filter_model->make_query($minimum_price, $maximum_price, $brand, $ram, $storage);*/
/*$query .= ' LIMIT '.$start.', ' . $limit;*/
$query = "
SELECT * FROM product
WHERE product_status = '1'
";
if(isset($minimum_price, $maximum_price) && !empty($minimum_price) && !empty($maximum_price))
{
$query .= "
AND product_price BETWEEN '".$minimum_price."' AND '".$maximum_price."'
";
}
if(isset($brand)){
$brand_filter = implode("','", $brand);
$query .="
AND product_brand IN('".$brand_filter."')
";
}
if(isset($ram)){
$ram_filter = implode("','", $ram);
$query .="
AND product_ram IN('".$ram_filter."')
";
}
if(isset($storage)){
$storage_filter = implode("','", $storage);
$query .="
AND product_storage IN('".$storage_filter."')
";
}
/*
return $query;*/
$data = $this->db->query($query);
$result = '';
if($data->num_rows() > 0)
{
foreach($data->result_array() as $row)
{
$result .= '
<div class="col-sm-4 col-lg-3 col-md-3">
<div style="border:1px solid #ccc; border-radius:5px; padding:16px; margin-bottom:16px; height:450px;">
<img src="'.base_url().'images/'. $row['product_image'] .'" alt="" class="img-responsive" >
<p align="center"><strong>'. $row['product_name'] .'</strong></p>
<h4 style="text-align:center;" class="text-danger" >'. $row['product_price'] .'</h4>
<p>Camera : '. $row['product_camera'].' MP<br />
Brand : '. $row['product_brand'] .' <br />
RAM : '. $row['product_ram'] .' GB<br />
Storage : '. $row['product_storage'] .' GB </p>
</div>
</div>
';
}
$output = array('product_list' => $result);
}
else
{
$result = '<h3>No Data Found</h3>';
}
echo json_encode($output);
views
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="userfile[]" size="40" multiple/>
<input type="submit" name="submit" value="Upload">
</form>
controller
public function image()
{
$data['error'] = '';
$this->load->model('StackM');
if(isset($_POST['submit']))
{
$data['update_pass_error_msg'] = $this->StackM->add_multiple_image();
}
$this->load->view('stack_view');
}
Model
public function add_multiple_image(){
if((!empty($_FILES['f2']['name'])))
{
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$files = $_FILES;
if ($files['f2']['name'][0] == '' )
{
# code...
return "Select a file to upload";
}
else
{
$mum_files = count($files['f2']);
for($i=0; $i<$mum_files; $i++)
{
if ( isset($files['f2']['name'][$i]) )
{
$config['file_name'] = time().'-'.$files['f2']['name'][$i];
$this->load->library('upload', $config);
$_FILES['f2']['name']= $files['f2']['name']["$i"];
$_FILES['f2']['type']= $files['f2']['type']["$i"];
$_FILES['f2']['tmp_name']= $files['f2']['tmp_name']["$i"];
$_FILES['f2']['error']= $files['f2']['error']["$i"];
$_FILES['f2']['size']= $files['f2']['size']["$i"];
$filename = rand().'-'.$_FILES['f2']['name'];
if (!empty($this->upload->do_upload('f2')))
{
$dataInfo[] = $this->upload->data();
$all_imgs = '';
if ( count($dataInfo) > 0) {
# code...
foreach ($dataInfo as $info) {
# code...
$all_imgs .= $info['file_name'];
$all_imgs .= ',';
}
}
}
}
}
}
}
else{
$all_imgs = "";
}
}
}
else{
$all_imgs = $this->session->userdata('image');
}
$this->db->insert('table_name', $all_imgs);
The problem I am facing in this code is Think suppose if I am adding 7 images, but it's showing only 5 images in database it's not taking more then five and also I want to know while editing the form if I don't want to change the image then it should remain same image so i have stored the old image in session and checking if it is empty then only it should session variable .
But In my code if I will not upload new one If I keep old image as then it will save blank
To avoid the offset error, inside of for loop you need to check if that array index is set or not:
Here I have a demo code to upload multiple files in CodeIgniter:
views/stack_view.php
<?php if ($this->session->flashdata('status')) { ?>
<h5><?=$this->session->flashdata('status')?>: <?=$this->session->flashdata('message')?></h5>
<?php } ?>
<?=form_open_multipart('stack', array('id' => 'my_id'))?>
<input type="file" name="userfile[]" size="40" multiple/>
<input type="submit" name="submit" value="Upload">
<?=form_close()?>
controllers/Stack.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Stack extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper(array('form', 'url'));
}
public function index()
{
if ($this->input->post('submit')) {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$files = $_FILES;
if ($files['userfile']['name'][0] == '' ) {
# code...
$this->session->set_flashdata('status', 'error');
$this->session->set_flashdata('message', "Select a file to upload");
}
else
{
$mum_files = count($files['userfile']);
$dataInfo = array();
for($i=0; $i<$mum_files; $i++)
{
if ( isset($files['userfile']['name'][$i]) ) {
$config['file_name'] = time().'-'.$files['userfile']['name'][$i];
$this->load->library('upload', $config);
$_FILES['userfile']['name']= $files['userfile']['name']["$i"];
$_FILES['userfile']['type']= $files['userfile']['type']["$i"];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name']["$i"];
$_FILES['userfile']['error']= $files['userfile']['error']["$i"];
$_FILES['userfile']['size']= $files['userfile']['size']["$i"];
$filename = rand().'-'.$_FILES['userfile']['name'];
if ( ! $this->upload->do_upload('userfile'))
{
$error_message = $this->upload->display_errors();
$this->session->set_flashdata('status', 'error');
$this->session->set_flashdata('message', "$error_message");
}
else
{
//$data = array('upload_data' => $this->upload->data());
$this->session->set_flashdata('status', 'success');
$this->session->set_flashdata('message', "Files upload is success");
}
$dataInfo[] = $this->upload->data(); //all the info about the uploaded files are stored in this array
}
}
//here you can insert all the info about uploaded file into database using $dataInfo
$all_imgs = '';
if ( count($dataInfo) > 0) {
# code...
foreach ($dataInfo as $info) {
# code...
$all_imgs .= $info['file_name'];
$all_imgs .= ',';
}
}
$insert_data = array(
'your_column_name' => rtrim($all_imgs,",")
);
$this->db->insert('your_table_name', $insert_data);
}
}
$this->load->view('stack_view');
}
}
Try this script and I hope you will get some help from this.
This is working script try to upload it
public function upload()
{
$this->load->library('session');
if ( ! empty($_FILES))
{
$config['upload_path'] = "assets/uploads/";
$config['allowed_types'] = 'jpg|png|jpeg';
$config['max_size'] = 5120; //limit only 5 Mb
$this->load->library('upload');
$files = $_FILES;;
$number_of_files = count($_FILES['files']['name']);
$errors = 0;
$myname = $this->input->post('ad_title');
for ($i = 0; $i < $number_of_files; $i++)
{
//$randVal = rand(450,4550).time('d-y-m');
$filename = basename($files['files']['name'][$i]);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new = md5($filename.''.time('d-y-m')).'.'.$extension;
$_FILES['files']['name'] = $new; //$files['files']['name'][$i];
$_FILES['files']['type'] = $files['files']['type'][$i];
$_FILES['files']['tmp_name'] = $files['files']['tmp_name'][$i];
$_FILES['files']['error'] = $files['files']['error'][$i];
$_FILES['files']['size'] = $files['files']['size'][$i];
$image = array('upload_data' => $this->upload->data());
$image_name = $_FILES['files']['name'];
$ip = $this->input->ip_address();
$this->session->set_userdata("userIP",$ip);
//$this->session->unset_userdata("userIP");
$Dval = array(
"filename" => $image_name,
"ip" => $this->input->ip_address()
);
$this->member_model->tmp_image($Dval);
$this->upload->initialize($config);
if ( $this->upload->do_upload("files"))
{
$errors++;
$data = $this->upload->data();
echo json_encode($data['file_name']);
//code is for thumbnail and watermark on images
//$this->watermark($data['full_path']);
//$myPathfT = $config1['upload_path'] = "./assets/thumbs/".$aDir;
//mkdir($myPathfT);b
$config1 = array();
$config1['image_library'] = 'gd2';
$config1['source_image'] = $data['full_path'];
$config1['new_image'] = 'assets/uploads/thumbs/';
$config1['create_thumb'] = false;
$config1['quality'] = 50;
$config1['height'] = 150;
$config1['width'] = 150;
$this->load->library('image_lib',$config1);
$this->image_lib->initialize($config1);
$this->image_lib->resize();
$this->image_lib->clear();
}
}
if ($errors > 0)
{
//echo "Data Transferred";
}
}
elseif ($this->input->post('file_to_remove'))
{
$aDir = $this->session->userdata('Dir');
$file_to_remove = $this->input->post('file_to_remove');
unlink("./assets/mainFilesData/$aDir/" . $file_to_remove);
$array = $this->session->userdata('photo');
$dataF = array_diff($array, array($file_to_remove));
$this->session->set_userdata('photo',$dataF);
}
else
{
$this->listFiles();
}
}
I'm trying to upload an image from a WYSIWYG textarea (TinyMCE), but it's not working, it gives me the error "File not selected".
I'm using multipart form, is it conflicting with other "input file" ?
Thanks.
Here is the code i'm using.
View (.twig)
{{ form_open_multipart() }}
...
<div class="form-group">
<label class="col-sm-2 control-label">Texto</label>
<div class="col-sm-10">
{{ form_textarea('text',set_value('text') ? set_value('text') : post.text|raw,'class="form-control editor"') }}
<input name="image" type="file" id="upload_img_wysiwyg" class="hidden" onchange="">
</div>
</div>
{{ form_close() }}
Controller
public function upload_image_tinymce() {
//Check whether user upload picture
if (!empty($_FILES['image']['name'])) {
$config['upload_path'] = ADDONPATH.'themes/escolamagica/img/escolamagica-blog/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['image']['name'];
$config['overwrite'] = TRUE;
$config['max_size'] = '10240';
$config['max_width'] = '10000';
$config['max_height'] = '10000';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ($this->upload->do_upload('image')) {
$picture = str_replace('\\', '/', base_url().'img/escolamagica-blog/'.$_FILES['image']['name']);
} else {
echo 'CONFIG';
var_dump($config);
echo 'IMAGE';
var_dump($_FILES);
echo 'ERROR';
$error = array('error' => $this->upload->display_errors());
var_dump($error);
die;
$picture = '';
}
} else {
$picture = '';
}
return $picture;
}
Javascript
function initImageUpload(editor) {
// create input and insert in the DOM
var inp = $('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
$(editor.getElement()).parent().append(inp);
// add the image upload button to the editor toolbar
editor.addButton('imageupload', {
text: '',
icon: 'image',
onclick: function(e) { // when toolbar button is clicked, open file select modal
inp.trigger('click');
}
});
// when a file is selected, upload it to the server
inp.on("change", function(e){
uploadFile($(this), editor);
});
}
function uploadFile(inp, editor) {
var input = inp.get(0);
var data = new FormData();
data.append('image[file]', input.files[0]);
$.ajax({
url: BASE_URL + 'admin/blog/upload_image_tinymce',
type: 'POST',
data: data,
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR) {
console.log(data);
editor.insertContent('<img class="content-img" src="' + data.url + '"/>');
},
error: function(jqXHR, textStatus, errorThrown) {
if(jqXHR.responseText) {
errors = JSON.parse(jqXHR.responseText).errors
alert('Error uploading image: ' + errors.join(", ") + '. Make sure the file is an image and has extension jpg/jpeg/png.');
}
}
});
}
tinymce.init({
language: "pt_PT",
language_url: BASE_URL + "/admin/js/pt_PT.js",
selector: ".editor",
height: 600,
plugins: [
"advlist autolink lists link image charmap print preview hr anchor pagebreak",
"searchreplace wordcount visualblocks visualchars code fullscreen",
"insertdatetime media nonbreaking save table contextmenu directionality",
"emoticons template paste textcolor colorpicker textpattern"
],
toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link imageupload",
toolbar2: "print preview media | forecolor backcolor emoticons",
image_advtab: !0,
setup: function(editor) {
initImageUpload(editor);
}
You are using a different index for the upload in your form and the tinyMce image upload. Your html form has file input with the name "image". But your MCE ajax file upload has the name "pic". So, in your controller function upload_image_tinymce() replace $_FILES['image'] with $_FILES['pic']
Use this in controller :
public function upload_image_tinymce() {
//Check whether user upload picture
if (!empty($_FILES['pic']['name'])) {
$config['upload_path'] = ADDONPATH.'themes/escolamagica/img/escolamagica-blog/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['pic']['name'];
$config['overwrite'] = TRUE;
$config['max_size'] = '10240';
$config['max_width'] = '10000';
$config['max_height'] = '10000';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ($this->upload->do_upload('pic')) {
$picture = str_replace('\\', '/', base_url().'img/escolamagica-blog/'.$_FILES['pic']['name']);
} else {
echo 'CONFIG';
var_dump($config);
echo 'IMAGE';
var_dump($_FILES);
echo 'ERROR';
$error = array('error' => $this->upload->display_errors());
var_dump($error);
die;
$picture = '';
}
} else {
$picture = '';
}
return $picture;
}
we are really facing very strange problem here.
we are using 1.9.0.1 and custom shipping method.
We Hide Shipping Method Step in checkout using answer gave by #Marius here :
https://magento.stackexchange.com/questions/53355/remove-shipping-steps-in-onepage-checkout
But we have one problem here.
we allowed only some zip codes to place an order.
but here its allowing for all zip codes when user enter first time.
once user enter zip code and click on "Continue" button, it will go to next step [payment methods]
Payment method step
Than if user again come to Previous step and enter same zip code and if user click on "Continue"
button, than it will show error message in pop up - "Invalid shipping method"
This is fine, but it should not allow when user enter zip code for first time also.
Before everything was fine, once we hide shipping method , this problem happened. but for default shipping method it is working fine.
ex site : link & zip code 000000
we are using this code for restricting zip codes and finding shipping charges.
<?php
class extension_Mpperproductshipping_Model_Carrier_LocalDelivery extends Mage_Shipping_Model_Carrier_Abstract
{
/* Use group alias */
protected $_code = 'mpperproductshipping';
public function collectRates(Mage_Shipping_Model_Rate_Request $request){
$postCode = $request->getDestPostcode();
$restrictedCodes = array(
110001,
110002
); //restricted values. they can come from anywhere
if (!in_array($postCode, $restrictedCodes)) {
return false;
}
$result = Mage::getModel('shipping/rate_result');
/* Edited by vikas_mageworx */
$postcode=$request->getDestPostcode();
$countrycode=$request->getDestCountry();
$items=$request->getAllItems();
/* End Editing by vikas_mageworx */
$postcode=str_replace('-', '', $postcode);
$shippingdetail=array();
/* one start */
$shippostaldetail=array('countrycode'=>$countrycode,'postalcode'=>$postcode,'items'=>$items);
/* one end */
foreach($items as $item) {
$proid=$item->getProductId();
$options=$item->getProductOptions();
$mpassignproductId=$options['info_buyRequest']['mpassignproduct_id'];
if(!$mpassignproductId) {
foreach($item->getOptions() as $option) {
$temp=unserialize($option['value']);
if($temp['mpassignproduct_id']) {
$mpassignproductId=$temp['mpassignproduct_id'];
}
}
}
if($mpassignproductId) {
$mpassignModel = Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId);
$partner = $mpassignModel->getSellerId();
} else {
$collection=Mage::getModel('marketplace/product')
->getCollection()->addFieldToFilter('mageproductid',array('eq'=>$proid));
foreach($collection as $temp) {
$partner=$temp->getUserid();
}
}
$product=Mage::getModel('catalog/product')->load($proid)->getWeight();
$weight=$product*$item->getQty();
if(count($shippingdetail)==0){
array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId()));
}else{
$shipinfoflag=true;
$index=0;
foreach($shippingdetail as $itemship){
if($itemship['seller_id']==$partner){
$itemship['items_weight']=$itemship['items_weight']+$weight;
$itemship['product_name']=$itemship['product_name'].",".$item->getName();
$itemship['item_id']=$itemship['item_id'].",".$item->getId();
$itemship['qty']=$itemship['qty']+$item->getQty();
$shippingdetail[$index]=$itemship;
$shipinfoflag=false;
}
$index++;
}
if($shipinfoflag==true){
array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId()));
}
}
}
$shippingpricedetail=$this->getShippingPricedetail($shippingdetail,$shippostaldetail);
if($shippingpricedetail['errormsg']!==""){
Mage::getSingleton('core/session')->setShippingCustomError($shippingpricedetail['errormsg']);
return $result;
}
/*store shipping in session*/
$shippingAll=Mage::getSingleton('core/session')->getData('shippinginfo');
$shippingAll[$this->_code]=$shippingpricedetail['shippinginfo'];
Mage::getSingleton('core/session')->setData('shippinginfo',$shippingAll);
$method = Mage::getModel('shipping/rate_result_method');
$method->setCarrier($this->_code);
$method->setCarrierTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/title'));
/* Use method name */
$method->setMethod($this->_code);
$method->setMethodTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/name'));
$method->setCost($shippingpricedetail['handlingfee']);
$method->setPrice($shippingpricedetail['handlingfee']);
$result->append($method);
return $result;
}
public function getShippingPricedetail($shippingdetail,$shippostaldetail) {
$shippinginfo=array();
$handling=0;
$session = Mage::getSingleton('checkout/session');
$customerAddress = $session->getQuote()->getShippingAddress();
/* Edited by vikas_boy */
$customerPostCode = $shippostaldetail['postalcode'];
$items = $shippostaldetail['items'];
/* End Editing by vikas_boy */
/* one */
foreach($shippingdetail as $shipdetail) {
$seller = Mage::getModel("customer/customer")->load($shipdetail['seller_id']);
$sellerAddress = $seller->getPrimaryShippingAddress();
$distance = $this->getDistanse($sellerAddress->getPostcode(),$customerPostCode);
// echo "distance ".$distance;die;
$price = 0;
$itemsarray=explode(',',$shipdetail['item_id']);
foreach($items as $item) {
$proid=$item->getProductId();
$options=$item->getProductOptions();
$mpassignproductId=$options['info_buyRequest']['mpassignproduct_id'];
if(!$mpassignproductId) {
foreach($item->getOptions() as $option) {
$temp=unserialize($option['value']);
if($temp['mpassignproduct_id']) {
$mpassignproductId=$temp['mpassignproduct_id'];
}
}
}
if (Mage::getModel('catalog/product_type_configurable')->getParentIdsByChild($proid))
{
continue;
}
$mpshippingcharge = 0;
$localDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/local_shipping_distance');
$regionalDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/regional_shipping_distance');
$stateDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/state_shipping_distance');
if(in_array($item->getId(),$itemsarray)) {
if($mpassignproductId) {
if($distance < $localDistance) {
$mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getLocalShippingCharge();
} elseif($distance > $localDistance && $distance < $regionalDistance) {
$mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getRegionalShippingCharge();
} elseif($distance > $regionalDistance) {
$mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getStateShippingCharge();
}
} else {
// echo "imte ".$item->getProductId();
if($distance < $localDistance) {
$mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpLocalShippingCharge();
// echo "imte ".$item->getProductId();
// echo "ship ".$mpshippingcharge;
} elseif($distance > $localDistance && $distance < $regionalDistance) {
$mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpRegionalShippingCharge();
} elseif($distance > $regionalDistance) {
$mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpStateShippingCharge();
}
}
/* tt */
// echo "test ".$mpshippingcharge;die;
if(!is_numeric($mpshippingcharge)){
$price=$price+floatval($this->getConfigData('defalt_ship_amount')* floatval($item->getQty()));
}else{
$price=$price+($mpshippingcharge * floatval($item->getQty()));
}
}
}
$handling = $handling+$price;
$submethod = array(array('method'=>Mage::getStoreConfig('carriers/'.$this->_code.'/title'),'cost'=>$price,'error'=>0));
array_push($shippinginfo,array('seller_id'=>$shipdetail['seller_id'],'methodcode'=>$this->_code,'shipping_ammount'=>$price,'product_name'=>$shipdetail['product_name'],'submethod'=>$submethod,'item_ids'=>$shipdetail['item_id']));
}
$msg="";
return array('handlingfee'=>$handling,'shippinginfo'=>$shippinginfo,'errormsg'=>$msg);
}
/* one end */
/* tt start */
private function getDistanse($origin,$destination) {
$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=".$origin.",india&destinations=".$destination.",india&mode=driving&language=en-EN&sensor=false";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_all = json_decode($response);
$distance = $response_all->rows[0]->elements[0]->distance->value / 1000;
if($distance==0){
$zips = array(
$origin,$destination
// ... etc ...
);
$geocoded = array();
$serviceUrl = "http://maps.googleapis.com/maps/api/geocode/json?components=postal_code:%s&sensor=false";
$curl = curl_init();
foreach ($zips as $zip) {
curl_setopt($curl, CURLOPT_URL, sprintf($serviceUrl, urlencode($zip)));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$data = json_decode(curl_exec($curl));
$info = curl_getinfo($curl);
if ($info['http_code'] != 200) {
// Request failed
} else if ($data->status !== 'OK') {
// Something happened, or there are no results
} else {
$geocoded[$zip] =$data->results[0]->geometry->location;
}
}
$distance=$this->DistAB($geocoded[$zips[0]]->lat,$geocoded[$zips[0]]->lng,$geocoded[$zips[1]]->lat,$geocoded[$zips[1]]->lng);
}
return $distance;
}
public function DistAB($lat_a,$lon_a,$lat_b,$lon_b)
{
$measure_unit = 'kilometers';
$measure_state = false;
$measure = 0;
$error = '';
$delta_lat = $lat_b - $lat_a ;
$delta_lon = $lon_b - $lon_a ;
$earth_radius = 6372.795477598;
$alpha = $delta_lat/2;
$beta = $delta_lon/2;
$a = sin(deg2rad($alpha)) * sin(deg2rad($alpha)) + cos(deg2rad($this->lat_a)) * cos(deg2rad($this->lat_b)) * sin(deg2rad($beta)) * sin(deg2rad($beta)) ;
$c = asin(min(1, sqrt($a)));
$distance = 2*$earth_radius * $c;
$distance = round($distance, 4);
$measure = $distance;
return $measure;
}
}
/* tt end */
onepage.phtml : app/design/frontend/default/em0113/template/checkout/onepage.phml
<div class="page-title">
<h1><?php echo $this->__('Checkout') ?></h1>
</div>
<script type="text/javascript" src="<?php echo $this->getJsUrl('varien/accordion.js') ?>"></script>
<script type="text/javascript" src="<?php echo $this->getSkinUrl('js/opcheckout.js') ?>"></script>
<ol class="opc" id="checkoutSteps">
<?php $i=0; foreach($this->getSteps() as $_stepId => $_stepInfo): ?>
<?php if (!$this->getChild($_stepId) || !$this->getChild($_stepId)->isShow()): continue; endif; $i++ ?>
<li id="opc-<?php echo $_stepId ?>" class="section<?php echo !empty($_stepInfo['allow'])?' allow':'' ?><?php echo !empty($_stepInfo['complete'])?' saved':'' ?>">
<div class="step-title">
<span class="number"><?php echo $i ?>.</span>
<h2><?php echo $_stepInfo['label'] ?></h2>
<?php echo $this->__('Edit') ?>
</div>
<div id="checkout-step-<?php echo $_stepId ?>" class="step a-item" style="display:none;">
<?php echo $this->getChildHtml($_stepId) ?>
</div>
</li>
<?php endforeach ?>
</ol>
<script type="text/javascript">
//<![CDATA[
var accordion = new Accordion('checkoutSteps', '.step-title', true);
<?php if($this->getActiveStep()): ?>
accordion.openSection('opc-<?php echo $this->getActiveStep() ?>');
<?php endif ?>
var checkout = new Checkout(accordion,{
progress: '<?php echo $this->getUrl('checkout/onepage/progress') ?>',
review: '<?php echo $this->getUrl('checkout/onepage/review') ?>',
saveMethod: '<?php echo $this->getUrl('checkout/onepage/saveMethod') ?>',
failure: '<?php echo $this->getUrl('checkout/cart') ?>'}
);
//]]>
</script>
What you can do is bind a javascript event to the input field of pincode and send the request everytime when someone is typing in the pincode like this:
<input type = "text" onchange = "myfun(this.value)">
And then bind a javascript function myfun to it and make an AJAX call to your pincode checking controller, this will take the value once you finish typing into the text box
Otherwise you can also go with
<input type = "text" onkeypress = "myfun(this.value)">
And then again bind a javascript function myfun to it and make an AJAX call to your pincode checking controller, this will take the value even when you are typing into the text box
Ok, in your onepage template, write this code:
jQuery('#billing:postcode').change(function(){
// your ajax call to your controller where you are verifying your pincode, something like:
jQuery.ajax({
url: "path/to/your/controller",
data: this.value,
success: function(response){
if(response == true){
// your success action
} else{
//your failure action
}
}
})
})
Ok, so my script tries to request from php results from mysql and load them into a div. The results are based on nid value which is has to send this value is extracted from id="record-#" the record- is removed and the # is left to be used by ajax as id for the nid.
here is the ajax data function
$(document).ready(function() {
$(".note").live('click',function() {
$("#note_utm_con").show();
$("#note_utm_nt").html("<img src='http://www.ajaxload.info/images/exemples/4.gif' />");
$.ajax({
type: "GET",
url: "_class/view.php",
data: "ajax=1&nid=" + parent.attr('id'),
success: function(html){
$("#note_utm").html(html);
$("#note_utm_nt").html("");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {$("#note_utm_nt").html(errorThrown);}
});
});
$("#note_utm_con_cls").click(function() {
$("#note_utm_con").hide();
});
});
and here is the rest of the page
<div id="note_utm_con" style="display: none;">
<button id="note_utm_con_cls" style="width: 20px;float: right; padding: 2px;clear: both;">X</button>
<div id="note_utm"></div>
<div id="note_utm_nt"></div>
</div>
<?php
class notes {
var $host;
var $username;
var $password;
var $table;
public function display_notes() {
$q = "SELECT * FROM `notice` ORDER BY nid ASC LIMIT 12";
$r = mysql_query($q);
if ( $r !== false && mysql_num_rows($r) > 0 ) {
while ( $a = mysql_fetch_assoc($r) ) {
$nid = stripslashes($a['nid']);
$note = stripslashes($a['note']);
$type = stripslashes($a['type']);
$private = stripslashes($a['private']);
$date = stripslashes($a['date']);
$author = stripslashes($a['author']);
if($type == 1) {
$type = "posted a comment."; $icon = "http://cdn1.iconfinder.com/data/icons/Basic_set2_Png/16/megaphone.png";
} elseif($type == 2) {
$type = "raised a support ticket."; $icon = "http://cdn1.iconfinder.com/data/icons/basicset/help_16.png";
} elseif($type == 3) {
$type = "added new photo."; $icon = "http://cdn1.iconfinder.com/data/icons/Basic_set2_Png/16/photo.png";
} elseif($type == 4) {
$type = "updated profile details."; $icon = "http://cdn1.iconfinder.com/data/icons/Basic_set2_Png/16/user_info.png";
} else { }
$entry_display .= <<<ENTRY_DISPLAY
<ul class="list">
<li id="$nid">
<a href="javascript:;" id="$nid" onClick="retun false;" class="note">
<img src="$icon" />
$author,
$type
</a>
</li>
</ul>
ENTRY_DISPLAY;
}
} else {
$entry_display = <<<ENTRY_DISPLAY
<ul class="list">
<li>
<p>
<img src="http://cdn1.iconfinder.com/data/icons/basicset/monitor_16.png" />
Nothing to display
</p>
</li>
</ul>
ENTRY_DISPLAY;
}
return $entry_display;
}
public function connect() {
mysql_connect($this->host,$this->username,$this->password) or die("Could not connect. " . mysql_error());
mysql_select_db($this->table) or die("Could not select database. " . mysql_error());
return $this;
}
private function note_type() {
if($type == 1) { $type = "posted a comment!"; } elseif($type == 2) { $type = "raised a support ticket!"; } else { }
return $type;
}
}
?>
so when a LI with a class="note" is clicked it triggers AJAX call. The call then uses the ID in the href to extract the $nid from the id="record-
In my case it seems as AJAX is sending the request since view.php returns the fields where the data should be but it does not seem to pass much needed nid so PHP is uable to select proper nid from MySQL to use.
Can some one tell me whats wrong with it and how it can be fixed to get the id?enter code here
Your quotation marks are wrong. Try this:
data: "ajax=1&nid=" + parent.attr('id').replace('record-',''),
Edit: Unless you haven't posted the full code still, you don't actually set parent anywhere. This means that you will use the window.parent object, which surprisingly enough doesn't have an id. You should use this.parentNode.id instead:
data: "ajax=1&nid=" + this.parentNode.id,
From what you've written it looks as if you're passing the parent.attr("id") replace call as a string rather than extracting the variable:
data: "ajax=1&nid=" + parent.attr('id').replace('record-',''),