简体   繁体   中英

Send Form Data to Controller (Codeigniter)

I have a pop up menu and inside that I have a form and a text box. I want to retrieve that value and submit it to my controller. Once submitted I want my pop up to close and go back to the other page. I tried with AJAX but I might be doing something wrong.

<form onsubmit="return(testing());" method="POST">
      <input type="text" name="vip_text_box" id="vip" value="<?php echo $total_amount ?>"> <br>
      <input type="submit" name="Redeem"  value="Redeem">
</form>

Now My Javascript

function testing() {
  $test = document.getElementById("vip").value;
  var url = base_url + '/index.php/home/redeeming_form_value';
    $.ajax({
      type : 'POST',
      url : url,
      data : {'myvalue':test},
      success: function(data){
        alert(data);
      }
    });
};

In my controller

function redeeming_form_value() {

     $amount = $this->input->post('myvalue');

     return $amount;

In the AJAQ I have a success, and want to alert my data(the value) to make sure it even works but it does nothing. When i click submit my pop up view just goes away.

Try adding dataType: "json", to your Ajax

dataType: "json",

Then in your controller use json_encode to return your data

$arr = array('amount' => $amount);
return json_encode($arr);

Test the response in success

console.log(data.amount);

Try it..

HTML

<form action="" method="POST">
      <input type="text" name="vip_text_box" id="vip" value="<?php echo $total_amount ?>"> <br>
      <input type="submit" name="Redeem" id="submit"  value="Redeem">
</form>

Javascript

<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
  var test = $("#vip").val();
  var base_url= 'http://localhost/shop';
  var url = base_url + '/index.php/home/redeeming_form_value';
    $.ajax({
      type : 'POST',
      dataType: 'json',
      url : url,
      data :'myvalue='+test,
      success: function(data){
         msg= eval(data);
         amount= msg.amount;
         alert(amount);
         }
      });
    });
});
</script>

At your Controller

function redeeming_form_value() 
{

     $amount = $this->input->post('myvalue');

     echo json_encode(array('amount'=>$amount));

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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