Appending jQuery AJAX response to an existing DIV - php

This the HTML code that displays the first two comments in my site. I want if a user clicks on the Load more comments button, it should load the fetched comments that is returned via the jQuery AJAX and append it to the two divs in .comment_data div but it is not working even though the AJAX seems to be returning the expected result.
This is the HTML code:
<div class = 'feeds'>
<div class = 'comments'>
<div class = 'comment_data>
<div class = 'per_comment'>
<p> slideToggle!</p>
</div>
<div class = 'per_comment'>
<p> classToggle!</p>
</div>
<button class='morecomments' value='7' name = 'more' type='submit'>
Load more comments</button>
</div>
</div>
</div>
And this is the AJAX code:
$(".morecomments").click(function () {
var post_id = $(this).val();
var request = $.ajax({
url: "comments.php",
type: "POST",
data: { post : post_id },
dataType: "html"
});
request.done(function( msg ) {
$(this).prev('.per_comment').html( msg );
});
});
And the comments.php code:
if(isset($_POST['post']) )
{
$post_id = $_POST['post'];
$qry = "SELECT user_id, comment FROM comments WHERE post_id = ? ORDER BY time DESC LIMIT 1, 1000";
$q = $conn->prepare($qry) or die("ERROR: " . implode(":", $conn->errorInfo()));
$q->bindParam(1, $post_id);
$q->execute();
if($commentz = $q->fetchAll()){
foreach ($commentz as $comment){
echo "<div class = 'per_comment'>";
echo "<p>". $comment[0] ." ". $comment[1] . "</p>";
echo "</div>";
}
}
}

Try the following:
$(".morecomments").click(function () {
var $this = $(this);
var post_id = $(this).val();
var request = $.ajax({
url: "comments.php",
type: "POST",
data: { post : post_id },
dataType: "html"
});
request.done(function( msg ) {
$this.prev('.per_comment').html( msg );
});
});

this isn't what you think it is. Try setting the context property of the ajax options:
$(".morecomments").click(function () {
var post_id = $(this).val();
var request = $.ajax({
url: "comments.php",
type: "POST",
data: {
post: post_id
},
dataType: "html",
context: this
});
request.done(function (msg) {
$(this).prev('.per_comment').html(msg);
});
});

Related

Passing Variable Value from PHP to Ajax and Changing Attribute Value in HTML

My PHP is returning this data to Ajax...
echo $data6['favorite_properties_id'];
I am updating it in one function and trying to send it to another using following html and jquery .
<img class="<?php if($favorite == 1){ echo 'alreadyfavorite';} else { echo 'addtofavorite';} ?>" pid="<?php echo $propertyid; ?>" fpid="<?php while($data5=$select5->fetch()){echo $data5['favorite_properties_id'];} ?>" src="../images/system/addtofavorite.png">
This is my jquery...
$('.alreadyfavorite1').click(function() {
event.preventDefault();
var del_id = $(this).attr('fpid');
var $ele = $(this).parent().parent().parent();
var reference = this;
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
del_id: del_id
},
success: function(data)
{
$ele.fadeOut(1000).delay(1000).remove(1000);
}
});
});
// On Search Property Results Page - Add to Favorite Button (Heart)
$('.addtofavorite').click(function() {
event.preventDefault();
var ins_id = $(this).attr('pid');
var del_id = $(this).attr('fpid');
var reference = this;
/* alert(del_id);
alert(ins_id); */
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
ins_id: ins_id
},
success: function(data)
{
$(reference).toggleClass("addtofavorite alreadyfavorite");
$('.alreadyfavorite').attr('fpid', data);
}
});
});
The second function is not working, but if i refresh the page then the second function is working...
First assign some id to the image and change fpid to data-fpid(data-attribute):
<img class="asdasd" id="aid" data-fpid="something">
In your success try:
success: function(data)
{
$('#aid').data('fpid', data); //this should update the value in data-fpid
}

Ajax sends data , but returns nothing

