id undefined when details are passed to a modal - javascript

I have a table of recipes created by a particular user, and when the pencil mark on each row of the table is clicked, a modal is displayed, showing the details of this particular recipe and it should allow the user to edit the recipe and save the updated version to the database. However, although the details are correctly being passed to the modal, the recipe id doesn't seem to be passed to the modal, since I have tried to output the recipe id into the console and it says the recipe id is undefined. I have tried to debug this error but to no avail. Can anyone provide any insight into why this might be?
//Recipe.js
$('.editThis').on('click', function() {
var recipe_id = $(this).attr('data-id');
var request = $.ajax({
url: "ajax/displayRecipe.php",
type: "post",
dataType: 'json',
data: {recipe_id : recipe_id}
});
request.done(function (response, textStatus, jqXHR){
console.log("response " + JSON.stringify(response));
$('#name').val(response.name);
$('#date').val(response.date);
});
});
$('#editRecipe').click(function() {
var recipe_id = $(this).attr('data-id');
var name_input = $('#name').val();
var date_input = $('#date').val();
var request = $.ajax({
url: "ajax/updateRecipe.php",
type: "post",
data: {name : name_input, date : date_input, recipe_id : recipe_id},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR){
console.log(response);
});
});
//Recipe.php
<?php
$recipeObject = new recipeList($database); //Lets pass through our DB connection
$recipe = $recipeObject->getUserRecipes($_SESSION['userData']['user_id']);
foreach ($recipe as $key => $recipes) {
echo '<tr><td>'. $value['name'].'</td><td>'. $value['date'].'</td><td>'.'<a data-id = '.$value['recip_id'].' data-toggle="modal" class="edit editThis" data-target="#editRecipe"><i class="fa fa-pencil"></i></a>'.'</td></tr>';
}
?>
// editRecipe Modal
<div id="recipe" class="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header recipe">
<h1 class="modal-title">Edit Recipe</h4>
</div>
<div class="modal-body">
<form method="post" id="updateRecipeForm">
<?php
require_once('classes/recipes.classes.php');
$recipeObject = new recipeList($database);
$recipe = $recipeObject->getRecipeDetails(recipe_id);
if(isset($_POST['submit'])) {
$updateRecipe = $recipeObject ->updateRecipe($_POST['name'], $_POST['date'], $_POST['recipe_id']);
if($updateRecipe) {
echo ("Your recipe has been updated!";
}
}
?>
<div class="form-group">
<input type="text" class="control-form" id="name" value = "<?php echo $recipe['name']; ?>">
</div>
<div class="form-group">
<input type="date" class="control-form" id="date" value = "<?php echo $recipe['date']; ?>">
</div>
</div>
<div class="form-group">
<input type="hidden" class="form-control" data-id=".$recipe['recipe_id']." id="recipe_id" name="recipe_id" value = "<?php echo $recipe['recipe_id']; ?>">
</div>
<button type="submit" class="btn recipe" id="editRecipe" data-dismiss="modal">Save</button>
</form>
</div>
</div>
</div>
</div>
//ajax - updateRecipe.php
<?php
require_once('../includes/database.php');
require_once('../classes/recipes.classes.php');
if($_POST['name'] && $_POST['date'] && $_POST['trans_id']){
$recipeObject = new recipeList($database);
echo $recipeObject->updateRecipe($_POST['name'], $_POST['date'], $_POST['recipe_id']);
}
?>
//recipes.classes.php
...
public function getRecipeDetails($recipeid){
$query = "SELECT * FROM recipe WHERE recipe_id = :recipe_id";
$pdo = $this->db->prepare($query);
$pdo->bindParam(':recipe_id', $recipeid);
$pdo->execute();
return $pdo->fetch(PDO::FETCH_ASSOC);
}
public function updateRecipe($name, $date, $recipe_id){
$query = "UPDATE recipe SET name = :name, date = :date WHERE recipe_id = :recipe_id";
$pdo = $this->db->prepare($query);
$pdo->bindParam(':name', $name);
$pdo->bindParam(':date', $date);
$pdo->bindParam(':recipe_id', $recipe_id);
$pdo->execute();
}

Try the following:
$(document).on('click', '.editThis',function() {...});
$(document).on('click','#editRecipe',function() {...});

Try this onclik function
Some time you cant get the apt value from this So Try this method.
we can use id but in your case you foreach the a tag so we cant repeat id. Hope Its Works
<a data-toggle="modal" class="recipe_<?php echo $value['recipe_id']; ?> edit editThis" onclick="editRecipe('<?php echo $value['recipe_id']; ?>')" ><i class="fa fa-pencil"></i></a>
function editRecipe(txt) {
var recipe_id = $('.recipe_'+txt).val();
var name_input = $('#name').val();
var date_input = $('#date').val();
var request = $.ajax({
url: "ajax/updateRecipe.php",
type: "post",
data: {name : name_input, date : date_input, recipe_id : recipe_id},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR){
console.log(response);
});
};

Related

Form doesn't insert into the database using codeigniter

I'm trying to create a one-page CRUD in CodeIgniter which only consist of not more than 5 fields. My problem is it doesn's insert its data in the database, I've been debugging this but I can't figure it out what is the problem. What did I miss?
Form:
<div class="col-md-4 col-sm-6 col-xs-12">
<div class="activity-item">
<form id="agencyForm" enctype="multipart/form-data" method="POST" class="form-horizontal">
<div class="form-body">
<input type="hidden" value="" name="agency_id" />
<div class="form-group">
<div class="col-md-12">
<input name="agency_name" id="agency_name" placeholder="Agency Name" class="form-control" type="text">
<?php echo form_error('agency_name','<span class="help-block">','</span>'); ?>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input name="category" id="category" placeholder="Category" class="form-control" type="text">
<?php echo form_error('category','<span class="help-block">','</span>'); ?>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input name="address" id="address" placeholder="Address" class="form-control" type="text">
<?php echo form_error('address','<span class="help-block">','</span>'); ?>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input name="acronym" id="acronym" placeholder="Acronym" class="form-control" type="text">
<?php echo form_error('acronym','<span class="help-block">','</span>'); ?>
</div>
</div>
</div>
<button type="submit" value="submit " id="btnSave" onclick="save(this.agencyForm); return false" class="btn btn-effect">Save</button>
</form>
</div>
<div class="clear"> </div>
Script:
<script type="text/javascript">
var save_method; //for save method string
var table;
$(document).ready(function() {
showAllAgency();
//datatables
table = $('#').DataTable({
"processing": true,
"serverSide": true,
"order": [],
"ajax": {
"url": "",
/*<?php echo site_url('agency/list')?>*/
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [{
"targets": [-1], //last column
"orderable": false, //set not orderable
}, ],
});
//set input/textarea/select event when change value, remove class error and remove text help block
$("input").change(function() {
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("textarea").change(function() {
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("select").change(function() {
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
});
function add_person() {
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
$('#modal_form').modal('show');
$('.modal-title').text('Add Agency');
}
function edit_person(id) {
save_method = 'update';
$('#form')[0].reset();
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url: "<?php echo site_url('agency/edit_agency/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data) {
$('[name="id"]').val(data.id);
$('[name="agency_name"]').val(data.agency_name);
$('[name="category"]').val(data.category);
$('[name="address"]').val(data.address);
$('[name="acronym"]').val(data.acronym);
$('#modal_form').modal('show');
$('.modal-title').text('Edit Agency');
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});
}
function reload_table() {
table.ajax.reload(null, false);
}
function save() {
$('#btnSave').text('saving...');
$('#btnSave').attr('disabled', true);
var url;
if (save_method == 'add') {
url = "<?php echo site_url('agency/save_c')?>";
} else {
url = "<?php echo site_url('agency/update_c')?>";
}
console.log($('#agencyForm').serialize());
// alert($(agencyForm).serialize());
$.ajax({
url: url,
// url: "<?php echo site_url('agency/save_c')?>",
type: "POST",
data: $('#agencyForm').serialize(),
dataType: "JSON",
success: function(data) {
if (data.status) {
alert('Successfully added the officer');
reload_table();
} else {
for (var i = 0; i < data.inputerror.length; i++) {
$('[name="' + data.inputerror[i] + '"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="' + data.inputerror[i] + '"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
}
});
}
function showAllAgency() {
$.ajax({
type: 'ajax',
url: '<?php echo base_url() ?>agency/getAgency',
async: false,
dataType: 'json',
success: function(data) {
var html = '';
var i;
for (i = 0; i < data.length; i++) {
html += '<tr>' +
'<td>' + data[i].agency_name + '</td>' +
'<td>' + data[i].category + '</td>' +
'<td>' + data[i].address + '</td>' +
'<td>' + data[i].acronym + '</td>' +
// '<td>'+
// 'Edit'+
// 'Delete'+
// '</td>'+
'</tr>';
}
$('#showagency').html(html);
},
error: function() {
alert('Could not get Data from Database');
}
});
}
</script>
Controller:
public function save_c() {
var_dump($this - > input - > post(NULL, TRUE));
$data = array(
'agency_name' => $this - > input - > post('agency_name'),
'category' => $this - > input - > post('category'),
'address' => $this - > input - > post('address'),
'acronym' => $this - > input - > post('acronym'),
);
$insert = $this - > agency - > save_now($data);
echo json_encode(array("status" => TRUE));
}
Model:
public function save_now($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
NOTE: It inserts data into the database when I change the URL like this:
$.ajax({
// url: url,
url: "<?php echo site_url('agency/save_c')?>",
this is the screenshot
You have ussue here. You haven't specify save_method anywhere. define save_method according to your logic or remove this if condition and assign insertion url directly
if (save_method == 'add') {
url = "<?php echo site_url('agency/save_c')?>";
} else {
url = "<?php echo site_url('agency/update')?>";
}
You can do insertion directly
url = "<?php echo site_url('agency/save_c')?>";

Jquery ajax Post is not working?

I have used ajax post without form. When I click submit button it should get the values of other fields. Post request is not being sent and neither output is being shown. It is returning this error Unexpected identifier
Here are the input fields
<input type="text" name="name" id="name" class="center-block Ename" placeholder="Enter you name">
<textarea class="center-block" name="message" id="message" rows="1" placeholder="Enter your message"></textarea>
<input class="center-block sendBtn" type="submit" id="submit" name="submit" value="Submit">
This is the ajax request.
$(document).ready(function(){
var interval = setInterval($('#submit').click(function(){
var values = {
'name': document.getElementById('name').value,
'message': document.getElementById('message').value
};
$.ajax({
type: "POST",
url: "chat.php",
data: values,
success: function(data){
$("#chat").html(data);
}
});
}),1000);
});
It is sending request to this php page
<?php
include 'db.php';
//Here post data is being assigned to variables
$name = $_POST['name'];
$message = $_POST['message'];
$queryInsert = "INSERT INTO chat(`name`, `message`) VALUES('$name', '$message')";
$queryInsertRun = mysqli_query($con, $queryInsert);
if(!$queryInsertRun){
echo mysqli_error($con);
}
//Here is the output which should be shown
$query = "SELECT * FROM `chat` ORDER BY `name` AND `message` DESC ";
$queryRun = mysqli_query($con, $query);
while($row = mysqli_fetch_assoc($queryRun)){
$name = $row['name'];
$message = $row['message'];
?>
<span class="name" style="font-weight: bold"><?php echo $name?>:</span>
<span class="message"><?php echo $message.'<br>'?></span>
<hr>
<?php
}
?>
I want to know that why is this not working.
try this code
function ajaxcall()
{
console.log('i am called');
var values = {
'name': document.getElementById('name').value,
'message': document.getElementById('message').value
};
$.ajax({
type: "POST",
url: "chat.php",
data: values,
success: function(data){
$("#chat").html(data);
}
});
}
$(document).ready(function(){
var id = setInterval(function() {
ajaxcall();
}, 1000);
});
http://jsfiddle.net/cod7ceho/116/
You want to display data if you clicked submit button , use simple click function . Using setInterval can't help you for clicking submit .
JS
$(document).ready(function(){
$('#submit').click(function(){
var values = {
'name': document.getElementById('name').value,
'message': document.getElementById('message').value
};
$.ajax({
type: "POST",
url: "chat.php",
data: values,
success: function(data){
$("#chat").html(data);
}
});
});
});
It sounds like your JSON Data is not valid.
var data = JSON.stringify(values);
var request = $.ajax({
url: "script.php",
method: "POST",
data: data,
dataType: "html" // read about dataType
});

Form action statement in PHP

I've got following problem with my PHP code:
my form is divided into two divs: first div shows up when the page is opened, second div displays after clicking a button (and this first one, thanks to Ajax, hides). My plan is to check a few statements, if true then create POST, get from it data and then dynamically create table, switching the content using Ajax again. BUT. I cannot use the 'action' thing because of the statements. When I've got 'submit' type - it creates POST, but reloads the page. If I replace it with 'button' type - Ajax works, but POST is empty.
Here's my code:
function formu ($w="1", $sr="on", $comma="",
$space ="", $other =""){?>
<form id="options" action="" method="POST" >
<div id = "first">
<h1 id = "title"> Choose a file </h1>
<input type = "radio" name="radio" id ="radio" value="op1" class ="radio"> ONE
<br>
<input type ="radio" name="radio" id="radio" value ="op2" class = "radio"> TWO
<br>
<input type ="radio" name="radio" id="radio" value="op3" class = "radio"> THREE
<br>
<input type = "button" id="Submit" Value = "Show">
</div>
<div id = "sec">
<h1 id = "title2"> Choose options </h1>
<p id="odwiersza"> Cut: </p>
<input type="text" name="w" value=""> <br>
<p id="Separators"> Separator: </p>
<input type = "checkBox" name="sr"> sr
<input type= "checkBox" name="comma"> comma
<input type = "checkBox" name = "space"> space
<input type = "checkBox" name ="other"> other (which?) <input type="text" name="such">
<br>
<input type="submit" id="choose" value = "Enter">
</div>
</form>
<?php }
formu();
?>
<div id= "here"> </div>
And then my ideas:
if($_SERVER["REQUEST_METHOD"] == "POST"){
$w = $_POST['w'];
$sr = $_POST['sr'];
$comma = $_POST['comma'];
$space = $_POST['space'];
$other = $_POST['other'];
if (empty($w) || !($sr || $comma || $space || $other)){
echo "You have to enter the number and choose at least one separator!";
} else {
**/* here I've tried:
?> <script>
window.location = 'third.php'; //but it doesn't create POST table
</script>
<?php
require_once("third.php"); //but it attaches value with reloading the page, so first div shows up above my table
include "third.php"; //same as above
*/**
}
}
I've also tried Ajax script but it doesn't work as well:
<script>
var SubmitBtn2 = document.getElementById('choose');
SubmitBtn2.onclick = function(){
var formularz = document.getElementById('sec');
formularz.style.display = 'none';
var formularz1 = document.getElementById('first');
formularz1.style.display = 'none';
var title2 = document.getElementById('title2');
$(title2).hide();
var FormData = {plik: "<?php echo $_POST['radio']; ?>",
wiersz: "<?php echo $_POST['w']; ?>",
średnik: "<?php echo $_POST['sr']; ?>",
przecinek: "<?php echo $_POST['comma']; ?>",
spacja: "<?php echo $_POST['space']; ?>",
inne: "<?php echo $_POST['other']; ?>",
jakie: "<?php echo $_POST['such']; ?>"};
$(document.getElementById('back')).hide();
$.ajax({
type: 'POST',
url: "third.php",
data: FormData,
complete: function (reply) {
$.ajax({
type: 'POST',
url: "third.php",
complete: function (reply) {
$('here').append(reply);
}
});
}
});
}
</script>
EDIT:
I've tried to use event.preventDefault(); and now my code looks as below:
$(document.getElementById('choose')).click(function()
{ event.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "POST",
data: $(this).serialize(),
success: function (data) {
$.get("test5new.csv", function(data) {
var build = '<table border="1" cellpadding="2" cellspacing="0" width="100%">\n';
var rows = data.split("\n");
var cut = rows.slice(<?php echo $w; ?>); //ponieważ tablice liczy się od 0
cut.forEach( function getvalues(thisRow) {
build += "<tr>";
var columns = thisRow.split("<?php echo $pattern; ?>");
for(var i=0;i<columns.length;i++){ build += "<td>" + columns[i] + "</td>"; }
build += "</tr>";
})
build += "</table>";
$(document.getElementById('wrap')).append(build);
});
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
but, although it does not refresh, it doesn't create POST neither. Please please help.

codeigniter get ajax post files

am trying to upload multiple files using ajax in codeigniter. my ajax post is working fine but i don't know how to get the post files in my controller.
I tried this way but its not working. please help. Thank you.
HTML
<form method="post" name="upload_files" action="<?php echo base_url(); ?>home/upload_files" id="form_files" enctype="multipart/form-data">
<h4 style="float: left">Add files. (file types .png, .jpeg, .dwg, .pdf, jpg) max: 10Mb <span style="color:red;" id ="err_type"> * </span></h4>
<div class=from-section>
<div class="row">
<div class="span4" id="image" >
<div class="cart-total" id="clone_image" data-provides="fileupload">
<div class="form-group has-success has-feedback">
<input class="form-control" type="file" name="files[]" accept="image/*" />
</div>
</div>
</div><!-- /.span4 -->
</div><!-- /.row -->
</div>
<div class="cart-total">
<a id="another_image" class="btn btn-default" style="height: 45px;padding: 12px 12px; margin-right: 10px; ">+ Add More Files</a>
<a id="submit_files" class="rx-bottom" >Submit Files</a>
</div>
</form>
AjAX
<script type="text/javascript">
$('#submit_files').click(function() {
var formData = new FormData($('#form_files')[0]);
$.ajax({
url: "<?php echo base_url('home/upload_files/'); ?>",
type: "POST",
data: formData,
mimeType: "multipart/form-data",
processData: false,
contentType: false,
success: function(res) {
console.log("success");
},
error: function(res) {
console.log("error");
}
});
});
</script>
My console is logging success message
CONTROLLER
public function upload_files(){
$order_id = 123;
if(!$order_id){
redirect('home/instant_quote', 'refresh');
}else{
$this->load->library('upload');
//$files = $this->input->post();
$files = $_FILES;
if($files){
for( $i = 1; $i < 20; $i++) {
$config = array();
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|jpeg|png|pdf|dwg|zip';
$config['max_size'] = '11000';
$config['file_name'] = 'order_'.$order_id.'_'.$i;
$config['overwrite'] = false;
$this->upload->initialize($config);
$this->upload->do_upload('files'.$i);
$image_data = array('upload_data' => $this->upload->data());
if($image_data["upload_data"]["file_size"]){
$inserted['order'] = $i ;
$inserted['name'] = $image_data["upload_data"]["file_name"];
$inserted['extension'] = $image_data["upload_data"]["file_ext"];
$inserted['type'] = $image_data["upload_data"]["file_type"];
$inserted['size'] = $image_data["upload_data"]["file_size"];
$prop = $this->home->insert_files($inserted);
}
}
}else{
$this->load->view('comman/header.php');
$this->load->view('home/add_files.php');
$this->load->view('comman/footer.php');
}
}
}
This is what i see when i log the form data
You can use this in your controller:
function upload(){
if(!empty($_FILES)){
$type= $_FILES["files0"]["type"]; //files0 is your input file name
$size= $_FILES["files0"]["size"];
$file_name = $_FILES["files0"]["name"];
$source = $_FILES['files0']['tmp_name'];
$dir = "./uploads/";
$file = $dir . $file_name;
if(!file_exists ($file ))
{
move_uploaded_file($source,$file );
exit("File has been uploaded");
}
else
{
echo "File exist";
}
}
$this->load->view('v_test');
}
And for your ajax jquery:
//add this to your head html
<script>
var base_url = "<?php echo base_url(); ?>";
</script>
and, this is your ajax call :
$("#submit_files").click(function() {
var formData = new FormData($("#form_files")[0]);
$.ajax({
url: base_url + "home/upload_files",
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Please test with single file first, and if it worked. Try to dynamically upload multiple files. Hope this help you out. :D

I Cannot get comment reply by Ajax under comment without refresh

I Cannot get comment reply by Ajax under comment, But reply saved in database and If i refresh Index.php page, it display correctly. So I think my problem either in my reply display element(Div id/class or php) OR Ajax call back.
Please help me. I can't do anything last 7 days about this.
my Index.php framework
$results = mysqli_query($dbh,"SELECT * FROM comments_lite WHERE qazi_id='$tutid' ORDER BY id DESC LIMIT 20") or die(mysqli_error($dbh));
echo'<div class="content"><comment>';
while($rows = mysqli_fetch_array($results)) {
$id = $rows['id'];
$username = $rows['username'];
//etc all
echo'<div class="post'.$id.'">
//Comments goes here
echo'<p class="name">'.$username.' Says:</p>';
echo'<span class="cdomment_time">'.$date.'</span><br/>
<div class="avatarcnt">
<img alt="" src="uploadprofile/'.$u_imgurl.'"/>
</div>
<div class="cdomment_text">';
echo'.htmlentities($description).'<br>';
echo'</div>';
// Reply Start
$query = "SELECT * FROM comments_reply WHERE parent_id ='".$id."'";
$res = mysqli_query($dbh,$query);
while($row = mysqli_fetch_array($res)){
$parent_id = $row['parent_id'];
$username = $row['username'];
//etc all
echo'<div class="rcontent"><replycomment><div class="reply'.$parent_id.'"><ul>
//Reply goes here
echo'<p class="name">'.$username.' Says:</p>';
echo'<span class="cdomment_time">'.$date.'</span><br/>
<div class="avatarcnt">
<img alt="" src="uploadprofile/'.$u_imgurl.'"/>
</div>
<div class="cdomment_text">';
echo'.htmlentities($description).'<br>';
</ul></div><replycomment></div>';
} //reply while close
} //comment while close
echo'<comment></div>';
my reply.php framework
$results = mysqli_query($dbh,"SELECT * FROM comments_lite WHERE qazi_id='$tutid' ORDER BY id DESC LIMIT 1") or die(mysqli_error($dbh));
$row = $results->fetch_array();
$id = $row['id'];
$res = mysqli_query($dbh,"SELECT * FROM comments_reply WHERE parent_id ='$id' LIMIT 1") or die(mysqli_error($dbh));
while($row = mysqli_fetch_array($res)) {
$parent_id = $row['parent_id'];
$username = $row['username'];
echo'<div class="rcontent"><replycomment><div class="reply'.$parent_id.'"><ul>';
//New reply goes here
echo'<p class="name">'.$username.' Says:</p>';
echo'<span class="cdomment_time">'.$date.'</span><br/>
<div class="avatarcnt">
<img alt="" src="uploadprofile/'.$u_imgurl.'"/>
</div>
<div class="cdomment_text">';
echo'.htmlentities($description).'<br>';
echo'</ul></div><replycomment></div>';
JavaScript { here $tutid is a page id, which work well ( If u have any confusion about this )}
$(document).ready(function(){
var inputReplycom = $(".replycom");
var inputTutid = $("#tutid");
var inputparent_id = $("#parent_id");
var commentList = $(".content > comment"); // update comment
//update reply
function updateReplybox(){
var tutid = inputTutid.attr("value");
**(EDITED)** var RID = inputparent_id.attr("value");
$.ajax({
type: "POST",
url: "reply.php",
data: "action=update&tutid="+ tutid,
complete: function(data){
**(EDITED)**
$(".postreply"+RID).append(data.responseText);
$(".postreply"+RID).fadeIn(2000);
}
});
}
//on submit reply
$(".replyfrm").click(function(){
var replycom = inputReplycom.attr("value");
var parent_id = inputparent_id.attr("value");
var tutid = inputTutid.attr("value");
$(".loader").fadeIn(400);
$.ajax({
type: "POST",
url: "reply.php",
data: "action=insert&replycom="+ replycom + "&parent_id="+ parent_id + "&tutid="+ tutid,
complete: function(data){
$(".reply_here").hide();
updateReplybox();
}
});
//we prevent the refresh of the page after submitting the form
return false;
});
});
EDITED:
New Edited Code that I am trying now which display fadeIn a blank result before refresh
In index.php change:
<div class="postreply'.$parent_id.'"><ul>
In reply.php change:
<div class="postreply'.$parent_id.'"><ul>
JavaScript change
function updateReplybox(){
var tutid = inputTutid.attr("value");
var RID = inputparent_id.attr("value");
//just for the fade effect
$.ajax({
type: "POST",
url: "reply.php",
data: "action=update&tutid="+ tutid,
complete: function(data){
$(".postreply"+RID).append(data.responseText);
$(".postreply"+RID).fadeIn(2000);
}
});
}
The following will be your js
$('#commentButton').click(function() {
replycom = document.getElementById('inputReplycom').value;
parent_id = document.getElementById('inputparent_id').value;
tutid = document.getElementById('inputTutid').value;
$.post('reply.php', {'replycom': replycom, 'parent_id': parent_id, 'tutid': tutid}, function(data) {
var parsed = JSON.parse(data);
var html = '<section class="comment-list block"><article id="comment-id-1" class="comment-item"> <a class="pull-left thumb-sm"> <img src="/uploads/' + parsed.photo +'" class="img-circle"> </a> <section class="comment-body m-b"> <header> <strong>'+parsed.username+'</strong> <span class="text-muted text-xs block m-t-xs">'+parsed.created_at.date+' </span> </header> <div class="m-t-sm">'+ parsed.comment +'</div></section> </article> </section>';
$('#extraComments').append(html);
}).success(function() {
$('#comment').val('');
$('#commentSuccess').html('Submitted successfully!').show().delay(5000).fadeOut();
}).fail(function() {
$('#commentFailed').html('Failed!').show().delay(5000).fadeOut();
});
});
in your reply.php get the data
$replycom = $_GET['replycom'];
$parent_id = $_GET['parent_id'];
$tutid = $_GET['tutid'];
//and process it
Please change the var names accordingly
Edited code :
echo json_encode(array('replycom' => $replycom, 'parent_id' => $parent_id, 'tutid' => $tutid));

Categories