Reputation: 177
I have a form and I send it to php
to insert into mysql
db by ajax
.
everything went good, and php
return the "true"
value, but in ajax
it shows false
message.
here you can look at the php
code:-
if(isset($result)){
$value = array('msg' => 'true' );
} else {
$value = array('msg' => 'false' );
}
echo json_encode($value);
and this is the ajax
code:-
success: function(value){
if (value.msg == 'true') {
alert("Saved");
}else{
alert("Something went wrong.");
}
and from console:
//value = "↵{"msg":"true"}
P.S. I don't know what is the ENTER sign "↵" do in the returned value, but I think it shouldn't affect, right?
Upvotes: 3
Views: 656
Reputation: 896
first check that there is no extra enter before open php tag or after close php tag then add this line to your request:
dataType:"json"
Upvotes: 0
Reputation: 72299
You need to add:-
dataType:"json",
In your Ajax and it will work.
One more solution is $.parseJSON
(if you are not using dataType:"json"
):-
success: function(value){
var json = $.parseJSON(value);
if (json.msg == 'true') {
alert("Saved");
}else{
alert("Something went wrong.");
}
}
Upvotes: 4
Reputation: 720
You need to convert json string with parse as below.
success: function(value){
var json = $.parseJSON(value);
if (json.msg == 'true') {
alert("Saved");
}else{
alert("Something went wrong.");
}
Please refer this link for more information http://api.jquery.com/jquery.parsejson/
Upvotes: 0
Reputation: 825
Probably the value you get back is a plain string. Try converting to json:
success: function (value) {
value = JSON.parse(value);
if(value.msg ==='true') {
/* your logic here */
}
}
Upvotes: 0
Reputation: 34914
May be you are getting true
as boolean not as string
Try like this
if (value.msg == true) {
alert("Saved");
}else{
alert("Something went wrong.");
}
Upvotes: 0