tags:

views:

1802

answers:

2

Sounds like a weird question, but say I have something like this:

$.post( "/myajax.php",
        { "param1": value1, "param2": value2 },
        function( data, status ) {
            if( status == "success" ) {
               $("#someid").html( data );
            }
        }, "html" );

While myajax.php is doing whatever it needs to do, it decides that it does not need to make any changes to #someid. If it just returns, the someid element is blanked, but I want to leave it alone. How can the php query return in such a way that status != "success"?

+4  A: 

Wouldn't it be simpler to check on the data returned?

$.post( "/myajax.php", { 
     "param1": value1, 
     "param2": value2 
   }, function( data, status ) {
       if( data != "" ) {
           $("#someid").html( data );
       }
   }, 
   "html" 
);
Eran Galperin
yes and no, both are pretty basic ideas i guess, returning a non 200 OK seems more "right" given it changes the status code.
Owen
but how do you differentiate it from a real error? I think it's important for the request to complete correctly.
Eran Galperin
@Eran - I agree. Using the data parameter means you're filtering on the logic of the server-side code (correct), not the HTTP transaction (incorrect).
alastairs
Additionally, if you return a 4xx or 5xx error code and later decide to put in an error handler on the $.ajax() for failed AJAX requests, you're going to end up breaking the existing logic.
alastairs
I originally accepted Owen's answer, but upon reflection, I think I like Eran's idea better. They both work, FWIW, but I agree that this is cleaner.
Graeme Perrow
+4  A: 

the ajax calls treat any 200 OK as success. as such you could return something else from your PHP script to trigger an error in your ajax.

here are some other status codes in case you wanted to choose something more appropriate.

edit: i don't necessarily disagree with that approach, but i'm still leaning more towards operating on the status message (http status) rather than the response body.

my thoughts are, in a post transaction as the one mentioned, you are updating a resource. one could reasonably assume you expect one of two things two happen (in "success" conditions):

  1. a 200 OK means the content was posted without issue, and the resulting response typically is to show the new content. the ajax method "enforces" this behaviour by allowing you to get the response body to update your UI.

  2. in a scenario where the update does not need to be done, a 200 OK is fine as well (as the request was processed as expected), but perhaps as 204 No Content is better, as it suggests the request is fulfilled, but no change of the view is necessary. i'm leaning towards believing this is more inline with the ajax call as well, as you can ignore the response body (as there is none) and operate on the status (204? update UI to say "no changes were necessary" or similar)

Owen