I'm trying to display response.message as content to a tag with id test. It's getting displayed as undefined.
success:function(response){
console.log("response"+response); // works
var msg = response.message;
if(response.status=="success"){
console.log("response1"+msg);
document.getElementById('test').innerHTML = msg; //undefined
} else {
jQuery('#test').contents(msg);
document.getElementById('test').innerHTML = msg; //undefined
}
}
The way I normally handle this is parsing the JSON response for it to be made into a JavaScript object (Using JSON.parse), try this code below.
success: function(response) {
console.log("response" + response);
response = JSON.parse(response);
var msg = response.message; // works
if (response.status == "success") {
console.log("response1" + msg); // prints/works
document.getElementById('test').innerHTML = msg; //undefined
} else {
jQuery('#test').contents(msg);
document.getElementById('test').innerHTML = msg; //undefined
}
}
You should also be able to set the content type on the PHP page itself before the output using headers
header("Content-type:application/json");
You can also set the datatype to json in your ajax call which is pretty standard
$.ajax({
type: "POST",
url: "",
dataType: "json",
success: function(msg) {
//process success
}
...
});
The undefined isn't msg, the undefined is probably being return from document.getElementById('test')
.