2

I have made an AJAX function with jQuery. The function works properly, and server return a JSON, but I can't use it in my JS script

Server side :

$array = array();

$array["count"] = count($accounts_list)."";

    for($i=0; $i<count($accounts_list); $i++)
    {
        $account = $accounts_list[$i];

        $array["marker"]["name"] = $account->name;
        $array["marker"]["lat"] = $account->map_latitude;
        $array["marker"]["lon"] = $account->map_longitude;
    }

    echo json_encode($array);

Client side :

$.ajax({  
    type: "POST",  
    url: "index.php?module=cap_Maps&action=AddMarkers", 
    data: dataString, 
    dataType: "json",
    success: function(data) {
        if (data == "error"){
            $(".tr_legend").before("<tr><td colspan='2' id='error'><span class='error_maps'>Erreur lors du chargement des marqueurs</span><td><tr>");
        }
        else {
            alert(data);
                var obj = jQuery.parseJSON( data )
                alert (obj.count);
        }

    }  
});

JSON returns by server:

{"count":"371","marker":{"name":"WAMPFLER","lat":"49.02751610","lon":"2.10611230"}}

Function alert(data) returns my JSON, but if I try to parse it with jQuery.parseJSON( data ), It doesn't work and alert(obj.count); doesn't open.

EDIT

I have add error function:

error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("XMLHttpRequest="+XMLHttpRequest.responseText+"\ntextStatus="+textStatus+"\nerrorThrown="+errorThrown);
                },

And error occured :

XMLHttpRequest={"count":"358"}
textStatus=parsererror
errorThrown=Invalid JSON: {"count":"358"}

EDIT

If I had contentType: "application/json", in my AJAX, I can return a static string which is considered as json, but if I try to execute other php code on my server, AJAX returns an 500 Internal server error

4
  • The similar question is asked before solution Check this out. Hope this helps Commented May 6, 2011 at 9:14
  • I really don't understand why jQuery throws this error; {"count":"358"} is completely valid. Commented May 6, 2011 at 14:32
  • Can I send an associative array instead of JSON ? If I do this, I will not have problems with JSON ;) Commented May 9, 2011 at 8:18
  • Have you ever tried jQuery.getJSON() instead of jQuery.parseJSON()? (Converted the answer to a comment). Commented Aug 13, 2012 at 10:30

5 Answers 5

1

Try this :

var json = jQuery.parseJSON('{"count":"371","marker":{"name":"WAMPFLER","lat":"49.02751610","lon":"2.10611230"}}');

alert(json.count);

maybe you forget to give a string ' ' to parseJSON.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I have forgotten quotes around data, but if I try to add this. I have an error in firebug JSON.parse [Stopper sur une erreur] (function(a,b){function cw(a){return f...a:a+"px")}}),a.jQuery=a.$=f})(window);
0

From jQuery.ajax:

The json type parses the fetched data file as a JavaScript object and returns the constructed object as the result data.

So you don't need jQuery.parseJSON, as the returned string already is parsed.

6 Comments

I just discover dataType: "json" make error : I can't execute function success. When I try alert(data.count), it 's undefined, so I think it isn't parse.
@Corum: Then add an error callback function and see what the error is.
If I specify dataType: "json", code which is after isn't executed. If I remove this line and spy jQuery.parseJSON(data) with Firebug, I have error Invalid JSON: [{"count":"358"}]
@Corum: Yes, that's exactly why I proposed to add an error handler and see what the error is.
@Corum: please read the documentation: “A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." ”
|
0

instead of using parseJson can you try just using eval.

$.ajax({  
    type: "POST",  
    url: "index.php?module=cap_Maps&action=AddMarkers", 
    data: dataString, 
    dataType: "text",
    success: function(data) {
        if (data == "error"){
            $(".tr_legend").before("<tr><td colspan='2' id='error'><span class='error_maps'>Erreur lors du chargement des marqueurs</span><td><tr>");
        }
        else {
            alert(data);
                var obj = eval(data);
                alert (obj.count);
        }

    }  
});

HTH.

Comments

0

It looks like you are not sending the JSON with proper format from your server try to use json_encode() function.

Comments

0

The output buffer didn't empty so AJAX received buffer content + JSON so it wasn't a valid JSON.

I use ob_clean() on server side just before output my JSON and it solves the problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.