5

I'm trying to build an ajax-powered shopping cart in codeigniter, and now I'm facing a problem with how to get the response as a HTML, and encode it as a JSON response, then append the shopping cart page with the response.

Here is the javascript code:

$('.addtocart').on('click', function (event) {
    event.preventDefault();
    var AddedQty = parseInt($('#attr-quantity').val());

    $('#shoppingcart div.cart, #shoppingcart div.loading').remove();
    $('#shoppingcart').append('<div class="loading"></div>');
    shoppingcart.open();

    $.post('/mywebsite/cart/add', {
        itemId: $('.addtocart').data('itemId'),
        quantity: AddedQty
    }, function (response) { 
        var html = $(response.ShoppingCartHtml).html(); 
        shoppingcart.update(html);
        shoppingcart.close();
    });
});

And this is the code for the cart controller:

public function add() {     
    $this->load->model('cart_model');
    $id = $this->input->post('itemId');
    $qty = $this->input->post('quantity');
    $cart = $this->cart->contents();
    $exists = false;
    $rowid = '';

    foreach ($cart as $item) {
        if ($item['id'] == $id) {
            $exists = true;
            $rowid = $item['rowid'];
            $qty = $item['qty'] + $qty;
        }
    }

    if ($exists) {
        $this->cart_model->update_item($rowid, $qty);          
    } else {
        $this->cart_model->add_cart_item();
    }

    $this->output->set_content_type('application/json');
    $this->output->set_output(json_encode(array('ShoppingCartHtml'=> $theHTMLResponse)));
}

And the code below is the sample code (not the real code) that I want to encode it as the JSON response, as the ShoppingCartHtml:

<li>
    <h3><?php echo $ProductName; ?></h3>
</li>

So far, I've tried to echo the view, and encode it using the json_encode, but I get an error. Here is what I've come with:

$theHTMLResponse= echo $this->load->view('pages/minicart.php', $data); //THIS LINE THROWS ERROR (I know that I cannot assign what echo-ed into a variable).
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode(array('ShoppingCartHtml'=> $theHTMLResponse)));

The example of the correct response that we wanted is like the codes below (as shown in Firebug) :

{"MinicartHtml":"\u003cli\u003e\r\n\u003ch3\u003eThe Product Name\u003c/h3\u003e\u003c/li\u003e"}

Which if I inspected in the Firebug console, on the JSON tab, it should shows the ShoppingCartHtml's html codes, enclosed with quotes, as the ShoppingCartHtml JSON Response.

The question is: How can I encode the ShoppingCartHtml's html codes as a JSON response?

PS: My apologize if my question is confusing. English is not my cup of tea. Even to type this question, I need almost 1 hour to complete it. But I hope you guys understand what I asked.

Thank you in advance.

3 Answers 3

8

You were close to getting it right. Just a couple of adjustments needed.

//set the 3rd param to true to make it return data 
$theHTMLResponse    = $this->load->view('path/to/view.php', null, true);

$this->output->set_content_type('application/json');
$this->output->set_output(json_encode(array('ShoppingCartHtml'=> $theHTMLResponse)));
Sign up to request clarification or add additional context in comments.

2 Comments

OMG! Thank you very much for the help! I really didn't know that it just needed a simple adjustments! Thank you very much! I've been stucked with this problem for 3 days! After I read your answer then I remembered about the 3rd parameter in codeigniter load view. :)
of course "set the 3rd param to true to make it return data" :)
0

I suppose shoppingcart is set to something returned from $('#...'). Then you need only this:

function (response) { 
    shoppingcart.html(response.ShoppingCartHtml); 
    shoppingcart.close();
}

Comments

0

First pass the third parameter in your view call as true

There is a third optional parameter lets you change the behavior of the function so that it returns data as a string rather than sending it to your browser. This can be useful if you want to process the data in some way. If you set the parameter to true (boolean) it will return data. The default behavior is false, which sends it to your browser. Remember to assign it to a variable if you want the data returned

$theHTMLResponse= echo $this->load->view('pages/minicart.php', $data,true); //THIS LINE THROWS ERROR (I know that I cannot assign what echo-ed into a variable).
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode(
array( 'sucesss'=>1, 'ShoppingCartHtml'=> $theHTMLResponse)
));

Also use $.getJSON and replace $(response.ShoppingCartHtml).html(); from response.ShoppingCartHtml

$.getJSON('/mywebsite/cart/add', {
        itemId: $('.addtocart').data('itemId'),
        quantity: AddedQty
    }, function (response) { 
     if(response.success){
        var html = response.ShoppingCartHtml; 
        shoppingcart.update(html);
        shoppingcart.close();
      }
});

views

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.