Ajax keeps refreshing the entire page instead of just the comment section - php

I'm working on a project with codeigniter and I decided to implement ajax into the comment section so that the whole page is not refreshed when the user submits his comment. The comment is displayed automatically but the page keeps getting refreshed. I don't know what I am doing wrong here but any help would be appreciated.
MODEL:
public function create_comments($post_id){
$data = array(
'post_id' => $post_id,
'body' => $this->input->post('body'),
'users_id' => $this->session->userdata('user_id')
);
return $this->db->insert('comments',$data);
}
CONTROLLER:
public function create($post_id){
//checking if user is logged in
if(!$this->session->userdata('isLoggedIn')){
redirect('users/login');
}
$slug = $this->input->post('slug');
$data['post'] = $this->post_model->get_posts($slug);
$this->form_validation-> set_rules('body', 'Comment', 'required');
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header');
$this->load->view('posts/view', $data);
$this->load->view('templates/footer');
$this->session->set_flashdata('comment_error', 'comment field is empty comment');
redirect('posts/'.$slug,'refresh');
} else {
$this->comments_model->create_comments($post_id);
redirect('posts/'.$slug);
}
}
VIEW:
<?php echo form_open_multipart('comments/create/'.$post['id'], 'id="comnt"'); ?>
<div class="panel-footer">
<!--//THIS IS THE FIELD WHICH COMMENTS WOULD BE ADDED-->
<div class="">
<input type="hidden" name="slug" value="<?php echo $post['slug']; ?>">
<small class="text-center text-danger"><?php echo form_error('body'); ?></small>
<div class="input-field">
<textarea id="icon_prefix2" name="body" class="materialize-textarea" rows="3"></textarea>
<label for="icon_prefix2">Comments</label>
</div>
<button class="btn waves-effect waves-light" type="submit" name="action" id="submit">comment <i class="material-icons right">send</i></button>
</div>
</div>
</form>
AJAX:
$('#submit').click(function() {
var form_data = {
body: $("#icon_prefix2").val()
};
$.ajax({
url: "<?php echo base_url();?>comments/create",
type: "POST",
data: form_data,
success: function(msg) {
alert("msg");
}
});
return true;
});

Use jquery preventDefault() function to prevent your form to be submitted
$('#submit').click(function(e) {
e.preventDefault();
var form_data = {
body: $("#icon_prefix2").val()
};
$.ajax({
url: "<?php echo base_url();?>"+"comments/create",
type: "POST",
data: form_data,
success: function(msg) {
alert("msg");
}
});
return true;
});

Try the done property to set the success handler. Also, as this is an event over a DOM element, you should attach it when the DOM is ready:
$(document).ready(function() {
$('#submit').click(function(event) {
var form_data = {
body: $("#icon_prefix2").val()
};
$.ajax({
url: "<?php echo base_url();?>comments/create",
type: "POST",
data: form_data,
}).done(function(msg) {
alert(msg);
}).fail(jqXHR, textStatus) {
alert('ERROR: ' + textStatus);
});
// return is not necessary here
// return true;
});
$("#comnt").submit(function(e) { // Prevent the form submitting
e.preventDefault();
});
});
As this already attaches an event, you should remove the onclick="comment()" property from your button:
<button class="btn waves-effect waves-light" type="submit" id="submit">comment
<i class="material-icons right">send</i>
</button>

Try this hope it work
$('#submit').click(function(event) {
e.preventDefault(); //stop actual action of browser
var form_data = {
body: $("#icon_prefix2").val()
};
$.ajax({
url: "<?php echo base_url();?>comments/create",
type: "POST",
data: form_data,
success: function(msg) {
alert("msg");
}
});
return true;
});
Change button type button instead of submit
<button class="btn waves-effect waves-light" type="button" name="action" id="submit">comment
<i class="material-icons right">send</i>
</button>

Related

How to update the child div element on ajax success in php

