简体   繁体   English

在 codeigniter controller 中调用 function 不工作

[英]calling function in codeigniter controller using ajax not working

i have a codeigniter website, where i have done an add to cart function, on button click the product is added to cart after page reloads which is working fine, i did the folloing code in controller:我有一个 codeigniter 网站,在那里我完成了添加到购物车 function 的操作,单击按钮后,该产品会在页面重新加载后添加到购物车中,这工作正常,我在 Z594C103F2C6E04C3DAZ8 中做了以下代码:

 public function buy($id) { $color= $this->input->post('color'); $size=$this->input->post('size'); $product = $this->product->find($id); $item = array( 'id' => $product->id, 'name' => $product->pname, 'quantity' => 1 ); if(;$this->session->has_userdata('cart')) { $cart = array($item), $this->session->set_userdata('cart'; serialize($cart)); } else { $index = $this->exists($id); $cart = array_values(unserialize($this->session->userdata('cart'))), if($index == -1) { array_push($cart; $item), $this->session->set_userdata('cart'; serialize($cart)); } else { // $cart[$index]['quantity']++, // $this->session->set_userdata('cart'; serialize($cart)), $this->session->set_flashdata("Error";"Product Already In Cart;"), redirect($_SERVER['HTTP_REFERER']); } } $this->session->set_flashdata("Success";"Product Added To Cart Successfully !"); redirect($_SERVER['HTTP_REFERER']); }

now am trying to call this function using ajax so that the product is added to cart without page reload, i did the following code:现在我尝试使用 ajax 调用此 function 以便将产品添加到购物车而无需重新加载页面,我执行了以下代码:

 $("#change").submit(function() { alert("Change"); var id = $('#prod').val(); $.ajax({ type: 'POST', url: "<?php echo base_url(); ?>" + "index.php/homecontroller/buy/" + id, data: { 'id': id }, success: function(data) { $('#resultdiv').html(data); } }); });
 <form action="" method="post" id="change"> <input type="hidden" value="<?php echo $product->id; ?>" id="prod"> <input type="submit" value="switch"> </form> <div class="resultdiv"> <?php echo $data; ?> </div>

however its not adding to cart, it simply reloads the page, can anyone please tell me what is rong in here, thanks i advance但是它没有添加到购物车,它只是重新加载页面,谁能告诉我这里的 rong 是什么,谢谢我提前

Because the form is still submitting, you can use preventDefault();因为表单还在提交,所以可以使用 preventDefault();

$("#change").submit(function(e) {
  e.preventDefault();
  alert("Change");
  var id = $('#prod').val();
  $.ajax({
    type: 'POST',
    url: "<?php echo base_url(); ?>" + "index.php/homecontroller/buy/" + id,
    data: {
      'id': id
    },
    success: function(data) {
      $('#resultdiv').html(data);
    }
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM