I need to check one value from JSON response before continuing the script, but it doesn't work.
$.ajax({
type: "POST",
url: "addproduct.php",
data: {productId : selectedValue, customerId : customerId},
datatype: "json",
success: function (response) {
response = JSON.parse(response);
if(response === undefined) {
alert("undefined");
} else if (response.pricelistupdate = 1) { //this doesn't work
alert("ERROR! Adding a product is denied");
} else {
orderAddRow(response);
}
},
error: function () {
alert("ERROR");
}
});
I'm getting following JSON response:
{"row":{"pricelistupdate":0,"ID":"000017","name":"Chair","discount":"0.00","price":"0.00"}}
Thanks in advance.
What errors did i see:
JSON.parse()
as datatype:"json"
is there.pricelistupdate
should be response.row.pricelistupdate
.===
to a value you are assigning it =
in the elseif
.As you have a dataType
:
datatype: "json",
so you don't need to parse the json then. you can remove it response = JSON.parse(response);
.
JSON.parse()
method should only be used on a json string but in your case the response is a valid json so you don't need it.
and just get it:
You need to refer to your object keys and you are missing the key row
and you have also missed =
equal sign in the elseif
:
else if (response.row.pricelistupdate === 1)
So it has to be something like this in your success callback:
success: function (response) {
if(response === undefined) {
alert("undefined");
} else if (response.row.pricelistupdate === 1) { // check "===" equals
alert("ERROR! Adding a product is denied");
} else {
orderAddRow(response);
}
},
@jai is right since your response type is json so your "response" variable is already contains json so first of all remove
response = JSON.parse(response);
seeing at your response, your response is stored in row object so you are accessing "pricelistupdate" incorrectly you should replace it with response.row.pricelistupdate so your final code looks like
$.ajax({
type: "POST",
url: "addproduct.php",
data: {productId : selectedValue, customerId : customerId},
datatype: "json",
success: function (response) {
if(response === undefined) {
alert("undefined");
} else if (response.row.pricelistupdate = 1) {
alert("ERROR! Adding a product is denied");
} else {
orderAddRow(response.row);
}
},
error: function () {
alert("ERROR");
}
});