I would like to display total amount of likes on page, the likes are displayed in:
<input type="tekst" id="<?php echo $item->getId();?>">
add like function button:
$(function () {
$('a.like').on('click', function () {
var url = $(this).attr('href');
$.post(url, {}, function () {
});
return false;
});
});
So not I have to click on $('a.like') and then refresh page to see the like added, I would like to skip refreshing the page. Any ideas?
EDIT there is also a script:
<script>
document.getElementById("<?php echo $item->getId();?>").value =<?php echo getVotesValue($item->getId());?>
</script>
If I understand correctly, you need to replace your code by this:
var likesCounter = $('#<?php echo $item->getId();?>');
$(function () {
$('a.like').on('click', function () {
var url = $(this).attr('href');
$.post(url, {}, function () {
likesCounter.val(parseInt(likesCounter.val()) + 1);
});
return false;
});
});
Related
I have a case where I want to pass a variable inside a function.
The code gives more clarity:
<?php
$id=$_POST['id'];
echo "
<script type=\"text/javascript\">
$(document).ready(function(){
function loadData(page){
$.ajax({
type: \"POST\",
url: \"loadSubscritor.php\",
dataType: \"html\",
data: ({ page:page }),
success: function(msg) {
$(\"#subscritor #container\").ajaxComplete(function(event, request, settings) {
$(\"#subscritor #container\").html(msg);
});
},
error: function(){
alert('alertErr');
}
});
}
loadData(1); // For first time page load default results
$('#subscritor #container .pagination li.active').live('click',function() {
var page = $(this).attr('p');
loadData(page);
});
$('#subscritor #go_bt').live('click',function() {
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val(\"\").focus();
return false;
}
});
});
</script>
<h3>Subscritor</h3>
<div id=\"subscritor\">
<div id=\"container\">
<div class=\"pagination\"></div>
</div>
</div>";
?>
As shown in the code,
I would like to know how could I pass $id inside the loadData(page) function .
I get this variable from a post request made with ajax, and need to use it inside the function to pass it has variable to loadSubscritor.php
Any idea on how to do it?
EDIT 1: I guees I wasnt very clear on what I wanted, i want to do this :
function loadData(page){
$.ajax({
data: ({ page:page id:$id }),
Thanks in advance.
Well, if I understood what you are trying to achieve you could replace this :
$id=$_POST['id'];
By this :
$id = isset($_POST['id']) ? $_POST['id'] : 1;
And this :
loadData(1); // For first time page load default results
By this :
loadData($id);
For explanation, if it's first time page load, $id will be set to "1".
Else, this will come from $_POST['id'].
Inside your jquery code you can call a php variable in following way
var current_page = "<?php echo $id; ?>" ;
You can make a local variable and easily use as below:
<?php
$id=$_POST['id'];
echo "
<script type=\"text/javascript\">
var id = \"".$id."\";
$(document).ready(function(){
function loadData(page){
$.ajax
({
type: \"POST\",
url: \"loadSubscritor.php\",
dataType: \"html\",
data: ({ page:page
}),
success: function(msg)
{
$(\"#subscritor #container\").ajaxComplete(function(event, request, settings)
{
$(\"#subscritor #container\").html(msg);
});
},
error:
function()
{ alert('alertErr');
}
});
}
loadData(1); // For first time page load default results
$('#subscritor #container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(id);
});
$('#subscritor #go_bt').live('click',function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(id);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val(\"\").focus();
return false;
}
});
});
</script>
<h3>Subscritor</h3>
<div id=\"subscritor\">
<div id=\"container\">
<div class=\"pagination\"></div>
</div>
</div>
";
?>
I have several views that contain this same javascript.
<script type="text/javascript">
$(function () {
$("#addAnother").click(function () {
$.get('/QuestionGroup/QuestionEntryRow', function (template) {
$("#questionEditor").append(template);
});
});
});
</script>
I decided to move this logic to a javascript file. So here what I did.
On my view I added a data-attr.
<a method="get" action="#Url.Action("QuestionEntryRow", "QuestionGroup")" href="#">Add another</a>
In the javascript file I added the following code.
var insertRow = function () {
var $a = $(this);
var options = {
url: $a.attr("action"),
type: $a.attr("method")
};
$.ajax(options).done(function (data) {
var $target = $($a.attr("data-cban-target"));
$target.append(data);
});
return false
};
$("a[data-cban-a]").click(insertRow);
When the user click the link "Add another". The javascript is not getting executed.
Target
<ul data-cureurban-target="questionEditor" style="list-style-type: none">
</ul>
Here the controller logic
public ActionResult QuestionEntryRow()
{
ViewBag.QuestionID = new SelectList(db.Questions, "QuestionID", "QuestionDesc");
return PartialView("_QuestionEntryEditor");
}
Try the following for your .js file:
var insertRow = function () {
var $a = $(this);
var options = {
url: $a.attr("action"),
type: $a.attr("method")
};
$.ajax(options).done(function (data) {
var $target = $($a.attr("data-cban-target"));
$target.append(data);
});
return false
};
$(document).ready(){
$("a[data-cban-a]").click(insertRow);
}
Try adding javascript:void(0) in href of anchor tag.
<a method="get" action="#Url.Action("QuestionEntryRow", "QuestionGroup")" href="javascript:void(0)">Add another</a>
Refer this stackoverflow post for more details
Default event propogation for (a)anchor tag needs to be stopped.
<script type="text/javascript">
$(function () {
$("#addAnother").click(function (e) {
e.preventDefault();
$.get('/QuestionGroup/QuestionEntryRow', function (template) {
$("#questionEditor").append(template);
});
});
});
</script>
I created a small function to test Zend-Ajax interaction.
In my view I set following code
<script type="text/javascript">
var urlform = '<?php echo $this->url('inbox/default', array('controller'=>'messages', 'action'=>'addmessage')); ?>';
</script>
<div onclick="ajaxtest();">Click</div>
Then, I created following function within file custom.js, already associated to the layout
function ajaxtest() {
$.post(urlform, null, function(data) {
if (data.success) {
alert('Ok');
} else {
alert('Failed');
}
}, 'json');
}
And finally, this is the code of my addMessageAction
public function addMessageAction()
{
$request = $this->getRequest();
$response = $this->getResponse();
$response->setContent(\Zend\Json\Json::encode(array('success'=>1)));
return $response;
}
When I click on the div associated to the javascript function, nothing happens, no alert is displayed.
Where am I wrong? Does it depend on particular zend settings?
I solved the problem by ridefining function in the following way:
var ajaxpost = $.post(urlform2).fail(function() {
alert("Failed");
})
ajaxpost.done(function(data) {
var parsed = jQuery.parseJSON(data);
if (parsed.success == 1) {
alert('Ok');
}
});
I am facing issues with creating a dynamic textarea and 'Add' and 'Edit' buttons for every new paragraph.
DEMO of what I have managed so far:
The 'Add' button is for creating new paragraphs. The user should see a textarea where they enter the content for new paragraph. The first time they click 'Add' button, the text on the button will change to 'Save', the second time they click 'Save' it should append the paragraph to the div and assign it a unique id, which will be used to reference it with the new 'Add' and 'Edit' buttons.
The 'Edit' button is for editing the paragraph from which the 'Edit' button was clicked. To make the paragraph editable I'm using jquery editable (jeditable). Below are appropriate links to jeditable plugin:
plugin documentation
jeditable live demo
All the paragraph load from the back-end. Using PHP to load paragraphs:
<div class="paragraphs">
<?php
foreach($notes['children'] as $overview) :
if ($overview['type'] == 'Paragraph') :
?>
<div id="block1">
<p class='edit1'><?php echo $overview['content']; ?></p>
<p>
<?php if (isset($subject) && $subject==true) : ?>
<div id="para1">
<p><textarea cols="40" rows="2" id="textarea1"></textarea></p>
<button id="add1" class="add1 success tiny">Add</button>
<button id="startEdit1" class="canEdit1 tiny">Edit</button>
</div>
<?php endif; ?>
</p>
</div>
<?php endif; ?>
<?php endforeach; ?>
</div>
The 'Add' and 'Edit' button functionality:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="<?php echo base_url(); ?>assets/teachers/js/jquery.jeditable.min.js"></script>
<script>
var $subject_id = "<?php echo $subject_id ?>";
var $teacher_id = "<?php echo $teacher_id ?>";
// Define our elements
var $lock = false;
//Make the elements editable
function makeThingsEditable() {
$editables.editable({
emptyMessage : '<em>Please write something...</em>',
callback : function( data ) {
$info.hide();
$info.eq(0).show();
}
});
}
function ajaxRequest(data, method_url, request_type) {
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('HTTP/1.1', '200');
}
});
var eurl = "<?php echo base_url(); ?>edit_flow/" + method_url;
var params = 'inputJson=' + data;
var post = $.ajax({
type: request_type,
url: eurl,
data: params,
success: function(result) {
console.log('result: '+result);
console.log('data: '+params);
},
async: false
});
//alert(post.responseText);
return post.responseText;
console.log(post.responseText);
}
// Edit paragraph button
// Button that toggles the editable feature
var i = 1;
var $editables = $('.edit'+i);
$('.canEdit'+i).click(function() {
if( $editables.is(':editable') ) {
//need to call save action here and pass in updated JSON
if ($(this).text() == 'Save changes')
{
var text = $(".edit"+i).text();
// ajax request
var datum = '{"subject_id":'+$subject_id+',"teacher_id":'+$teacher_id+',"editedContent":"'+text+'"}';
ajaxRequest(datum, 'editNotes', 'POST'); // POST request on editNotes
ajaxRequest(datum, 'loadNotes', 'GET'); // GET request on loadNotes
// jquery request
$.get( "<?php echo base_url(); ?>edit_flow/loadNotes", function( data ) {
var data = '{"subject_id":'+$subject_id+', "teacher_id":'+$teacher_id+', "editedContent":"'+text+'"}';
//console.log(data);
alert( data );
});
}
$editables.editable('destroy');
this.innerHTML = 'Edit';
i++;
} else {
makeThingsEditable();
this.innerHTML = 'Save changes';
// TODO h4kl0rd: make $editables selectable
}
});
// Add paragraph button
i = 1;
$('#textarea'+i).hide();
$('#add'+i).click(function(){
if ( $(this).text() == "Add" ) {
$('#textarea'+i).show();
$(this).text('Save');
$('#textarea'+i).focus(function() {
this.select();
});
}
else if ( $(this).text() == "Save" ) {
if ($('#textarea'+i).val() == ''){
alert('Enter something...');
} else {
$(this).text("Add");
$('#textarea'+i).hide();
var overview = $('#textarea'+i).val();
i++;
$('.paragraphs').append('<div id="block'+i+'"><p class="edit'+i+'">'+overview+'</p><div id="para'+i+'"><p><textarea cols="40" rows="2" id="textarea'+i+'"></textarea></p><button id="add'+i+'" class="add'+i+' success tiny">Add</button><button id="startEdit'+i+'" class="canEdit'+i+' tiny">Edit</button></div></div>');
}
}
});
</script>
Any help is appreciated.
change these:
$('.canEdit'+i).click(function() {
$('#add'+i).click(function(){
to these:
$(document).on('click', '.canEdit'+i, function() {
$(document).on('click', '#add'+i, function() {
What seemed to me is your buttons are dynamic and they can't take direct event binding. So instead you have to delegate the event to the closest static parent which is $('.paragraphs') or to $(document) itself because it is always available.
So if you are using closest static parent then you have to put your event handlers inside doc ready and if you are using $(document) then its not needed.
$(function(){
var i = 1;
var $editables = $('.edit'+i);
$('.paragraphs').on('click', '.canEdit'+i, function() {
// all your edit stuff
});
$('.paragraphs').on('click', '#add'+i, function() {
// all your addstuff
});
});
i am trying to post the database retrieved value to next page using ajax.i tried but it not posting, can any one guide me how to do it
php
connected with database
$sql = "SELECT * FROM `billingdatainputandexport` WHERE id='1'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
//print $sql;
$billingmonth=$rows['billingmonth'];
i want to pass this billing month to selectsuppliercostprice.php.
javascript
$(document).ready(function() {
$("#supplier").on("change", function() {
var billingmonth='$billingmonth';
var supplier = document.getElementById("supplier").value;
var mcc = document.getElementById("mcc").value;
var mnc = document.getElementById("mnc").value;
$.post('selectsuppliercostprice.php', { org: supplier,mcc: mcc,mnc: mnc,billingmonth: billingmonth }, function(result) {
$('#suppliercost').html(result);
}
);
});
});
selectsuppliercostprice.php.
$billingmonth=$_POST['billingmonth'];
Can you try this,
PHP
$billingmonth=$rows['billingmonth'];
echo '<input type="hidden" id="billingmonth" name="billingmonth" value="'.$billingmonth.'">'; // added hidden input
Javascript:
$("#supplier").on("change", function() {
var billingmonth= $('#billingmonth').val();
...
});
The post variable is $_POST not $POST so ... that should be right:
$billingmonth = $_POST['billingmonth'];
Also in Javascript you have to print the billingmonth variable. Javascript can't handle php-variables:
var billingmonth='$billingmonth';
to
var billingmonth='<?php echo $billingmonth; ?>';
Here is the latest code : u missed i guess the php tag inside ur script tag now try :)
$(document).ready(function() {
$("#supplier").on("change", function() {
var billingmonth='<?php echo $billingmonth ?>';
var supplier = document.getElementById("supplier").value;
var mcc = document.getElementById("mcc").value;
var mnc = document.getElementById("mnc").value;
$.post('selectsuppliercostprice.php', { org: supplier,mcc: mcc,mnc: mnc,billingmonth: billingmonth }, function(result) {
$('#suppliercost').html(result);
}
);
});
});
make hidden field and store your value in that and read that value in javascaript and pass it with ajax
<input type="hidden" name="some_name" value="<?php echo $billingmonth?>" id="some_name"/>
javascript code
$(document).ready(function() {
$("#supplier").on("change", function() {
var billingmonth=document.getElementById('billingmonth').value;
var supplier = document.getElementById("supplier").value;
var mcc = document.getElementById("mcc").value;
var mnc = document.getElementById("mnc").value;
$.post('selectsuppliercostprice.php', { org: supplier,mcc: mcc,mnc: mnc,billingmonth: billingmonth }, function(result) {
$('#suppliercost').html(result);
}
);
});
});
if you don't want to use it anyother place than
var billingmonth= '<?php echo $billingmonth?>';
Just Try.
Store $billingmonth value into any hidden input.
<input type="hidden" name="billing_month" id="billing_month" value="<?php echo $billingmonth; ?>"/>
Retrieve $billingmonth value in jQuery ready function using Hidden input id.
$(document).ready(function() {
$("#supplier").on("change", function() {
var billingmonth=$("#billing_month").val();
var supplier = $("#supplier").val();
var mcc = $("#mcc").val();
var mnc =$("#mnc").val();
$.post('selectsuppliercostprice.php', { org: supplier,mcc: mcc,mnc: mnc,billingmonth: billingmonth }, function(result) {
$('#suppliercost').html(result);
}
);
});
});