Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ajax is producing [object object]?

I'm getting an [object object] from my ajax response.

        $.ajax({
            type: "GET",
            data: "id_1="+id_1+"&id_2="+id_2,
            url:"ajax/url.php"
        }).done(function(data){
            var left= $(data).find("#left");
        $("#left").html(left);
            alert(left);


        });

In my url, I just have a simple coding

if(isset($_GET["id_1"]) && isset($_GET['id_2'])){
    $id_1 = $_GET["id_1"];
    $id_2 = $_GET['id_2'];

    $right= $dbh->prepare("SELECT COUNT(*) FROM table WHERE id_1 = ?");
    $right->execute(array($id_1));
    $left= $dbh->prepare("SELECT COUNT(*) FROM table WHERE id_1 = ? ");
    $left->execute(array($id_2));


    <div id='right'><?php echo $right->fetchColumn();?></div>

    <div id='left'><?php echo $left->fetchColumn();?></div>



}

When I this is all done, it alerts back [object object]

anyone know why it does that?

Thanks!

EDIT:

I added some coding in the .done(function())

like image 387
hellomello Avatar asked Mar 28 '12 03:03

hellomello


2 Answers

data is an object. [object Object] is just the object's toString() response.

You need to access the object's data. Try using console.log(data) to check its contents.

It looks like from your PHP example that you have not provided the code as is. The code you posted will be a syntax error.

Also, check the MIME type of your response. You may want to force the dataType as html.

like image 194
alex Avatar answered Sep 28 '22 19:09

alex


I Have solved my problem. The issue was that I needed to wrap my div's within another . After that the find() method would be able to capture those id's and return the proper objects.

if(isset($_GET["id_1"]) && isset($_GET['id_2'])){
    $id_1 = $_GET["id_1"];
    $id_2 = $_GET['id_2'];

    $right= $dbh->prepare("SELECT COUNT(*) FROM table WHERE id_1 = ?");
    $right->execute(array($id_1));
    $left= $dbh->prepare("SELECT COUNT(*) FROM table WHERE id_1 = ? ");
    $left->execute(array($id_2));

<div> // wrapper
    <div id='right'><?php echo $right->fetchColumn();?></div>

    <div id='left'><?php echo $left->fetchColumn();?></div>
</div>



}
like image 32
hellomello Avatar answered Sep 28 '22 19:09

hellomello