CodeIgniter Forums
Cannot use data returned from controller via ajax - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Cannot use data returned from controller via ajax (/showthread.php?tid=38602)



Cannot use data returned from controller via ajax - El Forum - 02-12-2011

[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!


Cannot use data returned from controller via ajax - El Forum - 02-12-2011

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

InsiteFX


Cannot use data returned from controller via ajax - El Forum - 02-13-2011

[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"


Cannot use data returned from controller via ajax - El Forum - 02-13-2011

[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.


Cannot use data returned from controller via ajax - El Forum - 02-13-2011

[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