views:

119

answers:

2

Hello,

I'm wondering what is the best method to handle AJAX calls with jQuery? Right now I'm doing something like following:

$("#test").live('click', function(){
    // Process form
    $.ajax({
        type: "post",
        url: "test.php",
        success: function(html){
            if(html.success == 0) {
                alert('Error');
            } else {
                var obj = $.parseJSON(html.rows);
                $("#success").html(obj[0].name);
            }
        },
        dataType:'json'
    }); 
    return false;
});

In test.php file, I'm checking if request is an AJAX request. If it's an AJAX request I'm running a database query to get some data (this part isn't important in this question, I think):

// query goes here
if(mysql_num_rows($query) > 0 ) {
    $result['success'] = 1;
    $result['data'] = json_encode($data);
} else {
    $result['success'] = 0;
}

Now I'm wondering if my method is the best possible? FYI I'm using KohanaPHP framework currently, so I want to not break MVC "rules". If I'm doing it wrong, do you have any tips and suggestions how to handle AJAX calls in controllers?

Regards, Tom

+1  A: 

What you have looks good here, though I don't think you need a $.parseJSON() there, it should already be an object at that point, this should work:

$("#success").html(html.rows[0].name);

As a side note, from a readability/maintainability perspective, I'd rename your html argument to be data, like this:

success: function(data) {

This is purely preference, but using html when it's an HTML type response, and data or something else when it's JSON/already an object you're expecting keeps things a bit easier to read for outsiders.

Nick Craver
Thanks for your answer Nick. I'm really glad to hear I'm doing it correct way, spent over few hours on reading jQuery manual. BTW... I was wondering the same way about an object, but when I tried `$("#success").html(html.rows[0].name);` before it just does not work. Wondering why?
Tom
@Tom - If you `console.log(html.rows)` what are you getting in your console (Firebug/Chrome)? Is it still a string or an object?
Nick Craver
@Nick - For unknown reason, it's a string.
Tom
@Tom - Hmm that's definitely a server-side problem there, may want to ask a question specifically on that (be sure to tag it `kohana`, `php` and `json`, that's a different audience that can help better), your client-side looks good, if we can fix the server bit, you can just improve it with the parsing removal :)
Nick Craver
Nick, thanks a lot for your answer and comments and generally for your time you spent on my question! Appreciated! Have a nice day!
Tom
@Tom - Welcome :) The PHP guys can help you pretty qucikly with the encoding, should be a simple issue...been far too long for me to raddle PHP off the top of my head, most of the JSON functions weren't there the last time I did a project in it :)
Nick Craver
A: 

@tom - you need to encode the PHP array like this:

$data = array(
    'status' => 'success'
);

echo json_encode($data);

But you might want to change the array structure a little. Since the xhr object has a text status I usually encode an JSON array like this:

$response = array(
    'status' => 'success' // or flash or error
    ,'flash' => array(
                   'header' => 'whatever is wrong with submission of data html list format'
                   'fields' => array('field names to be highlighted')
                   )

    ,'html'  => 'html presentation'
    ,'data   => array('json data')
);

echo json_encode($response);

Now you can do some nice things like this:

           ,success:    function(response) {
                if (response.status === 'success') {
                    $('.basic_container').hide();
                    that.removeDataTable();
                    that.getContent(contentUrl);
                    $('.basic_container').show();
                }
                if (response.status === 'flash') {
                    $('#flash').html(response.flash.header);
                    $('#flash').show();
                    that.highlightWithFlash(response.flash.fields);
                }
            }
Gutzofter