I want to update the child div but all the divs are getting updated on ajax success.
My html
<div class="add_wishlist">
<input type="hidden" name="prd_wishlist" class="prd_wishlist" value="1">
<div class="wishlist_icon">
<p><i class="far fa-heart"></i></p>
</div>
</div>
<div class="add_wishlist">
<input type="hidden" name="prd_wishlist" class="prd_wishlist" value="2">
<div class="wishlist_icon">
<p><i class="far fa-heart"></i></p>
</div>
</div>
Jquery
$('.add_wishlist').click(function(){
var prd_wish = $(this).find("[name='prd_wishlist']").val()
$.ajax({
type: 'post',
url: weburl+'pages/login-script.php',
data: {
prd_wish:prd_wish,
wishlist_submit:'submit',
},
success: function (response) {
$('.add_wishlist').children('.wishlist_icon').html(response)
}
});
})
I also tried to update the code with $('.add_wishlist').children('.wishlist_icon').html(response) but its not working.
Store a reference to the clicked .add_wishlist element in the click handler, then use that within the success handler:
$('.add_wishlist').click(function() {
let $addWishlist = $(this);
let prd_wish = $addWishlist.find("[name='prd_wishlist']").val()
$.ajax({
type: 'post',
url: weburl + 'pages/login-script.php',
data: {
prd_wish: prd_wish,
wishlist_submit: 'submit',
},
success: function(response) {
$addWishlist.children('.wishlist_icon').html(response);
}
});
})

Jquery redirect to another page

