[英]returning json data from php as response in javascript ajax
我正在用codeigniter建立簡單的商店網站。 如果用戶想購買產品,則必須以1st會員身份登錄。 用戶在產品上單擊“購買”時要創建的任務:
我有這樣的代碼:cart.js:
$(document).ready(function() {
//var url = window.location.pathname;
var base = 'http://thita.dev/index.php/'
//alert(url);
$('.prod_box form').submit(function() {
var id = $(this).find('input[name=id_produk').val();
var qty = $(this).find('input[name=qty]').val();
//alert('ID:' + id + '\n\rQTY:' + qty);
$.post(base + 'order/tambah_belanja', {id_produk: id, quantity: qty, ajax: '1'}, function(data) {
if (data.status === true) {
alert(data.message);
} else {
if (data.errtype === 'login') {
alert('please login 1st');
} else if (data.errtype === 'stok') {
alert('Stock is empty');
}
}
});
return false;
});
});
控制器order.php:
public function tambah_belanja() {
$this->load->library('auth');
$data = array();
if (!$this->auth->cek_login()) {
$data['status'] = false;
$data['errtype'] = 'login';
}
if ($this->mo_order->tambahBelanja() === TRUE) {
if ($this->input->post('ajax') <> '1') {
redirect('order');
} else {
$data['status'] = true;
$data['message'] = 'product is added to cart';
}
} else {
$data['status'] = false;
$data['errtype'] = 'stok';
}
return json_encode($data);
}
模塊mo_order.php:
function tambahBelanja() {
$id_produk = $this->input->post('id_produk');
$qty = $this->input->post('quantity');
$this->db->where('id_produk', $id_produk)
->where('stok >', 0);
$Q = $this->db->get('produk', 1);
if ($Q->num_rows() > 0) {
foreach ($Q->result() as $row) {
$data = array(
'id' => $row->id_produk, //id_produk
'qty' => $qty, //qty
'price' => $row->harga, //harga
'name' => $row->nama_produk //nama_produk
);
}
$this->cart->insert($data);
file_put_contents('/tmp/data.txt', var_export(array('id_produk' => $id_produk, 'qty' => $qty, 'item' => $data), true));
return TRUE;
} else {
return FALSE;
}
}
當我嘗試運行該代碼時,盡管我沒有以會員身份登錄,但仍可以將商品添加到購物車,並且不會顯示警報。
正確的方法如何?
嘗試
if (!$this->auth->cek_login()) {
$data['status'] = false;
$data['errtype'] = 'login';
}else{ //Add this else here i.e if valid login
if ($this->mo_order->tambahBelanja() === TRUE) {
if ($this->input->post('ajax') <> '1') {
redirect('order');
} else {
$data['status'] = true;
$data['message'] = 'product is added to cart';
}
} else {
$data['status'] = false;
$data['errtype'] = 'stok';
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.