2

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

2

4 Answers 4

7

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);
    });
Sign up to request clarification or add additional context in comments.

1 Comment

Success function is missing closing parenthesis.
6

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);
}

Comments

3

Use JSON as data format.

In PHP, you can use json_encode to create a JSON string. compact is an easy way to create an associative array from variables:

echo json_encode(compact('totalprice', 'totalduration', 'totaldives', 'totalhire'));
// compact produces array('totalprice' => <value-of-totalprice>, ...)
// json_encode produces '{"totalprice": <value>, ...}'

In jQuery, set the dataType option to json and the argument passed to the success callback will be a JavaScript object:

$.ajax({
    // ... all other options ...
    dataType: 'json',
    success: function(data) {
        // use .html() only for HTML data
        $('#resultsprice').text(data.totalprice);
        $('#resultsduration').text(data.totalduration);
        //...
    }
});

Comments

2

What is actually returned from the AJAX call? If it's a JSON object containing the various values, you can set each one to various HTML elements. Something like this:

success: function(data) {
    $('#resultsprice').html(data.TotalPrice);
    $('#resultsduration').html(data.TotalDuration);
    // etc.
}

Comments

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.