I'm trying to make an update status button which it's submited by ajax, but every single time when I update the status I get redirected on base_url().'/Admin/Jobs/'. It's possible to update the status without getting that redirect?
Code:
<?php if ($key['status'] === '1'): ?>
<?php echo form_open('Admin/update_job_status'); ?>
<input type="hidden" name="id" value="<?= $key['id'] ?>">
<input type="hidden" name="status" value="0">
<button class="btn btn-success btn-simple" id="submit" rel="tooltip" title="Status Active">
<i class="fas fa-eye"></i>
</button>
<?php echo form_close(); ?>
<script>
$(document).ready(function(){
$('#submit').on('click', function(){
var formData = {
'id' : $('#id').val(),
'status' : $('#status').val()
}
$.ajax({
type: 'post',
data: formData,
url: '<?php echo base_url().'/Admin/Jobs/' ?>',
success: function(data){
alert(id);
},
});
});
});
</script>
<?php endif ?>
<?php if (is_null($key['status']) || $key['status'] === '0'): ?>
<?php echo form_open('Admin/update_job_status'); ?>
<input type="hidden" name="id" value="<?= $key['id'] ?>">
<input type="hidden" name="status" value="1">
<button class="btn btn-warning btn-simple" rel="tooltip" title="Status Inactive">
<i class="fas fa-eye-slash "></i>
</button>
<?php echo form_close(); ?>
<script>
$(document).ready(function(){
$('#submit').on('click', function(){
var formData = {
'id' : $('#id').val(),
'status' : $('#status').val()
}
$.ajax({
type: 'post',
data: formData,
url: '<?php echo base_url().'/Admin/Jobs/' ?>',
success: function(data){
alert(id);
},
});
});
});
</script>
<?php endif ?>
You submit event is sent, because it is not stopped. You have to use event.stopPropagation() to prevent "natural" form submit.
$('#submit').on('click', function(event) { // add event parameter
event.preventDefault(); // stop form submit
//...
A button in a form by default is a submit button and if you click on it it will post your form back to the specified url.
You can explicitly set your button to be a normal button by setting the type attribute to button
<button type="button"...
or you can prevent the form from submitting via JavaScript in the event handler
$('#submit').on('click', function(event){
event.preventDefault();// prevents the default action, which is submitting the html form
...
Try this
$(document).ready(function(){
$('#submit').on('click', function(){
var formData = {
'id' : $('#id').val(),
'status' : $('#status').val()
}
$.ajax({
type: 'post',
data: formData,
url: '<?php echo base_url().'/Admin/Jobs/' ?>',
success: function(data) { alert(id); },
});
return false; // disable form submit
}); });

php can't get multiple ajax submit data

I have a form and it have 2 submit button.
<form name="posting" id="posting" method="post" action="posting_bk.php" role="form">
<input type="text" name="title" id="title" class="form-control" required="required">
....some form fields...
<input class="btn btn-home" type="submit" name="publish" id="publish" alt="Publish" value="Preview and Post" />
<input class="btn btn-home" type="submit" name="save" id="save" onclick="return confirm('Are you sure you want to Submit.')" alt="Save" value="Save as Draft" /></center>
</form>
i am using ajax to send/receive data.
$('#posting input[type="submit"]').on("click", function(e) {
e.preventDefault;
var btn = $('#publish');
var el = $(this).attr('id');
$.ajax({
type: 'post',
url: $('form#posting').attr('action'),
cache: false,
dataType: 'json',
data: {
data: $('form#posting').serialize(),
action: el
},
beforeSend: function() {
$("#validation-errors").hide().empty();
},
success: function(data) {
if (data.success == false) {
var arr = data.errors;
$.each(arr, function(index, value) {
if (value.length != 0) {
$("#validation-errors").append('<div class="alert alert-danger"><strong>' + value + '</strong><div>');
}
});
$("#validation-errors").show();
btn.button('reset');
} else {
$("#success").html('<div class="alert alert-success">Basic details saved successfully. <br> If you want to edit then please goto Edit. <div>');
$('#title').val('');
}
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
btn.button('reset');
}
});
return false;
});
this is my php file. posting_bk.php
if ($_POST['action'] == 'publish') {
if($title == 'test'){
array_push($res['errors'], 'data received by php.');
}else{
array_push($res['errors'], 'No data received by php.');
}
$res['success'] = true;
echo json_encode($res);
}
elseif ($_POST['action'] == 'save') {
array_push($res['errors'], 'Save button clicked.');
$res['success'] = true;
echo json_encode($res);
}
All the time if i click on publish button i am getting
No data recived by php
When I check in firebug it is showing data under post.
Like this
action publish
data title=test&
I am not sure what am i doing wrong here. Please advise.
Change the AJAX call to use:
data: $('form#posting').serialize() + '&action=' + el,\
Then access the parameter using
$title = $_POST['title'];
The way you're doing it, the form data is being nested a level down in the POST data, so you would have had to do:
$data = parse_str($_POST['data']);
$title = $data['title'];

how to find a parent?

i have a problem with finding parent for form in this code:
<li class="comment<?php echo $comment[id]?>">
<div class="comment-content">
<div class="comment-top">
<div class="comment-nme">
<?php echo $comment[name]?>
</div>
<div class="comment-dt">
<?php echo $comment[dt]?>
</div>
</div>
<div class="comment">
<?php echo $comment[comment]?>
</div>
<a class="reply" href="#comment<?php echo $comment[id]?>">Ответить</a>
</div>
<div class="answer-form">
<form method="post" name="answer-form" class="ans">
<textarea class="comment-textarea" name="comment"></textarea>
<div class="a-comment-inputs">
<input type="hidden" name="parent_id" value="<?php echo $comment[id]?>">
<input type="hidden" name="status" value="new">
<div class="a-comment-name">
Имя</br>
<input type="name" name="name" class="a-comment-name">
</div>
<div class="a-comment-email" >
Eмейл</br>
<input type="email" class="a-comment-email" name="email">
</div>
</div>
<div class="comment-apply">
<button value="submit" onclick="return sendDataChild();" class="answer-but">Добавить</button>
</div>
</form>
</div>
<?php if($comment[childs]){ ?>
<ul class="commentsRoot<?php echo $comment[id]?>">
<?php echo commentsString($comment[childs]) ?>
</ul>
<?php } ?>
</li>
i use this jQuery function:
function sendDataChild() {
var form = $('FORM[name=answer-form]');
var data = form.serialize();
$.ajax({
type: "POST",
url: "req.php",
dataType: "json",
data: data,
cache: false,
success: function (data) {
form[0].reset();
},
error: function (xhr, str) {
alert('Возникла ошибка: ' + xhr.responseCode);
}
//$("#messageModalDialog").text(resultStat).show();
});
return false;
};
but it select every form that find on button click.
Can somebody advise how to solve it?
one possible solution
<button value="submit" onclick="return sendDataChild(this);" class="answer-but">Добавить</button>
then
//pass the clicked button reference then find the parent form of the button
function sendDataChild(btn) {
var form = $(btn).closest('FORM[name=answer-form]');
var data = form.serialize();
$.ajax({
type: "POST",
url: "req.php",
dataType: "json",
data: data,
cache: false,
success: function (data) {
form[0].reset();
},
error: function (xhr, str) {
alert('Возникла ошибка: ' + xhr.responseCode);
}
//$("#messageModalDialog").text(resultStat).show();
});
return false;
};
Bind submit event on the form and pass the object to the form object to your method
$(document).ready(function(){
$("form[name='answer-form']").on('submit', function(){
sendDataChild($(this));
});
});
function sendDataChild(form) {
var data = form.serialize();
$.ajax({
type: "POST",
url: "req.php",
dataType: "json",
data: data,
cache: false,
success: function (data) {
form.reset();
},
error: function (xhr, str) {
alert('Возникла ошибка: ' + xhr.responseCode);
}
//$("#messageModalDialog").text(resultStat).show();
});
return false;
};

Ajax is getting called only for first button

<?php $count = 1; foreach ($settings[$slug] as $slug): ?>
<div data-toggle="buttons-radio" class="btn-group">
<button id="enable" value="1" class="btn btn-success active" type="button" name="includeicon"><i class="icon-ok icon-white"></i></button>
<button id="disable" value="0" class="btn" type="button" name="includeicon"><i class="icon-remove"></i></button>
</div>
<?phpendforeach?>
$(document).ready(function(){
$("#enable").click(function(event) {
var slugid = $('#slugid').val();
$.ajax({
url: SITE_URL + 'admin/PluginConf/enable/?'+slugid,
type: "POST",
data : {'slugid' : slugid},
success: function(data) {
}
});
});
$("#disable").click(function(event) {
var slugid = $('#slugid').val();
$.ajax({
url: SITE_URL + 'admin/PluginConf/disable/?'+slugid,
type: "POST",
data : {'slugid' : slugid},
success: function(data) {
}
});
});
});
I am passing button id in jquery, but ajax is getting called only for first button. For second and others it is not getting called, can anyone help me out in this?
Thanks
You have an id of enable and disable in a foreach. If the loop ever executes more than once you will then have multiple buttons with the same id. IDs have to be unique! Rather use something else to identify the click:
I suggest adding an enable class to the enable button and a disable class to the disable button, then catch the events like this:
$('.enable').click(function() {
// code in here
});
$('.disable').click(function() {
// code in here
});
Don't bind the click event(s) for multiple items by id! Ids have to be unique idetifiers.
<?php $count = 1; foreach ($settings[$slug] as $slug): ?>
<div data-toggle="buttons-radio" class="btn-group">
<button value="1" class="enable btn btn-success active" type="button" name="includeicon"><i class="icon-ok icon-white"></i></button>
<button value="0" class="btn disable" type="button" name="includeicon"><i class="icon-remove"></i></button>
</div>
<?phpendforeach?>
$(document).ready(function(){
$(".enable").click(function(event) {
var slugid = $('#slugid').val();
$.ajax({
url: SITE_URL + 'admin/xervPluginConf/enable/?'+slugid,
type: "POST",
data : {'slugid' : slugid},
success: function(data) {
}
});
});
$(".disable").click(function(event) {
var slugid = $('#slugid').val();
$.ajax({
url: SITE_URL + 'admin/xervPluginConf/disable/?'+slugid,
type: "POST",
data : {'slugid' : slugid},
success: function(data) {
}
});
});
});
You are using id what is not correct when several elements in your case buttons have the same id.When you use foreach loop you create multiple buttons with the same particular id. ID means that something is unique, and only one element can have that specyfic id. I assume you should make a class for this buttons and change your script code with having this in mind. Here what I suggest. Hope it helps.
<?php $count = 1; foreach ($settings[$slug] as $slug): ?>
<div data-toggle="buttons-radio" class="btn-group">
<button value="1" class="btn btn-success active enable" type="button" name="includeicon"><i class="icon-ok icon-white"></i></button>
<button value="0" class="btn disable" type="button" name="includeicon"><i class="icon-remove"></i></button>
</div>
<?php endforeach; ?>
$(document).ready(function(){
$(".enable").click(function(event) {
var slugid = $('#slugid').val();
$.ajax({
url: SITE_URL + 'admin/xervPluginConf/enable/?'+slugid,
type: "POST",
data : {'slugid' : slugid},
success: function(data) {
}
});
});
$(".disable").click(function(event) {
var slugid = $('#slugid').val();
$.ajax({
url: SITE_URL + 'admin/xervPluginConf/disable/?'+slugid,
type: "POST",
data : {'slugid' : slugid},
success: function(data) {
}
});
});
});

Categories