JSON returning as undefined
Hello I have an aj开发者_JAVA百科ax request that submits a form and sends and email, if the email is submitted successfully, I encode a PHP array that looks like this,
$success = array("state" => "Email Sent");
I am then checking the state of data
in my ajax request to see if state
matches "Email Sent" however when I alert(data)
i get undefined, what am I doing wrong? Below is my javascript,
$.ajax({
url: "<?php echo base_url(); ?>home/callback",
data: $("#callback").serialize(),
type: "POST",
dataType: "JSON",
success: function(data){
$("#fancybox-content div").html(data);
alert(data.state);
}
});
Try to get the html value of the 'fancybox-content' div. $('#fancybox-content').html();
If you alert is failing then are you sure your json is valid? Can you paste it into your question. You can validate it here online at JsonLint.
how do you return the $succes
array?
You should echo
the array in a way that would preserve it's format and would be understandable to javascript (not print_r
or var_dump
):
echo json_decode($success);
that will return a json string representing your php array, which js automatically converts into an object.
Hope this helps.
use
json_decode($success, true);
When TRUE, returned objects will be converted into associative arrays.
精彩评论