Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass PHP Variable to AJAX Variable

After a completed calculation form where the total is loaded in via PHP we have 4 pieces of data (variables left over with PHP)

$totalprice; $totalduration; $totaldives; $totalhire;

At the moment the PHP ends with echo for each of these. The ajax then collects them like this.

success: function() {
                 $('#results').html();

The problem is that echos all results.

I would like to send the $totalprice to $('#resultsprice').html(); the $totalduration to $('#resultsduration').html(); etc etc...

Any ideas how to do that?

Marvellous

like image 294
RIK Avatar asked Aug 24 '26 20:08

RIK


2 Answers

You could return a JSON string from PHP:

echo json_encode( array('totalprice'=>$totalprice, 'totalduration'=>$totalduration, 'totaldives'=>$totaldives, 'totalhire'=>$totalhire));

Then, change your jquery ajax call to set the response to json:

$.ajax({
    url: your_url,
    dataType: 'json',
    success: function (data) {
        $('#resultsprice').html(data.totalprice);
        $('#resultsduration').html(data.totalduration);
    });
like image 79
Pherrymason Avatar answered Aug 27 '26 16:08

Pherrymason


Use the php function json_encode(). First in php create an array with the 4 variables. Json encode the array and echo the result. Then in jQuery use jQuery.parseJSON() to parse the json code to javascript variables. Here's an example:

PHP:

$data = array('var1' => 'value1', 'var2' => 'value2', 'var3' => 'value3', 'var4' => 'value14');
echo json_encode($data);

jQuery:

success: function(data) {
     data = jQuery.parseJSON(data);
}
like image 43
Ray Avatar answered Aug 27 '26 17:08

Ray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!