views:

2057

answers:

5

I'm trying to write a simple JSON post and the callback alert does not show up no matter what I do. I used firebugs to see if the post was getting any response and "SHOE" returns. So why is the alert not working in the callback?

view code:

$('#GaragePartAddfrompartlistForm').click(function() { 
      var item = "CHEESE"; 
  $.post("garage_parts/getlastid", { 'item' : item }, 
   function(data){ 
     alert(data.result); 
   }, "json"); 
    });

controller code:

function getlastid() { 
    $newid = "SHOE"; 
        $array = array('result' => $newid); 
        echo json_encode($array); 
    }
A: 

You should try setting the HTTP header in the response with:

header("Content-type: application/json")

or

header("Content-type: text/plain")

jQuery might not be handling your response because it is not getting the expected type back.

Your response code would then be:

function getlastid() { 
    header("Content-type: text/plain");
    $newid = "SHOE"; 
    $array = array('result' => $newid); 
    echo json_encode($array); 
}

Hope this helps!

Stephen Delano
A: 

Don't forget to set empty layout for Ajax responses:

function getlastid() { 
    $this->layout = 'ajax';
    ...
Sergei
A: 

I'm not too familiar with cake, but I use codeigniter (which is similar)...

One thing I have noticed with framework like these, is that when you send out a json response using echo json_encode($array) you have to enter exit(); immediately on the next line. Other wise, the framework sends out headers indicating a html mime-type.

May be that is the case with cake too, in any case it's worth a try...

pǝlɐɥʞ
+3  A: 

Make sure you're setting debug to 0 in beforeFilter, use RequestHandler component to check if it is an ajax request.

Use RequestHandler

var $components = array(..., 'RequestHandler', ...);

set debug to 0 if it's an ajax request

function beforeFilter()
{
    if ($this->RequestHandler->isAjax()) {
        Configure::write('debug', 0);
    }
}

and in your function

function getlastid() 
{
    $this->autoRender = false;
    $this->autoLayout = false;

    $newid = "SHOE";
    $response = array('result' => $newid); 

    $this->header('Content-Type: application/json');
    echo json_encode($response);
    return;
}

If you echo json and don't set debug to 0, cake will add the execution time at the end and it will not be a valid json response, preventing jQuery to properly read it.

As an extra, usually i set some more stuff in the $response, so i can better handle it.

function getLastId()
{
    ...
    $response = array('success' => false);

    ... code ...
    if ($my_code_is_good) {
        $response['success'] = true;
        $response['data'] = $my_code_result;
    }

    ...
}

Hope this helps

Leite
Hi,so I noticed that if I change the type from "json" to "JSON" it prints the alert. However, if I try to print data.result in the alert, the alert prints "undefined". If I print data, the alert responds with "{"result":"SHOE"}". This is weird... why is the JSON not working properly?
Hooman Ahmadi
Have you used Firebug to see what the response from the server looks like? The problem is jQuery isn't detecting the response as json, so, if you just alert "data", it shows you a string, and if you try to access a property, like "data.result", since it's a string, you get undefined
Leite
how do i get jquery to detect the response as json?
Hooman Ahmadi
It should. I usually use $.ajax instead of $.post, but it's the same thing. As i've said, if you don't have firebug, install it and check what is the response from the server. The sample codes i've posted is very similar to what i usually do.
Leite
the POST response from getlastid is {"result":"SHOE"} and the JSON in firebug shows that it has "result" associated with "SHOE". This is the case, even if I try to print data.result
Hooman Ahmadi
I changed it to .ajax and now it alerts "[object Object]"
Hooman Ahmadi
nevermind... got it to work!! it was all about the Configure::write('debug', 0); I really appreciate your help thanks so much!!!
Hooman Ahmadi
A: 

I found that with my symfony/PHP application, ordinary text responses with no HTML characters (either using a null or a 'json' dataType) would trigger the success callback. However if the server does not output anything except headers, the success callback is not called (which I would consider a bug).

Furthermore, if the server response contained HTML characters (<> etc), again the callback would not be called unless the context type is explicitly set to text/html. This also removed annoying < pre> tags added incorrectly by jQuery as well as preventing jQuery from converting the response to HTML entities (& lt;& gt; etc).

Jon