Reuben Gomes Reuben Gomes - 2 months ago 5
PHP Question

jQuery array object to print only message key


I have this response from the server how do i print only the message
at the $('#message') div
the response was json_encoded php


{
"status":false,
"message":"<div id='errmsg' class='alert alert-danger'><button type='button' class='btn btn-info pull-right' id='remove'>Remove<\/button><p> Username Is Required<\/p>\n<p> Password Is Required<\/p>\n<p> Name Is Required<\/p>\n<p> Designation Is Required<\/p>\n<\/div>"
}


this is my axax code that im using iv

<script type="text/javascript">
$("#userform").submit(function(e) {
e.preventDefault();
var url = $(this).attr('action');
var formData = new FormData($(this)[0]);
$.ajax({
type: "POST",
url: url,
data: formData,
processData: false,
contentType: false,
success: function(data)
{
console.log(data);
$('#message').html(data.message);
}
});
});
</script>


I keep getting undefined if I try
data['message']

Answer

you have to pass dataType:'json' in ajax request option, so jQuery automatically convert JSON string into JSON object.

<script type="text/javascript">
    $("#userform").submit(function(e) {
e.preventDefault();
    var url = $(this).attr('action');
var formData = new FormData($(this)[0]);
    $.ajax({
           type: "POST",
           url: url,
           data:  formData, 
            processData: false,
        dataType: 'json',
           success: function(data)
           {
            console.log(data);
             $('#message').html(data.message);                     
           }
         });
});
</script>
Comments