json2021
json2021

Reputation: 2317

Need help returning a json string after a successful jquery $.post()

I am posting to a php page that is returning the following json encoded string

{"msg":"Hi {{full_name}}, <br \/>\r\n<br \/>\r\n  It was nice meeting you."}

I had added that json object in the <script> </script>

However when run the $.post() and try to output data.msg it says undefined.

Here is the full code

  $.post("mass_messaging.php",{template_id: template_id})

        .done(function(data){

            console.log(data.msg)
            //Outputs undefined??? 


        });

Below is a snippet of my html code

<script>

addMustachePlaceHolder();

{"msg":"Hi {{full_name}}, <br \/>\r\n<br \/>\r\n  It was nice meeting you."}

</script>

Any help would be really appreciated.

Upvotes: 0

Views: 40

Answers (3)

Jakir Hossain
Jakir Hossain

Reputation: 2517

var obj = jQuery.parseJSON( data );
console.log(obj.msg);

Upvotes: 0

jeroen
jeroen

Reputation: 91742

You probably need to parse the json as it is a string and you need an object. jQuery can do that automatically if you set the data type:

$.post("mass_messaging.php", {template_id: template_id}, function(){}, "json")
                                                                       ^^^^^^ here

Apart from that it is not entirely clear what you are returning. You should only return one valid json string from your php script and nothing else; no script tags, javascript, etc.

Upvotes: 2

json2021
json2021

Reputation: 2317

I found the answer. I was using json_encode() which was returning a json string.

So i just used data = JSON.parse(data);

and it worked!

Below is what I did

$.post("mass_messaging.php",{template_id: template_id})

    .done(function(data){

       data = JSON.parse(data);

            console.log(data.msg);



    });

Upvotes: 1

Related Questions