Hello,
This is my first time trying to make an ajax call with JSON.
I am developing a site with CodeIgniter 2.1.4.
I am on the verge of throwing my computer away and find a job selling flowers....
Here's the story:
In my view I have a dropdown box:<?php echo form_dropdown('delivery', $delivery, '1', 'id="delivery"'); ?>
When the user selectes a value in the dropdown box, I want to send some values to my controller and return some values.
In my view:
$('#delivery').on('change', function()
{
var delivery_type = $(this).val();
var orderId = $('#orderId').val();
var subtotal = $('#subtotal').val();
var postData = "type=" + delivery_type + "orderId=" + orderId + "subtotal=" + subtotal;
alert(postData);
$.ajax({
type: "POST",
dataType: "json",
data: postData,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
url: "<?php echo site_url('cart/calculate_delivery'); ?>",
success: function(data) {
// 'data' is a JSON object which we can access directly.
// Evaluate the data.success member and do something appropriate...
alert(data.subtotal . ' ' . data.postage);
$('#delivery_cost').html(data.postage);
$('#total').html(data.total);
}
});
return false;
});
It looks like the controller does not get all the posted values, so I am trying to test what is getting through.
My controller:
public function calculate_delivery($type=NULL)
{
if(!$type)
{
$ajax = TRUE; //Called from ajax, need to echo the result
$type = $this->input->post('type');
}
else
{
$type = 2;
$ajax = FALSE;//Not called from ajax, need to return the result
}
//Calculating postage
$totalWeight = 0;
$orderId = $this->get_open_order();
$order = $this->order_dets_m->get_open_order($orderId);
if($order)
{
foreach($order as $item)
{
$weight = $item['weight'] == '250g' ? 0.25 : 1;
$totalWeight += $weight * $item['qty'];
}
$totalWeight = ceil($totalWeight);
if($type == 1)
{
$this->load->model('delivery_types_m');
$rate = $this->delivery_types_m->get(1);
$baseRate = $rate->rate;
$additionalRate = $rate->additional_rate;
$postage = $this->cart->format_number($baseRate + ($totalWeight * $additionalRate));
}
else
{
$this->load->model('delivery_rates_m');
$rate = $this->delivery_rates_m->get_by(array('type_id'=>$type, 'kg'=>$totalWeight), TRUE);
$postage = $rate->rate;
}
if($ajax)
{
$subtotal = $this->input->post('subtotal');
$total = $this->cart->format_number($subtotal + $postage);
$result = array('total'=>$total,'postage'=>$postage, 'subtotal'=>$subtotal);
echo json_encode($result);
}
else
{
return $postage;
}
}
}
If I remove the ajax call the alret message: alert(postData); works and I see this string:
type=1orderId=12subtotal=90.00
If I add the ajax call, nothing happens, no error in firebug, no alret, silence.
What am I doing wrong?
Thanks