chris227 chris227 - 1 month ago 9x
Ajax Question

ajax success: function (msg) undefined

Hello i have this script that returns msg undefined. In consol it returns jsondata but when i do an alert or when i'm trying to verify it, it does not work.

$(function() {
$(".aplica_bt").click(function(e) {
var href = $(this).attr('href');

url: href,

datatype: "json",
success: function(msg) {
if (msg.exista == "yes") {
alert('ai aplicat');
if (msg.aplicat == "yes") {

enter image description here

also here is the php code that returns json



$stmt=$dbh->prepare("SELECT * FROM Aplicatii where id_c=:id_c and id_j=:id_j");
$arr = array('exista' => 'yes');
echo json_encode($arr);
$stmt=$dbh->prepare("INSERT INTO Aplicatii (id_c,id_j) VALUES (:id_c,:id_j)");
$arr = array('aplicat' => 'yes');
echo json_encode($arr);

And the response of



When console.log(msg) returns {"exista":"yes"} it is not an object, it is a string. So trying to access a property, like msg.exista, will return undefined.

This could be happen when you set a wrong dataType in your AJAX request, what is correctly set to JSON in your example.

So the probleme is on PHP side, you need to add the correct Content-Type to the response headers.

header("Content-Type: application/json");