I've been struggling to make it work, but cannot pass the inserted data from the controler to the view in CI using JSON. The input value from the form is successfully inserted into the database, but cannot make it appear in the view.
This is my view file ajax_view.php:
<script type="text/javascript" src="<?php echo base_url(); ?>js/jquery-1.4.2.min.js"></script>
$(document).ready(function(){
$("#submit").click(function(){
var inp = $('#inp').val();
$.post("ajax/ajax_input", { 'send' : inp },
function(data){
alert(data.input_text);
}, "json");
});
});
</script>
</head>
<body>
<form id="开发者_开发百科form1" method="post" action="">
<label for="inp">Text</label>
<input type="text" name="inp" id="inp" />
<label for="submit"></label>
<input type="submit" name="submit" id="submit" value="Submit" />
And this is the ajax_input method of the ajax.php controller:
<?php
// Initializing controller .....
// .............................
//ajax method
function ajax_input(){
$var_1 = trim($this->input->post('send'));
$array = array('input_text' => $var_1);
echo json_encode($array);
$this->db->insert('ajax',$array);
}
Trying to debug it with Firebug, it gives me that data.input_text is empty.
What am I doing wrong?
EDIT: I'm using XAMPP on Win, so is it posible that json configuration is the problem?
the code itself should work, here are some tip:
- I don't know if this is a typo or not, but your JS in not opened properly (missing
<script type="text/javascript">
) use
submit()
event instead of havingclick()
event on your submit input:<script type="text/javascript"> $(document).ready(function(){ $("#form1").submit(function(){ var inp = $('#inp').val(); $.post("ajax/ajax_input/", { 'send' : inp }, function(data){ console.log(data.input_text); }, 'json'); return false; }); }); </script>
switch the two line in your Controller and return the
insert()
to a variable just in case:if($this->db->insert('ajax',$array)) echo json_encode($array); else //echo json_encode(array("input_text"=>"Input was not inserted correctly!")); echo json_encode(array("input_text"=>$this->db->last_query())); // for testing purposes ONLY!! don't use in live website!
There is a typo in you ajax_input.php page. Change: $array = array('input_tekst' => $var_1); to
$array = array('input_text' => $var_1);
$array = array('input_tekst' => $var_1); //why tekst?
Change tekst to text.
精彩评论