Ajax not working in codeigniter 3 - javascript

when i click in the button btnSalvar, ajax need to send data to my controller, but not working.
my ajax:
$("#btnSalvar").on('click', function(){
$.ajax({
url: '<?= base_url(); ?>' + 'grupoProduto/cadastro',
type: 'POST',
data: {Nome: $("#txtNome").val(), Ativo: $("#cbxAtivo").val()},
dataType: 'json',
cache: false,
success:
function(data){
alert(data.Nome); //as a debugging message.
}
});
return false;
});
My controller:
public function cadastro() {
$this->load->view('grupoproduto_view');
}
my alert(data.Nome) showing nothing
here's my full php code:
`
<div class="row">
<div class="form-group">
<label for="txtNome" class="col-md-3 control-label">Nome</label>
<div class="col-md-6">
<?php echo form_input(['name' => 'txtNome', 'class' => 'form-control',
'value' => set_value('txtNome'), 'required' => 'true', 'maxlength' => '50', 'required' => 'true', 'id' => 'txtNome']); ?>
</div>
</div>
<div class="form-group">
<label for="cbxAtivo" class="col-md-3 control-label">Ativo</label>
<div class="col-md-1">
<?php echo form_checkbox(['name' => 'cbxAtivo', 'class' => 'form-control', 'required' => 'true', 'id' => 'cbxAtivo']); ?>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="modal-footer">
<?php echo anchor(NULL, "<i class='glyphicon glyphicon-remove'></i> Sair", ['class' => 'btn btn-default', 'id' => 'btnSair', 'role' => 'button', 'data-dismiss' => 'modal']); ?>
<?php echo form_button(NULL, "<i class='glyphicon glyphicon-ok'></i> Salvar", ['class' => 'btn btn-success', 'id' => 'btnSalvar', 'role' => 'button']); ?>
</div>
</div>
</div>
</div>
</fieldset>
new edit!
`$("#btnSalvar").on('click', function(){
var nome = $("#txtNome").val();
var ativo = $("#cbxAtivo").val();
var url = '<?= base_url(); ?>grupoProduto/cadastro';
$.ajax({
url: url,
type: 'POST',
data: {Nome: nome, Ativo: ativo},
dataType: 'json',
cache: false,
success:
function(data){
alert(data.Nome); //as a debugging message.
},
error: function() {
alert(url);
}
});
return false;
});`
return error in the ajax and show this url: http://localhost/admin/grupoProduto/cadastro. It's correct, but why not success?

Your PHP '<?= base_url(); ?>' + 'grupoProduto/cadastro' is not getting evaluated
$.ajax({
url: '+<?= base_url(); ?>+'+ 'grupoProduto/cadastro',
....
Problem is in your base_url()
In order to use base_url(), you must first have the URL Helper loaded. This can be done either in application/config/autoload.php (on or around line 67):
$autoload['helper'] = array('url');
Or,
manually:
$this->load->helper('url');
checkout this answer

maybe the problem as Nadir says that base_url not evaluated ,
you can try something like this
var link = "<?php echo base_url(); ?>";
var Nome = $("#txtNome").val();
var Ativo = $("#cbxAtivo").val();
$.post(link + "grupoProduto/cadastro", {Nome : Nome ,Ativo :Ativo},function(data){
alert("something")
});

Related

Unable to post the data from view to controller in Yii2

I am working on Yii2. I have a gridview with checkbox and on a button click I am redirecting it to an action controller using ajax.
<?= Html::a('Disconnect', ['dco'], ['class' => 'btn btn-success', 'id'=>'dco']) ?>
<?php Pjax::begin(); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
return ['value' => $d['msn']];
}],
'ref_no',
'dept_code:ntext',
'dept_name:ntext',
'allowed_units',
'msn',
'units_consumed',
[
'label' => 'Disconnected',
'attribute' => 'disconnected',
'format'=>'raw',
'contentOptions' => ['style'=>'text-align:center'],
'value' => function($model){
return $model->disconnected == 1 ? '<span class="glyphicon glyphicon-ok text-success"></span>' : '<span class="glyphicon glyphicon-remove text-danger"></span>';
},
'filter' => Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' => 'form-control']),
],
'diconnected_at',
'reconnected_at',
'active_energy_total_m',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?php Pjax::end(); ?>
JS
<?php
$DCOurl = Url::toRoute(['/hecolog/dco']);
$script = <<< JS
$(document).ready(function () {
//DCO
$('#dco').on('click',function(e) {
e.preventDefault();
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!=="")
{
strValue = strValue + " , " + this.value;
}
else
strValue = this.value;
});
$.ajax({
url: '$DCOurl',
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
alert(data);
}
});
});
});
JS;
$this->registerJs($script, static::POS_END);
?>
But when I click on the disconnect button it doesn't redirect to my controller. In console it gives me Not Found (#404): Page not found.
Update 1
I have updated the ajax call like below
$.ajax({
url: $DCOurl, // removed the inverted commas ''
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
alert(data);
}
});
Controller
public function actionDco()
{
if(Yii::$app->request->isAjax && Yii::$app->request->post())
{
$data = explode(',',$_POST['data']);
var_dump($data);
die();
}
else{
$this->redirect('index');
}
}
After updating the code as suggested I am able to go into my controller but still not able to get the data
In console I am getting error Uncaught SyntaxError: Invalid regular expression flags
Update 2
Below is the code for my view
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
use yii\helpers\Url;
use yii\web\JqueryAsset;
/* #var $this yii\web\View */
/* #var $searchModel common\models\HescologSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'DCO / RCO';
$this->params['breadcrumbs'][] = $this->title;
?>
<section class="content-header">
<h1>DCO / RCO List</h1>
</section>
<section class="content">
<div class="box">
<div class="box-body">
<p>
<?= Html::a('Disconnect', ['dco'], ['class' => 'btn btn-success', 'id'=>'dco']) ?>
<?= Html::a('Re-Disconnect', ['rco'], ['class' => 'btn btn-info','id'=>'rco']) ?>
</p>
<?php Pjax::begin(); ?>
<div class="pre-scrollable">
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
return ['value' => $d['msn']];
}],
'ref_no',
'dept_code:ntext',
'dept_name:ntext',
'allowed_units',
'msn',
'units_consumed',
[
'label' => 'Disconnected',
'attribute' => 'disconnected',
'format'=>'raw',
'contentOptions' => ['style'=>'text-align:center'],
'value' => function($model){
return $model->disconnected == 1 ? '<span class="glyphicon glyphicon-ok text-success"></span>' : '<span class="glyphicon glyphicon-remove text-danger"></span>';
},
'filter' => Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' => 'form-control']),
],
'diconnected_at',
'reconnected_at',
'active_energy_total_m',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
<?php Pjax::end(); ?>
</div>
</div>
</section>
<?php
$DCOurl = Url::toRoute(['/hescolog/dco']);
$RCOurl = Url::toRoute(['/hescolog/rco']);
$script = <<< JS
$(document).ready(function () {
//DCO
$('#dco').on('click',function(e) {
e.preventDefault();
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!=="")
{
strValue = strValue + " , " + this.value;
}
else
strValue = this.value;
});
$.ajax({
url: $DCOurl,
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
alert(data);
}
});
});
$('#rco').on('click',function(e) {
e.preventDefault();
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!=="")
{
strValue = strValue + " , " + this.value;
}
else
strValue = this.value;
});
$.ajax({
url: '$RCOurl',
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
alert(data);
}
});
});
});
JS;
$this->registerJs($script, static::POS_END);
?>
I must be doing something wrong which I am not understanding
Any help would be highly appreciated.
first of all url:'$DCOurl' is correct and url must be in single or
double quotation. so you have a not found problem:
is your project in htdocs or www followed by /inventory-web/backend/ or there are some more directories? you use relative url so the url would be for ex: localhost/inventory-web/backend/web/ ...
ajax type 'POST' should match with behaviors['verbs']['actions'] if you have set it
check controller file name, class name and namespace
First, if you're serving an Ajax request you cannot do a redirect:
public function actionDco()
{
Yii::$app->response->format = Response::FORMAT_JSON;
$rv=[];
if(Yii::$app->request->isAjax && Yii::$app->request->post())
{
$data = explode(',',$_POST['data']);
$rv["infos"]=$data;
$rv["status"]='gotData';
}
else{
$rv["url"]=Url::to('index');
$rv["status"]='redirect';
}
return $rv;
}
About the JS error, instead of:
$.ajax({
url: $DCOurl,
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
alert(data);
}
});
Add the quotes aroun the $DCOurl and to manage the return value from the ajax call
$.ajax({
url: "$DCOurl",
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
if(data.status=='gotData'){
alert(data.infos);
}
if(data.status=='redirect'){
window.location.href=data.url;
}
}
});

AJAX and Codeigniter - Determining what button has been pressed to update

I have this shopping cart wherein I can add or subtract the quantity of a specific item. The problem is I don't know how to determine if the user has pressed the plus button or the minus button.
HTML code of the plus/minus
<td>
<div class="input-group" style="width: 100px !important;">
<span class="input-group-btn">
<button class="btn btn-danger btn-minus" type="button">-</button>
</span>
<input class="form-control table-shopping-qty" type="text" id = "<?php echo $cartrow['id']?>" value="<?php echo $cartrow['qty']?>" style="padding-left:5px;text-align: center;"/>
<span class="input-group-btn">
<button class="btn btn-success btn-plus" type="button">+</button>
</span>
</div><!-- /input-group -->
</td>
AJAX Function
function updateShoppingCart(){
var productid = $(".table-shopping-qty").attr("id");
dataString = {productid: productid};
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>"+"listproductscontroller/editcart_item",
data: dataString,
cache: false,
success: function(){
swal('Success!', 'Cart updated!', 'success');
}, error: function(){
swal('Oops!', 'Something went wrong. Please try again later', 'error');
}
});
}
Controller
public function editcart_item(){
$id = $this->input->post('productid');
if($this->session->userdata('cartsession')){
$cartsession = $this->session->userdata('cartsession');
foreach($cartsession as $row){
if($row['id'] == $id){
$updated = array('id'=>$row['id'], 'qty'=>$row['qty'] - 1);
}else{
$updated = array('id'=>$row['id'], 'qty'=>$row['qty']);
}
}
$this->session->set_userdata('cartsession', $updated);
}
if($this->session->userdata('cartsession')!=NULL){
if($this->cartdata = $this->ProductModel->getProductToCart($this->session->userdata('cartsession'))){
$this->session->set_userdata('globalcart', $this->cartdata);
}
}
}
load url helper in controller.using $this->load->url('url');.Then
function updateShoppingCart(){
var productid = $(".table-shopping-qty").attr("id");
dataString = {productid: productid};
$.ajax({
type: "POST",
url: "<?php echo base_url('listproductscontroller/editcart_item');?>",
data: dataString,
cache: false,
success: function(data){
alert("success");
}, error: function(){
alert("failed");
}
});
Don't forget to set
$_config['base_url'] ="your_domain_name";

"You did not select a file to upload. " get this error while uploading image using ajax

I am working with CodeIgniter and jQuery ajax. I want to upload image using ajax. But it shows an error like You did not select a file to upload.
Here,I have write jQuery :
jQuery(document).on('submit', '#signup_form', function()
{
//debugger;
var data = jQuery(this).serialize();
jQuery.ajax({
type : 'POST',
url : '<?php echo base_url()."front/ajax_register"; ?>',
data : data,
success : function(data)
{
jQuery(".result").html(data);
}
});
return false;
});
<form id="signup_form" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-3">Upload Photo</div>
<div class="col-md-4">
<input type="file" name="pic" accept="image/*">
</div>
</div>
<div class="row">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
And My function looks like this :
function ajax_register()
{
if($this->input->post())
{
$this->form_validation->set_rules('pass', 'Password', 'required|matches[cpass]');
$this->form_validation->set_rules('cpass', 'Password Confirmation', 'required');
if($this->form_validation->run() == true)
{
$img = "";
$config['upload_path'] = './uploads/user/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('pic'))
{
$data['error'] = array('error' => $this->upload->display_errors());
print_r($data['error']);exit;
$data['flash_message'] = "Record is not inserted";
}
else
{
$upload = $this->upload->data();
//print_r($upload);exit;
$data = array(
'ip_address' =>$this->input->ip_address(),
'first_name' =>$this->input->post('firstname'),
'last_name' =>$this->input->post('lastname'),
'phone' =>$this->input->post('phone'),
'email' =>$this->input->post('email'),
'group_id' =>$this->input->post('role'),
'password' =>$this->input->post('password'),
'image' =>$upload['file_name'],
'date_of_registration' =>date('Y-m-d')
);
print_r($data);exit;
$user_id = $this->admin_model->insert_user($data);
$user_group = array(
'user_id' => $user_id,
'group_id' => $this->input->post('role')
);
$this->admin_model->insert_group_user($user_group);
echo "<p style='color:red;'>You are successfully registerd.</p>";
}
}
else
{
echo "<p style='color:red;'>".validation_errors()."</p>";
}
}
}
So how to resolve this issue?What should I have to change in my code?
As I said, the problem is probably in the data you send to backend. If you want to submit AJAX with input file, use FormData.
Try this:
jQuery(document).on('submit', '#signup_form', function()
{
//debugger;
var data = new FormData($('#signup_form')[0]);
jQuery.ajax({
type : 'POST',
url : '<?php echo base_url()."front/ajax_register"; ?>',
data : data,
processData: false,
contentType: false,
success : function(data)
{
jQuery(".result").html(data);
}
});
return false;
});
Try this:
$('#upload').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'upload.php', // point to server-side PHP script
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
$('#pic').val(''); /* Clear the file container */
});
Php :
<?php
if ( $_FILES['file']['error'] > 0 ){
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}
?>
This will upload the file.
P.S.: Change the code as per CI method.
var data = jQuery(this).serialize();
this refers to document

My radio button does not get the value from the foreach loop and form validation returns 'field required' even if its checked?

i am using codeigniter. The validation error keeps saying 'chairman field required' although on element inspection there is a value given to the radio button. So i guess the problem is that the radio button input field is not seen.
Here is my view:
<form method="" action="" id="vote_results" >
<?php if (isset($vchairman_records)) : foreach ($vchairman_records as $v_chairman_row) : ?>
<input type="radio" id="chairman" name="chairman" value="<?php echo $chairman_row->registration_number ?>" />
<?php endforeach; ?>
<?php else : ?>
<p class="">No records were returned</p>
<?php endif; ?>
<button type="submit" class="btn btn-success btn-lg alert-info sb_button" id="vote">
<span id="sending_btn" style="display: none">Sending....</span>
<span class="" id="profesional-btn">Submit</span>
</button>
</form>
## My Controller ##
$this->form_validation->set_rules('chairman', 'Chairman', 'required|xss_clean');
if (!$this->form_validation->run() == FALSE) {
$data = array(
'success' => FALSE,
'errors' => validation_errors()
);
echo json_encode($dat
a);
Ajax
function loader_doc(v) {
if (v === 'on') {
$('#sending_btn').show();
$('#profesional-btn').hide();
} else {
$('#sending_btn').hide();
$('#profesional-btn').show();
}
}
$(document).ready(function () {
$('form#vote_results').submit(function (e) {
e.preventDefault();
loader_doc('on');
var vote_data = new FormData();
vote_data.append('chairman', $('#chairman').val());
$.ajax({
url: '<?php echo base_url('StartPageController/get_results'); ?>',
method: 'post',
contentType: false,
processData: false,
cache: false,
dataType: 'json',
data: vote_data,
success: function (data) {
if (!data.success) {
$('.n').modal('show');
$('.m').append(data.errors);
loader_doc('off');
} else {
alert(data.msg);
loader_doc('off');
}
loader_doc('off');
},
error: function () {
}
});
});
});
You are missing a semicolon in your echo $chairman_row->registration_number

Scroll to bottom of Div using jquery if Ajax returns success

I have this Div which includes the users messages where the newest message is right at the very bottom of the Div and initiates a scroll bar if the messages start to go lower than the div height:
<div class="list-group-message" style="overflow-y: scroll;height:385px;width:680px">
<div id="content">
/// My messages
</div>
</div>
And I am using Jquery from my js folder to bring the scroll bar to the bottom of the messages on Page load to show the newest message:
var $content = jQuery(".list-group-message");
$content.scrollTop($content[0].scrollHeight);
This works well, unless a new message is added to the page, the scroll bar won't automatically scroll down again unless you refresh the page or unless you add a new message. So you have to manually scroll down everytime you get a new message.
I am using an automatic Div reload script to show new messages:
<script>
setInterval(function() {
$("#content").load(location.href+" #content","");
}, 5000);
</script>
And I am using this Ajax script to add new replies:
<script>
function loadDoc() {
$.ajax({
url: 'system/reply_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
})
.done(function() {
$.ajax({
url: 'system/sars_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
})
.fail(function() {
console.log("error");
})
}
</script>
Is there a way I can set up the Jquery to run on success of my Ajax so that the scroll bar will be sent to the bottom upon a new message, something like this, which I have tried and found it doesn't work:
<script>
function loadDoc() {
$.ajax({
url: 'system/reply_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
})
.done(function() {
var $content = jQuery(".list-group-message");
$content.scrollTop($content[0].scrollHeight);
$.ajax({
url: 'system/sars_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
})
.done(function() {
console.log("success");
var $content = jQuery(".list-group-message");
$content.scrollTop($content[0].scrollHeight);
})
.fail(function() {
console.log("error");
})
})
.fail(function() {
console.log("error");
})
}
</script>
Additional code included as requested:
<div class="list-group-message" style="overflow-y: scroll;height:385px;width:680px">
<div id="content">
<?
$res6=mysqli_query($conn, "SELECT * FROM ap_messages WHERE conversation_id = '$conversation_id' ORDER BY time_sent ASC");
while($row6=mysqli_fetch_array($res6))
{
$me_message = $row6['message'];
$me_message_id = $row6['message_id'];
$me_sender_id = $row6['sender_id'];
$todaysdate = date('d/m/Y');
$me_time_sent_date = date('d/m/Y', strtotime($row6['time_sent']));
$me_time_sent_date_and_time = date('d/m/Y H:i:s', strtotime($row6['time_sent']));
$me_time_sent_time = date('H:i', strtotime($row6['time_sent']));
if($todaysdate == $me_time_sent_date){
$me_time = ''.$me_time_sent_time.'';
} else {
$me_time = ''.$me_time_sent_date.' '.$me_time_sent_time.'';
}
$me_time_read = $row6['time_read'];
$res7=mysqli_query($conn, "SELECT * FROM ap_users WHERE user_id = '$me_sender_id'");
while($row7=mysqli_fetch_array($res7))
{
$me_first_name = $row7['first_name'];
$me_last_name = $row7['last_name'];
$me_display_img = $row7['display_img'];
}
mysqli_query($conn, "UPDATE ap_messages SET time_read = NOW() WHERE message_id = '{$me_message_id}' AND time_read = '0000-00-00 00:00:00' AND conversation_id = '$co_conversation_id' AND sender_id != '$user_id'");
?>
<div class="media" style="max-width: <? echo $screenwidth; ?>px;">
<div class="media-left">
<a href="#">
<img src="userimg/<? echo $me_display_img; ?>" alt="user" width="64px" height="64px" hspace="10px" class="media-object" align="left">
</a>
</div>
<div class="media-body" style="position: relative !important;">
<div style="display:inline"><b><? echo ''.$me_first_name.' '.$me_last_name.''; ?></b></div> <div align="right" style="float:right; display:inline"> <? echo $me_time; ?> </div><br>
<? echo $me_message; ?>
</div>
</div>
<?
}
?>
</div>
</div>
<form action="" method="post" id="reply" name="reply" onsubmit="loadDoc()">
<div class="form-group">
<textarea class="form-control" rows="3" cols="80" id="message" name="message" placeholder="Send a reply..."></textarea>
<input type="hidden" id="conversation_id" name="conversation_id" value="<? echo $co_conversation_id; ?>">
<input type="hidden" id="sarssystem" name="sarssystem" value="<? echo $sarssystem; ?>">
<input type="hidden" id="user_id" name="user_id" value="<? echo $user_id; ?>">
</div>
<div class="form-group" align="right">
<div class="btn-group" align="left" style="float:left">
<button type="button" class="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="glyphicon glyphicon-cog" aria-hidden="true"></span> <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li>Delete Conversation</li>
<li>Visit Profile</li>
<li>Report User</li>
<li role="separator" class="divider"></li>
<li>Change Display Photo</li>
</ul>
</div>
<button type="reset" class="btn btn-default btn-sm">Cancel</button>
<button type="submit" class="btn btn-primary btn-sm">Send Message</button>
</div>
<script>
setInterval(function() {
$("#content").load(location.href+" #content","");
}, 5000);
</script>
<script>
function loadDoc() {
$.ajax({
url: 'system/reply_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
success: function(data) {
console.log("success");
var $content = $(".list-group-message");
$content[0].scrollTop = $content[0].scrollHeight;
// Second ajax
$.ajax({
url: 'system/sars_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
success: function(data) {
$content[0].scrollTop = $content[0].scrollHeight;
},
error: function(e) {
//called when there is an error
console.log('fail');
}
});
},
error: function(e) {
//called when there is an error
console.log('fail');
}
});
}
</script>
</div>
When your script is done, you can use the following script:
$content[0].scrollTop = $content[0].scrollHeight;
Example:
$.ajax({
url: 'system/reply_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
success: function(data) {
console.log("success");
var $content = $(".list-group-message");
$content.text(data); // Here you have to insert the received data.
$content[0].scrollTop = $content[0].scrollHeight;
// Second ajax
$.ajax({
url: 'system/sars_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
success: function(data) {
$content.text(data); // Here you have to insert the received data.
$content[0].scrollTop = $content[0].scrollHeight;
},
error: function(e) {
//called when there is an error
console.log('fail');
}
});
},
error: function(e) {
//called when there is an error
console.log('fail');
}
});
Hope it helps.
Try like this:
$.ajax({
url: 'system/sars_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
}),
success: function(response) {
console.log(response);
var $content = $(".list-group-message");
$content[0].scrollTop = $content[0].scrollHeight;
},
error: function(response) {
console.log(response);
}
});
This is the one that how I approached. First access the parent div that you want to load the data. Then scroll down using jquery.
$.ajax({
type: "GET",
url: baseURL + "notification/get_load_notif_member_message",
data: "member_id=" + member_id + "&message_id=" + message_id,
contentType: 'html',
success: function (html) {
$('.msg_history').html(html);
$("input[name='text']").val('');
var $content = $(".msg_history");
$content[0].scrollTop = $content[0].scrollHeight;
},
error: function (html) {
$('.msg_history').html('Something went wrong. Please try again.');
}
});

Categories