How to refresh my div after submit comment? - javascript

I am using smarty framework in my project, I perfectly did my comment system but I cannot get the exactly result I want.
This is my PHP code inside event-detail.php :
$event_comment = $eventComment->geteventcomment($record, $startfrom, $max);
$tpl->assign("event_comment", $event_comment);
$tpl->display("event-detail.html");
This is HTML code inside event-detail.php :
//this is javasctipt
<script type="text/javascript">
// on post comment click
$('.bt-add-com').click(function(){
$.ajax({
type: "POST",
url: "add-comment.php",
data: 'act=add-com&event_id='+theEventId.val()+'&comment='+theCom.val()+'&user_id='+theUserId.val()+'&user_name='+theUserName.val()+'&file_path='+theFilePath.val(),
success: function(html){
theCom.val('');
theEventId.val('');
theUserId.val('');
theUserName.val('');
theFilePath.val('');
$('.new-com-cnt').hide('fast', function(){
$('.new-com-bt').show('fast');
$('.new-com-bt').before(html);
})
}
});
});
});
</script>
<div class="content-container-left">
<{section name=thisrsa loop=$event_comment}>
<div class="comment-box">
<div class="comment-listing">
<div><small><{$event_comment[thisrsa].date}></small></div>
<div class="avatar">
<img src="<{$smarty.const._CONST_CONTENT_MEMBER_THUMBNAIL}><{$event_comment[thisrsa].file_path}>"/>
<p><{$event_comment[thisrsa].name}></p>
</div>
<div class="comment-template">
<p><{$event_comment[thisrsa].content}></p>
</div>
</div>
</div>
<{/section}>
</div>
This is SQL statement which I had did it limit 3 record shows each page :
function geteventcomment($record, $startfrom, $max){
global $db,$comment;
$arrResult = array();
$stmt = "SELECT tbl1.event_id, tbl2.name, tbl2.file_path, tbl1.text, tbl1.modified_timestamp, tbl1.creation_timestamp FROM "._CONST_TBL_EVENT_COMMENT." tbl1, "._CONST_TBL_ALUMNI." tbl2 WHERE tbl1.event_id = $record AND tbl1.member_id = tbl2.id ORDER BY tbl1.creation_timestamp DESC";
$stmt .= " LIMIT $startfrom, $max";
if($rs = $db->Execute($stmt))
{
while($rsa = $rs->FetchRow())
{
array_push($arrResult, array(
"id" => $record,
"name" => $rsa['name'],
"file_path" => $rsa['file_path'],
"content" => $rsa['text'],
"date" => $rsa['modified_timestamp']
));
}
}
return $arrResult;
}
I had get the following result in my website :
But what I really want is to refresh div and make it only display the latest 3 comment in my website, like below :
I hope I can get some help from you guys.

Please check if following code helps.
$('.new-com-cnt').hide('fast', function(){
$('.new-com-bt').show('fast');
$('.new-com-bt').empty().append(html);
});

Related

Laravel & JQuery: Display mysql row data if ID is set

