How to update the child div element on ajax success in php - 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);
}
});
})

Related

How to get CKEditor value in Codeigniter?

I Want to receive the values from the CKEditor. I Have written this HTML code
<div class="col-md-12">
<div class="form-group">
<label for="Image" class="control-label">Item Description </label>
<textarea id="item_description" name="item_description" rows="10" cols="80" style="resize:none"></textarea>
</div>
<!-- /.form-group -->
</div>
<div class="col-md-2">
<input type="submit" name="submit" id="Add" value="Add Items" class="btn btn-success">
</div>
This is the JQuery Code to get the value of the CKEditor
$("#Add").on("click", function(e) {
e.preventDefault();
var item_description = CKEDITOR.instances["item_description"].getData();
var formData = new FormData($("#form1")[0]); //It automatically collects all fields from form
$.ajax({
url: "'.base_url().'Home/add_items",
type: "post",
data: formData,
success: function(output) {
alert('Added'):
}
});
});
And this the Home controller but when I here access the item_description
value is empty.
<?php
class Home extends MY_Controller
{
public function add_items()
{
echo $title = $this->input->post('item_description');
//$this->show('admin/add_items.php');
}
}
?>
Modify your javascript codes, like this :
$("#Add").on("click", function(e) {
e.preventDefault();
var formData = new FormData($("#form1")[0]); //It automatically collects all fields from form
formData.append('item_description', CKEDITOR.instances['item_description'].getData());
$.ajax({
url: "<?=base_url()?>Home/add_items",
type: "post",
data: formData,
success: function(output) {
alert(output);
}
});
});

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

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>

Cannot post data with JQuery and Ajax

I'm new with php. I'm trying to post some input with ajax but it doesn't work.
This is my HTML for input:
<div class="form-group">
<h3>Answer:</h3>
<div class="input-group">
<textarea name="q1" id="q1" class="form-control" rows="4" ></textarea>
</div>
</div>
<button type="button" id="button" class="btn btn-primary btn-lg">Submit</button>
And this is my jquery function to post data:
$(function(){
$('button').click(function(){
var q1= $('#q1').val();
$.ajax({
type: 'post',
url: 'test.php',
data: {
q1: q1
},
success: function (response) {
console.log( response);
}
});
});
});
My test.php is a simple code to display the input:
<?php
$q1= $_POST['q1'];
echo $q1;
?>
I don't know why in my test.php I get this error : Notice: Undefined index: q1 in C:\xampp\htdocs\series\file\test.php on line 2
Can anyone tell me where is the issue?
First of all you are trying to post a json data to your php file so jQuery may not create correct payload for your request since you getting undefined index:q1. Can you try the code below;
$(function () {
$('button').click(function () {
var q1 = $('#q1').val();
$.ajax({
type : 'post',
url : 'test.php',
data : "q1="+q1,
success : function (response) {
console.log(response);
}
});
});
});
Try this:
$('document').ready(function(){
$("form#data").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: 'url',
type: 'POST',
data: formData,
async: false,
success: function (data)
{
alert(data);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
}
<form id="data" method="post">
<div class="form-group">
<h3>Answer:</h3>
<div class="input-group">
<textarea name="q1" id="q1" class="form-control" rows="4" ></textarea>
</div>
</div>
<input type="submit" id="button" class="btn btn-primary btn-lg">
</form>

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