I have a script which allows user to like(+1) a record. Everything is working, but I don't know how to show a new value from DB after button is pressed (without refresh). I'm using codeigniter and I'm not really know a lot about jquery.
My script:
<script type="text/javascript">
var base_url = '<?php echo base_url();?>';
jQuery(document).ready(function(){
$('.like').click(function() {
var id = $(this).attr("uid");
$.ajax({
url: base_url+'quotes/quotes_rating',
type: 'GET',
data: {'id': id}
});
});
});
</script>
My controller:
public function quotes_rating() {
$id = $this->input->get('id');
$this->quotes_model->write_likes($id);
}
Model function write_likes() saves records into DB.
This is my model function which shows how many likes has a record:
public function all_likes($id)
{
$sql = "select COALESCE(sum(like),0) as likes from rating WHERE record_id = '{$id}'";
$likes = $this->db->query($sql)->row_array();
return $allikes['likes'];
}
What I have to change in this code?
When user will click .like button, he shoud see a new value from database. Thank you!!!
jQuery(document).ready(function(){
$('.like').click(function() {
var $this = $(this);
$.ajax({
url: base_url+'quotes/quotes_rating',
type: 'GET',
data: {'id': id},
dataType: 'html',
success: function(d){
$this.html(d); //will set html of clicked link
}, error: function(){ //code for error }
});
});
<script type="text/javascript">
var base_url = '<?php echo base_url();?>';
jQuery(document).ready(function(){
$('.like').click(function() {
var id = $(this).attr("uid");
$.ajax({
url: base_url+'quotes/quotes_rating',
type: 'GET',
data: {'id': id}
success: function(data) {
$("someelementyouwanttoseelikesin").html(data);
//data will contain anything you echo in your php script!
}
});
});
});
</script>
Related
I am trying to send a JS variable to a PHP file but it does not seem to be working. In the console its showing an error as an show.php file. I am not able to understand What I am doing wrong.
function details(id) {
var id = id;
// alert(id);
$.ajax({
type: 'POST',
url: 'show.php',
data: id,
success: function(data) {
alert("hi");
}
});
}
<button onclick="details(<?php echo $id ; ?>)" class="btn btn-rounded btn-primary">Details</button>
show.php:
<?php
if (isset($_POST['id']))
{
$uid = $_POST['id'];
echo json_encode($uid);
}
?>
Write data in json object
see code below
function details(id)
{
var id = id;
// alert(id);
$.ajax({
type: 'POST',
url: 'show.php',
data: {id:id},
success: function(data)
{
alert("hi");
}
});
}
Check your network tab and check the sending parameters list . You have to mention datatype json
Try this
function details(id)
{
var id = id;
// alert(id);
$.ajax({
type: 'POST',
url: 'show.php',
dataType: 'json',
data: {'id':id},
success: function(data)
{
alert("hi");
}
});
}
In your show.php
<?php
if (isset($_POST['id']))
{
$uid = $_POST['id'];
echo json_encode($uid);
}
?>
Since couple of weeks(two) started my adventure with Magento. So far I've learned a little but have a problem how to send data using Ajax (jQuery).
$(document).ready(function(){
var total = $(this).find(\"input[class=tramp]:checked\").length;
$(\".caret input[type='checkbox']\").change(function(){
if($(this).is(':checked')){
var value= true;
}else{
var value = false;
}
var brand = $(this).data('brand');
data = {brand: brand, value: value}
$.ajax({
data: data,
url: 'checkbox/ajax/index',
method: 'POST',
success: function(result){
console.log(data, total);
}});
});
});
This is my Ajax, so as you can see trying to send brand and value. AjaxController.php looks like this:
class Amber_Checkbox_AjaxController extends Mage_Core_Controller_Front_Action {
public function indexAction()
{
$brand = Mage::app()->getRequest()->getPost('brand', 'value');// not sure or I should use data?
if($brand )
{
....
$this->getResponse()->setBody($brand);
echo $brand;
...
}
}
}
remove \"
$(document).ready(function(){
var total = $(this).find("input[class=tramp]:checked").length;
$(".caret input[type='checkbox']").change(function(){
if($(this).is(':checked')){
var value= true;
}else{
var value = false;
}
var brand = $(this).data('brand');
data = {brand: brand, value: value}
$.ajax({
data: data,
url: 'checkbox/ajax/index',
method: 'POST',
success: function(result){
console.log(data, total);
}});
});
});
remove \", $ replace with jQuery and pass absolute URL Mage::getUrl('checkbox/ajax/index');
$.ajax({
data: data,
url: '<?php echo Mage::getUrl("checkbox/ajax/index"); ?>',
method: 'POST',
success: function(result){
console.log(data, total);
}});
i have a div that shows the total sum of some products:
<div class="total-price"><?php echo (!empty($cart)) ? $cart['total'] : '0'; ?> $</div>
with ajax, i'm adding products to cart ... se the page is not reloading.
How to refresh the div after I add the product to cart?
The ajax that i'm using:
<script>
$('#order-to-cart').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/tdt/order',
data: $(this).serialize(),
success: function () {
$(".success-message").slideDown().delay(5000).slideUp();
$(".total-price").something...;
}
});
})
</script>
Thank you!
You can do something like this:
<script>
$('#order-to-cart').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/tdt/order',
data: $(this).serialize(),
success: function () {
$(".success-message").slideDown().delay(5000).slideUp();
var oldPrice = $('.total-price').text() * 1;
var itemPrice = "15"; //the price that should be added
$('.total-price').text(oldPrice + itemPrice);
}
});
})
</script>
You should be returning a total basket value from your /tdt/order path.
In the PHP script you should echo some JSON data with all the required information, for example
echo json_encode(array("totalPrice" => "£10.01"));
Then you need to parse this information into your Javascript and update the pages elements;
<script>
$('#order-to-cart').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/tdt/order',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
$(".success-message").slideDown().delay(5000).slideUp();
$('.total-price').val(data.totalPrice);
}
});
})
</script>
The above ajax request will expect the data returned to be JSON, you will then use this to update the total-price element.
You can use something like angularjs or knockoutjs - for angular you would update your model - for knockout you would use the self.object.push(value) i.e.,
function OrderViewModel() {
var self = this;
self.myOrder = ko.observableArray([]);
self.addOrderItem = function () {
$.ajax({
type: "post",
url: "yourURL",
data: $("#YOURFORMFIELDID").serialize(),
dataType: "json",
success: function (value) {
self.myOrder.push(value);
},
headers: {
'RequestVerificationToken': '#TokenHeaderValue()'
}
});
}
}
ko.applyBindings(new orderViewModel());
</script>
</pre>
I am working on a jQuery sortable. I pull information from my database to populate each orderable element and then repost the new order back to my data base. However I cannot figure out how to take the variable that I define in my serialize jQuery and enter it into my AJAX function in the data: area.
Here is my code:
$(document).ready(function()
{
$('#social_list').sortable(
{
update: function()
{
var order = $('#social_list').sortable('serialize');
alert(order);
}
});
});
$.ajax(
{
url: 'save_items_order.php',
data: ?,
type: '$_POST',
success: function(msg)
{
alert(msg);
}
});
So I want to take the string that var order creates and pass it into the ajax so data: = var order string
I tried data: $('#social_list').sortable('serialize'), everything seemed to work it just doesn't seem to update my table
Simplest solution is to make a global
$(document).ready(function() {
$('#social_list').sortable({
update: function() {
// global. you could just omit var, but I find this clearer
window.order = $('#social_list').sortable('serialize');
}
});
});
$.ajax({
url: 'save_items_order.php',
data: window.order, /* ...rest of code */
});
But I'm sure you know globals are bad, you can at least contain them to your namespace,
var myNs = {};
$(document).ready(function() {
$('#social_list').sortable({
update: function() {
myNs.order = $('#social_list').sortable('serialize');
}
});
});
$.ajax({
url: 'save_items_order.php',
data: myNs.order /* ... rest of code */
});
or re-organize your code so they can share variables.
$(document).ready(function() {
var order;
$('#social_list').sortable({
update: function() {
order = $('#social_list').sortable('serialize');
}
});
$('#myButton').click(function(){
$.ajax({
url: 'save_items_order.php',
data: order, /* ... rest of code */
});
});
});
Note that for this case, you could just do the following
$.ajax({
url: 'save_items_order.php',
data: $('#social_list').sortable('serialize') /* ... rest of code */
});
You just pass any javascript object in as the data.
For your specific case, I would probably wrap the AJAX call in a function, like:
function saveItemOrder(order)
{
$.ajax({
url: 'save_items_order.php',
data: { "order": order },
type: 'POST', // <-- this should be just "POST"
success: function(msg){
alert(msg);
}
});
}
And then:
update: function() {
var order = $('#social_list').sortable('serialize');
// alert(order);
saveItemOrder(order);
}
$(function(){
$('.page').click(function() {
var paging = $(this).attr("name");
var dataString = 'page='+paging;
$.ajax({
type: "POST",
url: "<?php echo $backtrack; ?>shop.php",
data: dataString,
success: function(){
$('#products').load('shop.php/skateboards/ #products > *', function(){
$('#products').delay(200).fadeOut();
$('#products').delay(600).fadeIn();
});
$(".current-page").attr("class", "");
}
});
return false;
});
});
I am guessing this is not working because I am reloading the part of the page that gets the post. What I want to do is post the page number to the current page and then reload the items inside the products div, with it being the next set of items
I think you need to do something like this:
$('.page').click(function() {
$('#products').delay(200).fadeOut();
var paging = $(this).attr("name");
var dataString = 'page='+paging;
$.ajax({
type: "POST",
url: "<?php echo $backtrack; ?>shop.php",
data: dataString,
complete: function() {
$.get('shop.php/skateboards/', function(data) {
$('#products').replaceWith(data);
});
}
});
return false;
});