Adib
Adib

Reputation: 369

Passing php string as json to be received by jquery

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.

Upvotes: 1

Views: 792

Answers (4)

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

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");
        }
    }
});

Upvotes: 2

duduwe
duduwe

Reputation: 1260

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

Upvotes: 0

Oooogi
Oooogi

Reputation: 383

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".

Upvotes: 0

pritesh
pritesh

Reputation: 543

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.

Upvotes: 0

Related Questions