payal_suthar payal_suthar - 2 months ago 6
Javascript Question

Applying if else condition depending on the type of data returned

I am returning data from my php file which can be json or anything else.And i want to conditionally perform the function.
Here is the php code-

<?php
ini_set("display_errors", 1);

require_once("db.php");

$resultnew = "SELECT DISTINCT(`item_name`) FROM item_master WHERE `item_name`='" . $_POST['key'] . "'";

$resultfinal = mysqli_query($conn, $resultnew);

if (mysqli_num_rows($resultfinal) > 0)
{
$sql = "SELECT * FROM `item_master` WHERE `item_name` = '" . $_POST['key'] . "' ";
$result=mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($result))
{

$item_name = $row["item_name"];
$des = $row["item_description"];
$qty = $row["item_in_qty"];
$rate = $row["item_price"];
$unit = $row['item_unit'];

}
echo json_encode(array("item_name"=>$item_name,"des"=>$des, "qty"=> $qty, "rate"=> $rate, "unit"=> $unit ));

}
else{
echo "not ok";

}


?>


In the above code,if there is any matching value in the database then it will return json value and if there is no such value in database then it will return "not ok".

On this i am applying condition like this-

function checkitems(targetID)
{
var items = $('#items_' + targetID).val();
if (items != "") {
$.ajax({
type: 'post',
url: 'itemcheck.php',
data: {key: items},
dataType: 'json',
success: function(data) {

if (data == "not ok") {

$('#myitemmodal').modal("show");

} else {

var tr = $(this).closest('tr'); // here is the code for retrieving the values. i think here i need to make some changes
$('#price_' + targetID).val(data.rate);
$('#size_' + targetID).val(data.des);
$('#qty_' + targetID).val(data.qty);
$('#unit_' + targetID).val(data.unit);
}
}
});
}
}


Now ,problem that i am facing is that it is always going into else-condition only and not in if-condition.Maybe because i have mentioned datatype to be json. And when i remove datatype :json ,it does not perform well.
How do i deal with such condition.Let me know if you need anything else.
Thanks in advance.

Answer

As you're expecting to get JSON back, you should return JSON, and "not ok" is not valid JSON.

<?php

    ...
    if (mysqli_num_rows($resultfinal) > 0) {
        ...
        echo json_encode(
            array("data" =>
                 array("item_name"=>$item_name,"des"=>$des, "qty"=> $qty, "rate"=> $rate, "unit"=> $unit )
            )
        );
    } else {
        echo json_encode( 
            array("data" => "not_ok") 
        );
    }

And then catch it

success: function(data) {  

    if ("data" in data && 
        typeof data.data == "string" && 
        data.data.trim() == "not ok") {

       $('#myitemmodal').modal("show");

    } else {
Comments