views:

60

answers:

5

Hello, I'm having an annoying issue, on complete i get undefined when trying to make simple url validation. success working fine.

i get a valid json response:

{"error":"some error"}

and this is my jQuery

$("#myform").submit(function(){
            dataString = $("#myform").serialize();
            $.ajax({
                type:       "GET",
                url:        "myform.php",
                data:       $.URLDecode(dataString), //fixing url problem
                dataType:   "json",
                beforeSend: function(){ 
                        $('#search').append('<img src="images/ajax-loader.gif" />'); //loader
                        $('.error').remove(); //removes every submit
                    }, 
                success:    function(data){
                                    $('<span class="error">' + data.error + '</span>').appendTo($('#search'));

                            },
                complete:   function(data){ 
                                $('#search img').fadeOut(); //removes loader
                                    alert(data.error);

                }

            });
            return false;  //force ajax submit
        });

Any hint please?

A: 

try "alert(data.responseText);"

i think the problem lies in your thinking that the server is sending back your "error" object as the "data" variable. in the "complete" callback, the "data" variable is actually an XMLHTTPRequest object.

marduk
A: 

maybe $.URLDecode() returns not JSON key/value structure

Mouster
A: 

I think you want URLEncode not URLDecode? Either way I'd recommend fiddler for debugging issues like this - it'll show you exactly what's being sent to/from the server.

Tom Carver
A: 

As per the docs, the complete event doesn't hold your json response.

Why do you need to define the complete handler and the success handler? Just define success.

thenduks
+1  A: 

If you look at the docs:

complete(XMLHttpRequest, textStatus)

A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The XMLHttpRequest object and a string describing the status of the request. This is an Ajax Event.

Data is not a return value from your method.

If you're using firebug, use console.log(XMLHttpRequest) and you'll see what it includes.

You can also do this (quick - using eval here - not recommended.)

var err = eval("(" + XMLHttpRequest.responseText + ")");
alert(err.Message);
ScottE
I see, basically i don't really want to alert data.error, that was just an example. but i need json values to be passed to the complete function. well i'll try to work this around, thanks.
JQman
Like others have said, the data is not available here. Use .success instead.
ScottE