Welcome Guest, Not a member yet? Register   Sign In
Cannot use data returned from controller via ajax
#1

[eluser]Javatuan[/eluser]
Here is my view

Code:
<select name="producttypecode" id="producttypecode">
    <option value="GA02">GA027</option>
    <option value="GA04">GA047</option>
</select>
<div id='product' name='product'>test</div>

&lt; script language="JavaScript"&gt;
$(document).ready(function() {
    $('#producttypecode').change(function() {
        var producttypecode = $(this).val();
        $.post('index.php/product/productlist',
        {'producttypecode': producttypecode},
        function (data){
            alert (data);
            //$('#product').replaceWith(data.result);
        }, 'json');
    });
});
&lt;/ script&gt;

Here is my "product" controller

Code:
// for ajax request
function productlist(){
    $producttypecode = trim($this->input->post('producttypecode'));        
    
    $productSearch = array('TYPE_CODE' => $producttypecode);
    $productlist = $this->Product_model->getProduct($productSearch);
    echo 'processed';
    //echo json_encode($productlist);
}

In Firebug/NET, there's already the response of 'processed'. However, I cannot alert or use 'replaceWith' with the data returned. Is there any mistake here?

Thank you in advance!
#2

[eluser]InsiteFX[/eluser]
Your data should be json encoded before sending it to Ajax.

InsiteFX
#3

[eluser]intractve[/eluser]
Since you've told jQuery to look for a json string in return, just returning 'processed' will not work. It has to be a json encoded string.
And you can also not just alert an object (the data variable is an object not a simple string variable).

if you want to test the returned string as it is above, remove the ",json" from the $.post function. then you can alert data and you will see "processed"
#4

[eluser]Dennis Rasmussen[/eluser]
Tip: Use console.log() while using Firebug instead of alert()
This also gives you the content of the object while debugging.
#5

[eluser]Javatuan[/eluser]
Thank you all for json encoded and console.log(). I've received more than what I expected from my first question here Smile




Theme © iAndrew 2016 - Forum software by © MyBB