Question

Scripts:

$.post("<?php echo base_url(); ?>home/comment?"+$("#MYFORM").serialize(), {

                    }, function(response){

                    if(response.msg == '1')
                    {
                        .....
                    }
                    else
                    {
                                            ....
                    }
            }, "json"
            );

action:

function comment()
{   
    echo json_encode("msg=".$this->homemodel->comments());          
}

Problem: homemodel->comments returns either 1 or 0 The problem is that in response panel of firebug it shows echo value of action plus whole html pages. Therefore I can't take value of response.msg as 1 or 0. What's wrong with this code. What I have to change to return only value echo on comment action to the post jquery?

Was it helpful?

Solution

I'm not sure how you thing works or even what it should do, but something I usually do when i use $.post (or ajax) is that I add an extra parameter (ajax=1) in the post data so that i can know and do only the echo I want when its an ajax call. So basicly, on server side, it could look like this:

if (isset($_POST['ajax']) && $_POST['ajax']) {
   echo json_encode($anArray);
   die()
}

The die() function prevent the rest of the page to be echoed. This is quite usefull because you can create a file (we'll call this inc.ajax.php) which is included BEFORE ANY CODE IS ECHOED (let's say in header or first line in index.php, whatever) and you can use it as a controller. So you could add an operator, and inc.ajax.php would become your ajax controller. Taking back previous example:

if (isset($_POST['ajax']) && $_POST['ajax']) {
   $operator = $_POST['operator'];
   switch ($operator) {
     case 'upload':
        $obj->upload();
        echo json_encode($obj,true);
     break;
     default:
        echo json_encode($anArray);
     break;
   }
   die()
}

If inc.ajax is included in every page (on the index.php perhaps), it is easy to $.post() on the current url with ajax=1&operator=[your operator] and you'll always get the json you need (or response could still be html. In one operator, you could for example echo an entire template and then "die()" so that you just get the one portion of the website that you want.) Hope this helps, hope i didn't miss the point and surely hope i didn't confuse you with all that stuff!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top