Peter
Peter

Reputation: 1

Update Javascript variable from PHP without page reload

I am using jCart as shopping cart, and from jCart it's possible to get the variable $subtotal.

However, when changing something in the shopping cart, the variable $subtotal doesn't change until a page reload.

Is it possible to use jQuery to update $subtotal on page click with .click(function()) ?

Upvotes: 0

Views: 5411

Answers (3)

Sampo Sarrala
Sampo Sarrala

Reputation: 4868

It is a bit unclear what you are trying to do

But here is some suggestions.


Use jQuery to update Client side only:

If you need to update some visible value on web page, let's say you just need to increment or decrement subtotal displayed on web page then you can do this with jQuery without any server side processing.

Client side processing (Javascript / jQuery):

var subtotal = 0;

// Add value to subtotal and update div displaying subtotal
function addToSubtotal( value ) {
    subtotal += value;
    $('#subtotal').html(subtotal);
}

// When DOM is loaded...
$(document).ready( function(){
    // Bind onclick event to every <a class="buyme">
    $('.product').on('click', 'a.buyme', null, function(e){
        // Buyme link clicked, add <span class="pricetag"> value to subtotal:
        addToSubtotal( parseInt( $(this).siblings('.pricetag').html() ));
    });
});

Client side processing (HTML):

<div class="product">
    <a class="buyme" href="#">Add to subtotal</a><br/>
    <span class="pricetag">55</span>€
</div>
<br/>
<span id="subtotal">0</span>​​​​​​​​​​​

Or use jQuery.ajax() to update Server side:

You can use this to update JS variables too, especially needed if server checks and returns subtotal. In this case it is actually server that returns new subtotal value for you.

It seems that your PHP variable $subtotal is first read from some data storage system, it may look like it is always there it it is initially set for example when doing $myStore = new onlineStore();.

I assume that $subtotal is already available and contains some consistent integer value.

Code for AJAX update requests (server side and client side):

This will update server side PHP variables if properly used, and retrieve them for use with client side jQuery / Javascript.

However, this function will not do it out-of-box and should be only used as starting point for your complete implementation.

Client side processing (javascript/jquery):

function updateSubtotalAtServer( args ) {
    $.ajax({
        type: 'POST',
        url: 'processing.php', // <= Request url
        // Add method=ajax, we use PHP to check that value
        data: $(args).serialize()+"&method=ajax",
        // processing.php returned some data:
        success: function(data){
            // Try decoding data as JSON encoded string:
            try { 
                dataobj = $.parseJSON(data);
            } catch (e) { 
                dataobj = null;
            }
            // Check if JSON return value decoded successfully:
            if (dataobj !== null) {
                // Successfully decoded JSON, log values to console.
                // ...update subtotal <span> to display it for user:
                $('#subtotal').html( dataobj.subtotal );
                console.log( dataobj );
            } else {
                // Result was not JSON string (server error).
            }
        }
    });
}

// Create new object to be used as array:
var arrayobject = new Object;
// Add this value at server side to $subtotal:
arrayobject.addtosubtotal = 55;
// Then send ajax request to server:
updateSubtotalAtServer( yourvariables or array object );

Server side processing (php):

// Variable that needs updating:
/* $subtotal is already available, ..read above.. */ 

if (isset($_POST['method']) && $_POST['method'] == 'ajax') {
    // Update variables:
    $subtotal += (int)$_POST['addtosubtotal'];
    // Put all data together what is needed at client side:
    $ajaxreply = array( 'subtotal' => $subtotal, 'othervalue' => 'FooBar' );
    // Return it to browser:
    echo json_encode( $ajaxreply );
    // JSON reply will fail if there is any additional output after that.
    exit;
}

More reading / maybe helpful answers:
Another answer about jQuery.ajax, focusing on REST, forms and data arrays
Another answer about jQuety.ajax, fetch data from server

Upvotes: 0

Nanne
Nanne

Reputation: 64399

The question is flawed to begin with.

PHP runs server side. When all PHP is done, it gets presented to the browser and all the variables are gone. Maybe you're echoing some of them, so they are "there" in literal format, but there is no PHP variable anymore to update.

You can update something, like a javascript variable that you have filled before trough PHP, or a HTML value that got set by PHP. This can be done by reload, or this can be done by using an AJAX post, then some PHP magic, then a return + assign, but you are NOT replacing/reloading any PHP variables.

It is REALLY important to understand that there is no $subtotal anymore whatsoever after you've send the page to the browser. Please look into server side versus client side!

Upvotes: 3

Nick Fury
Nick Fury

Reputation: 1313

I made you a JSFiddle of an ajax post example here (without page reload): http://jsfiddle.net/5RjUt/1/

JQUERY

$("#button").click(function(){ // click function fired

var subtotal = $("#subtotal").val()
var dataString = 'subtotal=' + subtotal;

$.ajax({ // ajax post
    type: "POST",
    url: "YOUR_PHP_PAGE.php", // post data to this URL
    data: dataString,
    cache: false,
    success: function(html){ // this is where you can set a success callback
       $("#subtotal").val("You're new value");
    }
});
return false; // this tells the page not to refresh

)};​

Upvotes: 0

Related Questions