I have got this html
<div class="Likes" data-i=<?php echo $row[8];?>>
<img src="../img/like.png">
<p class="L_c"><?php echo $row[4];?></p>
</div>
And this jquery/ajax
$(".Likes").click(function() {
var i = $(this).attr("data-i");
$.ajax({
type: "GET",
url: '../connect.php',
data: "I=" + i,
success: function(data) {
$(this).children(".L_c").html(data);
}
});
});
Connect.php
if (isset($_GET["I"]) && !isset($_GET["C"])) {
$RandS=$_GET["I"];
$query3=$con->query("SELECT id,likes FROM uploads WHERE Rand='$RandS'");
$row=$query3->fetch_row();
$IdU=$row[0];
$Likes=$row[1];
$Sel2=$con->query("SELECT id FROM likes WHERE User_id='$NameId' AND Post_id='$IdU'");
$num_rows=$Sel2->num_rows;
if ($num_rows>0) {
echo $Likes;
}else{
$query=$con->query("INSERT INTO likes (Post_id,User_id,`DATE`) VALUES('$IdU','$NameId',NOW())");
$query=$con->query("UPDATE uploads SET Likes=$Likes+1 WHERE Rand='$RandS'");
echo $Likes+1;
}
}
But it does not return anything untill i refresh the page
The this keyword inside the $.ajax methods callback is not the element, but the ajax call itself.
You have to either set context, or just store the outer this -value
$(".Likes").on('click', function() {
var me = $(this);
var i = me.attr("data-i");
$.ajax({
type: "GET",
url: '../connect.php',
data: "I=" + i,
success: function(data) {
me.find(".L_c").html(data);
}
});
});

Return JSON from PHP to ajax on button click

I have a page with list of buttons, when each button is clicked, it's value is captured and ajax call in made. PHP does DB updates on ajax call. I want to return data to ajax call. The data is obtained from DB. But I'm unable to point out what's the error in below code.
Here is PHP code:
if (isset($_GET['val']))
{
$chapter_id=$_GET['val'];
$sql= "SELECT file_name,edit_link,name,email FROM `chapter_list` where chapter_id='$chapter_id'";
$result = mysql_query($sql,$rst);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$vol_name = $row["name"];
$vol_email= $row["email"];
$vol_link= $row["edit_link"];
}
$update=mysql_query("UPDATE `chapter_list` SET `status` = '$update_status' WHERE `chapter_list`.`chapter_id` = '$chapter_id';");
header('Content-Type: application/json');
echo json_encode(array("name"=>$vol_name,"email"=>$vol_email,"link"=>$vol_link));
}
Here is the AJAX request
$(document).ready(function(){
$('.btn').click(function(){
var clickBtnValue = $(this).val();
$.ajax ({
url: '',
data: { val : clickBtnValue},
dataType:'JSON',
success: function(res) {
alert(res.name);
}
});
});
});
I'm not getting the alert!
Try like this.
Maybe response data is null.check your php code(query lines).
Here My php code is :
if (isset($_GET['val'])) {
$vol_name = 'dummy_name';
$vol_email = 'dummy_email';
$vol_link = 'dummy link';
header('Content-Type: application/json');
echo json_encode(array("name"=>$vol_name,"email"=>$vol_email,"link"=>$vol_link));
exit;
}
My javascriptcode is :
<input type="text" class="btn" value="test" />
<script type="text/javascript">
if('addEventListener' in document){
document.addEventListener("DOMContentLoaded", function(e){
//dom loaded
$(document).on("click",".btn",function(e){
e.preventDefault()
var e_val = $(this).val();
console.log('my value is :' + e_val);
if(e_val){
$.ajax({
type: "get",
dataType: 'json',
url: 'here your url or slash',
data: { // request e_val
val : e_val,
}
}).done(function(xhr) {
// console.log(xhr);
if(xhr.name){
alert('response data is '+ xhr.name);
}
})
}
})
},false)
}
</script>
try this..
while($row = mysql_fetch_assoc($result))
{
$vol_name = $row["name"];
$vol_email= $row["email"];
$vol_link= $row["edit_link"];
$ret[$vol_name]= array(
'email'=>$vol_email,
'link'=>$vol_link
);
}
then use in the return statement..
echo json_encode($ret);
You can send parameters in HTML
<button class="btn" atribute_id="21543">Button</button>
$(document).ready(function() {
$('.btn').click(function() {
var Value_of_Btn= $(this).attr("atribute_id"); <-------
$.ajax({
url: '',
data: {
val: clickBtnValue
},
dataType: 'JSON',
success: function(res) {
alert(res.name);
}
});
});
});

