tags:

views:

58

answers:

4

Hi, I want to check in client side(jQuery) whether return data from a PHP function is Json object or String to assign different function.

+1  A: 

In javascript, you can use typeof

orolo
How to tell if `typeof(A) != typeof(B)`, where `A` and `B` are strings...? :-)
pst
Thanks for yr advice but typeof is not working for my example :)
Devyn
+4  A: 

Return data is always a string (i.e., a character sequence). But, if you tell jQuery you expect json response, it'll attempt to convert string into a javascript object for you.
There's no dedicated network protocol to transfer javascript objects over the internet.

Nikita Rybak
+2  A: 

jQuery's parseJson will generate an exception if the json is not in the correct format. You could wrap your call in a try catch block. (But remember that having exceptions in your normal code's flow is bad practice)

data = '{}';
try {
    json = $.parseJSON(data);
} catch (e) {
    // not json
}
Yarek T
Thanks for your fast reply but I'm a little confuse with bad practice. You mean I shouldn't try to solve my problem with parseJSON's exception?
Devyn
No, firing exceptions in normal execution is a bad practice. Exeptions should only be fired when something is wrong (when you don't expect some result)
Yarek T
+3  A: 
try {
   jQuery.parseJSON( json )
   //must be valid JSON
} catch(e) {
    //must not be valid JSON    
}
FatherStorm