chris227 chris227 - 2 months ago 20
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) {
e.preventDefault();
var href = $(this).attr('href');

$.ajax({
url: href,

datatype: "json",
success: function(msg) {
alert(msg.exista);
if (msg.exista == "yes") {
alert('ai aplicat');
}
if (msg.aplicat == "yes") {
$('#modal_succes').modal('show');
}
},
});
});
});


enter image description here

also here is the php code that returns json

<?php

$id_c=$_GET['id_c'];
$id_j=$_GET['id_j'];

$stmt=$dbh->prepare("SELECT * FROM Aplicatii where id_c=:id_c and id_j=:id_j");
$stmt->bindParam(":id_c",$id_c);
$stmt->bindParam("id_j",$id_j);
$stmt->execute();
if($row=$stmt->fetch())
{
$arr = array('exista' => 'yes');
echo json_encode($arr);
}
else
{
$stmt=$dbh->prepare("INSERT INTO Aplicatii (id_c,id_j) VALUES (:id_c,:id_j)");
$stmt->bindParam(":id_c",$id_c);
$stmt->bindParam("id_j",$id_j);
$stmt->execute();
$arr = array('aplicat' => 'yes');
echo json_encode($arr);
}
?>


And the response of
console.log
:

{"exista":"yes"}

Answer

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");