kendo ui grid edit button not working after loading persisting state

I am using Teleric kendo UI grid. I am using a database table to store grid options to save (persist) the grid state (column ordering, no of column default viewable etc) . It save option for every user, when the user login agin the state will automatically loded using an ajax call. Everything work fine
But the problem is that Edit button not working after loading saved state.
Please help.
thanks in advance
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<?php echo $this->session->flashdata('message');?>
<div class="panel panel-default">
<div class="panel-heading clearfix">
<div class="panel-body">
<?php
$transport = new \Kendo\Data\DataSourceTransport();
$read = new \Kendo\Data\DataSourceTransportRead();
$read->url(site_url('task/jsonMData'))
->contentType('application/json')
->type('POST');
$transport->read($read)
->parameterMap('function(data) {
return kendo.stringify(data);
}');
$model = new \Kendo\Data\DataSourceSchemaModel();
$id = new \Kendo\Data\DataSourceSchemaModelField('id');
$id->type('number');
$Name = new \Kendo\Data\DataSourceSchemaModelField('name');
$Name->type('string');
$Address = new \Kendo\Data\DataSourceSchemaModelField('address');
$Address->type('string');
$model->addField($id)
->addField($Name)
->addField($Address);
$schema = new \Kendo\Data\DataSourceSchema();
$schema->data('data')
->model($model)
->total('total');
$dataSource = new \Kendo\Data\DataSource();
$dataSource->transport($transport)
->pageSize(500)
->schema($schema)
->serverFiltering(true)
->serverSorting(true)
->serverGrouping(false)
->serverPaging(true);
$grid = new \Kendo\UI\Grid('grid');
$idField = new \Kendo\UI\GridColumn();
$idField->field('id')
->locked(false)
->width(60)
->hidden(true)
->title('ID');
$nameField = new \Kendo\UI\GridColumn();
$nameField->field('name')
->width(100)
->locked(false)
->hidden(true)
->title('Name');
$addressField = new \Kendo\UI\GridColumn();
$addressField->field('address')
->width(200)
->locked(false)
->hidden(true)
->title('Address');
$command = new \Kendo\UI\GridColumnCommandItem();
$command->click('commandClick')
->text('Edit');
$commandColumn = new \Kendo\UI\GridColumn();
$commandColumn->addCommandItem($command)
->title('Edit')
->width(125);
$excel = new \Kendo\UI\GridExcel();
$excel->fileName(' Task Export.xlsx')
->filterable(true)
->proxyURL('task/saveToExcel');
$grid->addColumn($id,
$name, $commandColumn)
->height(500)
->scrollable(true)
->editable('popup')
->dataSource($dataSource)
->resizable(true)
->reorderable(true)
->sortable(true)
->filterable(true)
->columnMenu(true)
->pageable(true)
->addToolbarItem(new \Kendo\UI\GridToolbarItem('excel'))
->excel($excel);
$grid->columnHide('function(e) { saveGridState(); }');
$grid->columnShow('function(e) { saveGridState(); }');
echo $grid->render();
?>
</div></div></div>
<div style="display:none;">
Click
<input type="hidden" name="rowIndex" id="rowIndex" value="-1" />
<input type="hidden" name="taskId" id="taskId" value="0" />
</div>
<!--to support excel import -->
<script>
function commandClick(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
console.log(dataItem);
var grid = $(e.currentTarget).closest("tr");
var row = grid.select();
var rowIndex = row.index();
var j = $('#hidden-link');
if(j)
{
$('#rowIndex').val(rowIndex);
$('#taskId').val(dataItem.id);
j.attr('href','<?php echo base_url()."task/edit";?>/'+dataItem.id)
j.click();
}
}
</script>
<script type="text/javascript">
$(document).ready(function() {
$(".fancybox").fancybox({
'afterClose':function () {
var rowIdx = $('#rowIndex').val();
var taskId = $('#taskId').val();
if(taskId != 0 && rowIdx >= 0)
{
userData = 'id='+taskId;
$.ajax({
url: "<?php echo site_url('task/getTaskById');?>",
type: "post",
data: userData,
dataType: "json",
success: function(data){
var firstRowItem = $('#grid').data().kendoGrid.dataSource.data()[rowIdx];
firstRowItem.set('Name',data.name);
firstRowItem.set('Plant',data.address);
},
async:false,
error:function(){
alert('There is error while submit');
}
});
}
},
});
var grid = $("#grid").data("kendoGrid");
userData = "type='m'";
$.ajax({
url: "<?php echo site_url('task/getGridSavedState');?>",
type: "post",
data:{type:'m'},
// contentType:'application/json',
dataType: "json",
success: function(data){
if(data.columns)
{
options=data;
grid.setOptions(options);
}
},
error:function(){
console.log("Error loding save grid state");
}
});
});
function saveGridState()
{
var grid = $("#grid").data("kendoGrid");
gridOptions=grid.getOptions();
var request=kendo.stringify({gridOptions : gridOptions,type:'m'});
$.ajax({
url: "<?php echo site_url('task/saveGridState');?>",
type: "post",
contentType:'application/json',
data: request,
dataType: "json",
success: function(data){
console.log("stated saved");
},
error:function(){
console.log("Error in stated saved")
}
});
}
</script>
From the API docs
Notice that when the options object is retrieved and then serialized into a string through JSON.stringify(options), then each field that is a function will be lost. This is limitation of the serialization that the JSON.stringify does. You need to either explicitly set the fields that were functions after parsing the object back or you need to use some custom implementation for serialization to handle the serialization of the JavaScript functions.
So you need to bind the command button to the function again: at least I think that is what they mean. So try adding a basic jQuery ('selector').on('click') function after the setOptions.
var grid = $("#grid").data("kendoGrid");
userData = "type='m'";
$.ajax({
url: "<?php echo site_url('task/getGridSavedState');?>",
type: "post",
data:{type:'m'},
dataType: "json",
success: function(data){
if(data.columns)
{
options=data;
if(options.editable)
{
//popout last column i.e command column
edit= options.columns.pop()
//add new command column explicitly.
commandCol={"command":[{"text":"Edit","click":commandClick}],"title":"Edit","width":125};
options.columns.push(commandCol);
grid.setOptions(options);
}
}
},
error:function(){
console.log("Error loding save grid state");
}
});