I have manage to get autocomplete data with typeahead search tutorial where I change in a way that now searching by three columns instead of one. So, when I start typing in search field autocomplete display:
Street from-to
and based on that I supposed to display other data from that ID (ID of that row but ID is not displayed).
You can see how it looks in my controller:
public function ajaxData(Request $request)
{
$query = $request->get('query', '');
$streets = Street::select('id', 'name')
->where('name', 'LIKE', '%'.$query.'%')
->get();
$results = array();
foreach($streets as $sn) {
$street_numbers = StreetNumber::select('from', 'to')
->where('town_id', Auth::user()->town_id)
->where('street_id', $sn->id)
->get();
foreach($street_numbers as $st) {
$data = array(
'name' => $sn->name." ".$st->from."-".$st->to
);
$results[] = $data;
}
}
return response()->json($results);
}
In view I supposed to select from autocomplete and when I click on submit it should display data like town, settlement etc...
But, if I try to use $street_numbers variable it shows me error:
(2/2) ErrorException
Undefined variable: street_numbers
In view beside field I have JQuery from typeahed tutorial:
{!! Form::open(['route'=>'add.index', 'method'=>'GET']) !!}
<div class="col-sm-12">
<div class="panel panel-default">
<div class="panel-heading">Search</div>
<div class="panel-body">
<div class="input-group">
{!! Form::text('search_text', null, array('placeholder' => 'Street from - to','class' => 'form-control','id'=>'search_text')) !!}
<span class="input-group-btn">
{!! Form::button('<i class="fa fa-search"></i>', ['type' => 'submit', 'class'=>'btn btn-default']) !!}
</span>
</div>
</div>
</div>
</div>
{!! Form::close() !!}
<script type="text/javascript">
var url = "{{ route('autocomplete.ajax') }}";
$('#search_text').typeahead({
source: function (query, process) {
return $.get(url, { query: query }, function (data) {
return process(data);
});
}
});
</script>
I'm very stuck on this one and don't know how to start from here because in JS or JQuery I'm a beginner.
Before ajaxData() function I have index() function and there I have:
return view('members.index', compact('towns', 'user', 'activist', 'capillary'));
So there is my view.
I'm trying to use $street_numbers variable in view like this:
<div class="col-sm-6">
<div class="form-group">
{!! Form::label('', 'Settlement') !!}
{!! Form::select('', [$street_numbers? $street_numbers->settlement->name : null => $street_numbers? $street_numbers->settlement->name : null], null, ['class'=>'form-control', 'readonly']) !!}
</div>
</div>
I succeeded and I want to share with others in case somebody needs it:
In submit button I placed 'id'=>'get_cust_data' and then I made separate .js file where I pull information from autocomplete search field when it's submitted.
JS:
$(document).ready(function(){
$('#get_cust_data').click(function(){
var st = $.trim($("#search_text").val());
get_cust_data(st);
});
});
In controller I get data with explode function because, as I said in first post I have street-from-to from database, not just one data. In further codes you will see how I get ID from street and then object which I use to get other info from same row like settlement, electorUnit and so...
public function get_cust_data(Request $reques)
{
$arr = explode("-", $reques->st);
$street = $arr[0];
$from = $arr[1];
$to = $arr[2];
// Street ID
$street_id = Street::select('id')
->where('name', $street)
->first()->id;
// Object
$street_data = StreetNumber::select('*')
->where('street_id',$street_id)
->where('from', $from)
->where('to', $to)
->get();
$result = array();
// Settlement ID
$settlement_id = $street_data[0]->settlement_id;
$result['settlement_id'] = $settlement_id;
// Settlement Name
$settl_data = Settlement::select('name')
->where('id',$settlement_id)
->get();
// ElectoralUnit ID
$electoral_unit_id = $street_data[0]->electoral_unit_id;
$result['electoral_unit_id'] = $electoral_unit_id;
// ElectoralUnit Name
$el_unit_data = ElectoralUnit::select('name')
->where('id',$electoral_unit_id)
->get();
// ElectoralUnitNumber
$el_unit_number_data = ElectoralUnit::select('electoral_unit_number')
->where('id',$electoral_unit_id)
->get();
$result['s_name'] = $settl_data[0]->name;
$result['e_name'] = $el_unit_data[0]->name;
$result['e_n_name'] = $el_unit_number_data[0]->electoral_unit_number;
$result['street'] = $street;
$result['str_id'] = $street_id;
return response()->json(json_encode($result));
}
Then in the sam JS file, which is connected in header to view, I put another function that I googled and can't explain completely how it works, but that function forwarding variables from controller through view with fields ID-s like this:
function get_cust_data(street_data){
var method_url= "/get_cust_data";
$.ajax({
type: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: method_url,
cache: false,
data:{ st:street_data},
async: true,
success: function(response){
var data = JSON.parse(response);
// console.log(data.id);
$('#street').append("<option value='"+data.street+"'>"+data.street+"</option>");
$('#settlement_id').append("<option value="+data.settlement_id+">"+data.s_name+"</option>");
$('#electoral_unit').append("<option value='"+data.e_name+"'>"+data.e_name+"</option>");
$('#electoral_unit_number').append("<option value="+data.electoral_unit_id+">"+data.e_n_name+"</option>");
// console.log(data.message);
}, error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
I hope that at least I explained a bit and will help somebody. Cheers!

php html div set POST variable in click

hello i want to set a $_POST value in php when someone click a div element , here's part of my code :
<?php
$looperone = 1;
$judulcountquery = "SELECT nomorsoal FROM soal";
$judulcountrun = mysqli_query($konek,$judulcountquery);
if ( $judulcountrun == FALSE ) {
die(mysqli_error());
} else {
}
$judulcount = mysqli_num_rows($judulcountrun);
$amountofrows = $judulcount;
while($looperone == 1) {
$judulherequery = "SELECT * FROM soal WHERE nomorsoal = $amountofrows";
$judulsatuqueryconnect = mysqli_query($konek,$judulherequery);
$judulsatufetch = mysqli_fetch_assoc($judulsatuqueryconnect);
if($judulsatufetch != NULL) {
$judulsatu = $judulsatufetch['judul'];
} else {
break;
}
$judulnya = $judulsatufetch['judul'];
echo "<div class=\"head-main-recenttest-result\" style=\"text- decoration:none;\">". "".$amountofrows.".".$judulnya." </div>";
$looperone++;
$amountofrows--;
}
?>
example of output from echo :
<div class="head-main-recenttest-result" style="text-decoration:none;">
Latihan 1
</div>
as you see that only will redirect people to the link without giving post data , anyone know the method ? also im new so i can't ask well
By the looks of your code, you are not sending any post variable to the bacasoal.php. If you just want to submit then this will suffice.
<form method="post" action="bacasoal.php">
<div class="head-main-recenttest-result" style="text-decoration:none;">
<input type="submit" name="button" value="Latihan 1">
</div>
</form>
Note: Your <a> tag was replaced by a an submit input
And if you want to do it via AJAX when click on the <a> then
HTML
<div class="head-main-recenttest-result" style="text-decoration:none;">
Latihan 1
</div>
AJAX
$('a').click(function(){
$.ajax({
url: "bacasoal.php",
type: "post",
success:(unction(){
alert("success");
},
error:function(){
alert("error");
}
})
});
In the first approach the page will be redirected to bacasoal.php.
In second one the page will stay(unless you make it to).

how to get data from javascript

hello i want to get text from textarea and register in database but not work where is problem thanks all. $get_text show empty value.
<script type="text/javascript">
$(function() {
$(".new_post").click(function(){
var get_text = $("#post_text").val();
$.ajax({
type: "POST",
url: "ajax/ajax_new_post.php",
data: get_text,
success: function() {
alert(get_text);
$('#post_text').val('');
//$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
//.animate({ opacity: "hide" }, "slow");
}
});
return false;
});
});
</script>
<body>
<textarea id="post_text" placeholder="What's on your mind?"></textarea>
</body>
ajax_new_post.php
$get_text = $_GET['get_text'];
mysqli_query($Connection, "INSERT INTO posts VALUES('$ID', '$get_text')");
You are missing key. Change your data to:
data: { get_text : $("#post_text").val() },
And your type is POST, so use $_POST['get_text'] in PHP file.
You are using post method . So use $_POST['get_text'];
The problem is that you are making a POST and trying to get the value as GET.
Use :
$get_text = $_POST['get_text'];
mysqli_query($Connection, "INSERT INTO posts VALUES('$ID', '$get_text')");
Use jQuery to send a JavaScript variable to your PHP file:
'$url = 'path/to/phpFile.php';
$.get($url, {name: get_name(), job: get_job()});'
In your PHP code, get your variables from $_GET['name'] and $_GET['job'] like this:
<?php
$buffer_data['name'] = $_GET['name'];
$buffer_data['job'] = $_GET['job'];
?>

AJAX cannot return Json data

I'm trying to post a piece of Json data to AJAX and get a "upvote_message" in return. However, the "upvote_message" is returned as undefined.
Code:
<div class="media">
<div class="media-body">
<p align="right">
<span href="javascript:;" rel="1" class="upvote">Text to be replaced</span>
</p>
</div>
</div>
JS:
<script type="text/javascript">
$(function(){
$('.media .media-body .upvote').click(function(){
var this_a = $(this);
var comment_id = $(this).closest('span').attr('rel');
$.ajax({
type:"POST",
url: base_url + "/upvote",
data:{comment_id : comment_id},
dataType: "json",
success: function(data,status){
if(data.state == 'succ')
{
this_a.html(upvote_msg);
}
else
{
this_a.html(upvote_msg);
}
}
});
});
});
</script>
PHP
public function upvote (){
$comment_id = $this->input->post('comment_id');
if($comment_id==5){
echo json_encode(array('state' => 'succ','upvote_msg'=>'haha'));
}
else{
echo json_encode(array('state' => 'fail','upvote_msg'=>'bam'));
}
exit();
}
}
The PHP and AJAX's write-into part works fine. Data is also registered in database.
The issue is that the 'upvote_msg' is shown as "undefined" when being returned to the Javascript.
How to fix this? Many thanks,
upvote_msg is a property of the data object so it should be data.upvote_msg
To get upvote_msg value you have to use
data.upvote_msg or data["upvote_msg"]

call javascript function in every div in html

Hi I have a javascript function and I want it to call when the c_id loops each. but I don't have an idea about it.
here is my function.
function getCLowestPrice(c_id){
$.ajax({
type: "POST",
url: 'http://sample.com/api/store_lowest_price/',
dataType: "xml",
cache: false,
data: {'id' : c_id},
success: function(resp){
// we have the response
console.log(resp);
$(resp).find("response").each(function() {
var c_name = $(this).find("c_name").text();
var c_currency = $(this).find("currency").text();
var c_min_price = $(this).find("price_min").text();
var formated_price = addCommas(parseFloat(c_min_price).toFixed(2));
$('.cinformation').html("<p>Lowest Price : " + c_currency + " " + formated_price + "</p>");
});
},
});
}
and I want it to call when the div loaded. but it loops all the clients and also their c_id.
<div>
Client : <?php echo get_post_meta($post->ID, 'wpcf-c', true); ?>
<div class="cinformation">
C ID = <?php echo get_post_meta($post->ID, 'wpcf-c-id', true); ?>
....
</div>
...
</div>
so it will be this when it loops.
<div>
Client : Hello
<div class="cinformation">
C ID = 1
....
</div>
...
</div>
....
<div>
Client : World
<div class="cinformation">
C ID = 2
....
</div>
...
</div>
....
....
...
but i don't have any idea on how can I add the getCLowestPrice(c_id) in the cinformation div.
I try to use the onload but it can't be used in div.
does anyone have an idea about my case?
thanks in advance ...
You need to put your C ID using data attribute like so:
<div>
Client : Hello
<div class="cinformation" data-c_id="1">
</div>
</div>
Then after the page loads just use jQuery to select all your divs and call your function:
$(".cinformation[data-c_id]").each(function(index, elem){
var cId = $(this).data("c_id");
getCLowestPrice(cId);
});
You can just try adding this
<script type="text/javascript">
getCLowestPrice (<?php echo get_post_meta($post->ID); ?>)
</script>
in your for loop in php

Categories