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);
}});
Related
post and get works fine but json returns wrong value , or something is wrong with my php code.
$(function () {
$('#username').on('keypress',function () {
var input = $('#username').val();
if(input.length>=4){
$.ajax({
url:'registration_php.php',
type: 'POST',
data:{username:input},
success:function () {
$.getJSON('registration_php.php',function (text) {
alert(text.user);
});
}
});
}
});
});
success:function(result) {
var items = JSON.parse(result);
alert(items['user']);
}
pass the result directly to your reponse as an argument like this
you should specify a dataType: "json" in your ajax call
var postData = JSON.stringify({
username: 'value'
});
var request = $.ajax({
url: "registration_php.php",
method: "POST",
dataType: "json",
data: postData,
});
request.success(function( results ) {
console.log(results)
});
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>
This is a sample of the php and javascript.
<form id="image-comment" method="post" action="includes/insert_image_comment.php">
<textarea id="comment-area" name="comment-area"></textarea>
</form>
// javascript
$("#image-comment").submit(function(event) {
event.preventDefault();
var action_url = event.currentTarget.action;
var id = 4;
var params = $("#image-comment").serializeArray();
params.push({imageid: id});
$.ajax({
url: action_url,
type: 'post',
data: params,
success: function(data) {
alert(data);
}
});
});
// insert_image_comment.php
echo $get_image = $_POST['imageid'];
$comment = $_POST['comment-area'];
When echoing $_POST['imageid'] i get an error 'Undefined index: imageid'.
When echoing $_POST['comment-area'] it's ok.
Why one works and the other not?
Thanks
Try to use the format that serializeArray uses: Example:
$("#image-comment").submit(function(event) {
event.preventDefault();
var id = 4;
var params = $("#image-comment").serializeArray();
params.push({name: 'imageid', value: id}); // this one
$.ajax({
url: document.URL,
type: 'POST',
data: params,
success: function(data) {
alert(data);
}
});
});
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>
$(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;
});