How can i load php file after sending ajax data

So I have 2 files file1.php with all the php and ajax, and file2.php with only php.
$_POST["there_id"] will be sent from file1.php page to file2.php through ajax.
file1.php code:
<div class="list_items">
<li><p>content here ...</p>
</div>
<div class="content_area">
//load ajax content here
</div>
$(".box").on("click", function(e) {
e.preventDefault();
var there_id = $(this).attr("id");
$.ajax({
url: "indexnew.php",
type: "POST",
data: { there_id : there_id}
});
});
file2.php code:
<div id="file2content>
<?php
$there_id = $_POST['there_id'];
$user_id = 5;
$fetch_data = regular_query("SELECT * FROM contents WHERE
(user_by = :me or user_by + :them) AND (user_to = :me or user_to = :them)",
["me" => $user_id, "them" = $there_id], $conn);
foreach ($fetch_data as $data) : ?>
<li><p>database data here</p>
<?php
endforeach;
?>
</div>
now what i want to do is when file2.php is done with php and list items are available i want to load file2contents to content_area on file1.php.
$(".box").on("click", function(e) {
e.preventDefault();
var there_id = $(this).attr("id");
$.ajax({
url: "indexnew.php",
type: "POST",
data: { there_id : there_id},
success: function(data) {
$('.content_area').html(data);
}
});
});
However, content_area should really be an id rather than a class so that it's unique.
Since you're just returning html, you can simplify it using the .load() function.
$('.box').on('click', function(e) {
e.preventDefault();
var there_id = $(this).attr('id');
$('.content_area').load('indexnew.php', {there_id: there_id});
});
success: function(data) { $(".content_area").html(data); }
adding the above to your AJAX call should do what you want if I understand you correctly.

Categories