I have been working on this code
$("#library").submit(function(e){
//return false;
e.preventDefault();
dataString = $("#library").serialize();
$.ajax({
type:"POST",
url:"<?= base_url() ?>index.php/library/comment",
data: dataString,
dataType: 'json',
success: function(data){
$("#librarycomment").val("");
$('#comment-list').prepend('<li><div class="avatar"><img src="<?= base_url();?>asset/css/library/images/picture.jpg">' +
'</div>' + '<div class="colset">' + '<div class="author">' + data.user +
' <strong>' + data.date + '</strong>' +
'</div>' + '<div class="comment-content">' +
data.text + '</div></div></li>').find("li:first").hide().slideDown('slow');
}
});
});
Where i would like to have a nice form validation without having to refresh the browser. Somewhat the code above does not work.
I have tried to replace e.preventDefault(); with
All giving nothing at all. The form does submit the data and store the data to the database. However, the ajax part does not run quiet like what i expect it to be.
Does anyone know what am i missing here?
class somehelperclass
{
public function unserialize($input, $pIndex = 'data')
{
if(!isset($input[$pIndex]))
exit('index '.$pIndex.' is not exist');
parse_str($input[$pIndex], $input);
$post = array();
foreach($input as $index => $value)
{
$index = preg_replace('/\;/', '', $index);
$post[$index] = $value;
}
return $input;
}
public function jsonResponse($array)
{
header("Content-type: application/json");
echo json_encode($array);
exit();
}
}
// your controller
class Library extends CI_Controller
{
public function comment()
{
$this->load->library('somehelperclass');
$_POST = $this->somehelperclass->unserialize($_POST, 'data');
$this->somehelperclass->jsonResponse($_POST);
}
}
// js
$("#library").submit(function(){
that = $(this);
$.ajax({
type: "post",
url: "/index.php/library/comment",
data: {data: that.serialize()},
dataType: 'json',
success: function(response)
{
$("#librarycomment").val("");
$('#comment-list').prepend('<li><div class="avatar"><img'
+ ' src="/asset/css/library/images/picture.jpg"></div>'
+ '<div class="colset"><div class="author">'
+ response.user + ' <strong>' + response.date + '</strong>' +
'</div>' + '<div class="comment-content">' +
response.text + '</div></div></li>').find("li:first").hide().slideDown('slow');
}
});
return false;
});
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.