0

I'm making my first website and I've encountered a problem with AJAX. I have tried and searched a lot of things but I'm missing something, please help me on this one. I have products' count and it works fine, but I need to refresh page everytime when I add new product to cart to see difference, so I need to use AJAX on my php variable. Please help me write AJAX code. I really appreciate it, thanks a lot and have a good day!

PHP Code:

<?php
 $cart = new cart(); 
 $products = $cart->getCart(); 
 $sum = 0; 
 foreach($products as $product){ 
     $sum += $product->count;
 } 
 echo $sum; 
?>  
3
  • You need to expose a REST API for your cart if you want to do an Ajax update. Commented Mar 30, 2017 at 11:39
  • @Webbanditten my cart works fine, I have problem displaying products' count on top of my shopping cart logo on main page. But I will upload my cart.php and main.js if thats the case Commented Mar 30, 2017 at 11:50
  • Hi, welcome to the site. I think you should have a look for some basic introductions to AJAX if you're having trouble understanding it. If you do understand it, but are having some particular problem with your implementation, then try to clarify your question a bit. At the moment, it's not clear how the PHP code you show relates to your problem. Commented Mar 30, 2017 at 11:55

2 Answers 2

1

You could perform an ajax request like this. Your php will return the content which can then be appled to the DOM.

// create array to POST
aData = {
    AjaxRequest:true,
    PostField2:'content',
}


// perform ajax request 
$.ajax({
    type: "POST",
    url: "/relative_path_to_script/",
    data: aData,
    cache: false,
    success : function(data){
        console.log( 'response:' + data );
        $('#cartCountID').html(data);
    },

    failure : function(data){
        // report any ajax errors
    },

    complete : function(data){
        // runs once on completion
    }

});
Sign up to request clarification or add additional context in comments.

1 Comment

more than welcome. Let me know if you need help detecting the request in php :)
0

This can be done by adding the following code

$.ajax({
                type: "GET",
                url: "your url",
                data: "",
                success: function () {
                        setInterval(functionName,timeInMilliseconds);                         
        }
  functionName=function(){
//your code comes here which you want to get refreshed
}

Using this code after a flag which will test with an if condition that the product count is updated or not. Cheers.

1 Comment

Thank you for your answer, man. I really appreciate it, have a good day and good luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.