1

I am trying to echo a string which is structured like json, but the jquery ajax post is not able to parse it properly. What I want to know is if this string will be treated like json in the jquery json parse just like when we echo a json_encode.

echo '{"mobno":'.$mobno.',"charge":'.$charge.',"capacity":'.$capacity.'}';

ajax code:

jQuery.ajax({
       type: "POST",
       url: "file.php",
       data: { type: $(this).val(), amount: $("#amount").val()},
       cache: false,
       success: function(response){

            var Vals = JSON.parse(response); 

            if(!Vals){
                alert("Error1");
            }else{
                var capacity = parseInt(Vals.capacity);
                if(capacity>0){

                   alert("worked1");

                }else{
                    alert("worked2");
                }

            }
        }
    });

I don't get a single alert out of the 3.

Adib
  • 359
  • 1
  • 6
  • 16
  • You corrected your ajax... really made me wonder how it became Vals.capacity. My answer became irrelevant instantly. Anyways, you have a syntax error in your json string apart from the Vals.length issue. @Rajdeep Paul pointed out the string issue for you. Glad you solved it. And just in case you want to get the count/length, I undeleted my answer for your reference. – duduwe Feb 07 '16 at 12:36

4 Answers4

2

As per your edit and comment, your json string is correct. You just have to change your AJAX request.

Add this setting dataType: "json" in your AJAX request if you're expecting a json object as response from server.

So your AJAX request should be like this:

jQuery.ajax({
    type: "POST",
    url: "file.php",
    data: { type: $(this).val(), amount: $("#amount").val()},
    cache: false,
    dataType: "json",

    success: function(response){
        // you can access json properties like this:
        // response.mobno
        // response.charge
        // response.capacity

        var capacity = response.capacity;
        if(capacity > 0){
            alert("worked1");
        }else{
            alert("worked2");
        }
    }
});
Community
  • 1
  • 1
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
  • tried, still not working :( are u sure that the json return is not an array but a string? – Adib Feb 07 '16 at 10:04
  • @KimJongUn How are you processing this json string? Please update the question with your AJAX code. And also [see this comment](http://stackoverflow.com/questions/35250223/passing-php-string-as-json-to-be-received-by-jquery/35251290#comment58215520_35251290). – Rajdeep Paul Feb 07 '16 at 10:19
  • @KimJongUn `Vals.count`? Your json string doesn't have `count` property. From where this count property came? – Rajdeep Paul Feb 07 '16 at 12:19
  • @KimJongUn Glad I could help. :-) And one more thing, `mobno`, `charge`, `capacity`, are these numeric values? Because only that way your [edited json string](http://stackoverflow.com/revisions/35250223/5) can be correct. – Rajdeep Paul Feb 07 '16 at 12:41
  • @KimJongUn I thought so. :-) – Rajdeep Paul Feb 07 '16 at 12:44
  • Just a minor correction, count == response.capacity and the associated conditions are illogical. Nevertheless, this solved the basic issue. Cheers. – duduwe Feb 07 '16 at 12:47
  • I've updated my answer so that it could be useful for the future visitors of SO. – Rajdeep Paul Feb 07 '16 at 13:01
0

Just so JavaScript can differ string and properties of json, please use double quote for starting and ending the string and for json properties use single quote or vice-versa. Try that out and let me know if you could not figure that out.

pritesh
  • 533
  • 4
  • 15
  • tried, still not working :( are u sure that the json return is not an array but a string? – Adib Feb 07 '16 at 10:04
0

As other answers suggest you need to fix the quotes of the JSON the web service is sending back in the response.

Regarding you question, everything sent back in the response is actually a string. You need to decide what to do with it once it arrives.

One of the ways to allow both client side and server side programs understand what was sent is setting the right content type header.

For JSON the best way is to set the content type header to "application/json". If you're using php you can do this:

$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);

On the client side jquery ajax you can do this:

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: function(data, textStatus, jqXHR){}
});

In this example the "data" parameter passed to the "success" callback function is already a js object (after JSON.parse). This is due to the use of the "dataType" parameter in the ajax declaration.

Optionally, you can do this manually and write a simple $.post which receives a string and do the JSON.parse yourself.

Maybe you should do the manual parsing yourself at first, and use the console.log(data) before and after the parsing so you'd know you're doing it correctly. Then, move on to the automatic way with "dataType" set to "json".

Oooogi
  • 383
  • 4
  • 14
  • tried, still not working :( are u sure that the json return is not an array but a string? – Adib Feb 07 '16 at 10:04
  • Everything passed in an HTTP request/response is a string. Anything but a string must be serialized to a string before the transport. That's why we're using json_encode($data), in order to serialize everything in $data into a string (JSON is string). – Oooogi Feb 09 '16 at 08:53
  • Please debug the process. In the browser press F12 and look for thrown errors in the Console. Also goto the Network tab (in all major browsers) and look for the ajax call. Look at the request and the response and write here what is says. – Oooogi Feb 09 '16 at 08:57
0

Please see @Rajdeep Paul's JSON string correction. Then, have your response JSON object remapped to an array.

JSON string

echo "{\"mobno\":\"".$mobno."\",\"charge\":\"".$charge."\",\"capacity\":\"".$capacity."\"}";

Ajax

$.ajax({
   type: "POST",
   url: "file.php",
   data: { type: $(this).val(), amount: $("#amount").val()},
   cache: false,
   success: function(response){

        // map JSON object to one-dimensional array
        var Vals = $.map( JSON.parse(response), function(el) { return el });

        if(!Vals){
            alert("Error1");
        }else{
            var count = parseInt(Vals.length);

            if(count>0){

               alert("worked1");

            }else{
                alert("worked2");
            }

        }
    }
});

Reference: Converting JSON Object into Javascript array

Community
  • 1
  • 1
duduwe
  • 888
  • 7
  • 16