0

I have ajax url php code as follows:

<?php
if (isset($_POST["icdmaincode"]) && !empty($_POST["icdmaincode"])) 
{
    $icd_main_code = strip_tags(trim($_POST["icdmaincode"]));
}
$stmt5 = $conn->prepare("SELECT icd_sub_code,icd_sub_code_description 
                        FROM icd_sub_code 
                        WHERE icd_main_code = :icdmaincode");
$stmt5->bindValue(':icdmaincode', $icd_main_code);
$stmt5->execute();
$row = $stmt5->fetchAll(PDO::FETCH_ASSOC);
foreach($row as $key => $value)
{
    echo json_encode(array($key => $value));
}
$conn = null;
?>

and it is giving output as follows which is not valid json.

[{"icd_sub_code":"icdcat1-1","icd_sub_code_description":"(A00-A09) Intestinal infectious diseases"}]
{"1":{"icd_sub_code":"icdcat1-2","icd_sub_code_description":"(A15-A19) Tuberculosis"}}
{"2":{"icd_sub_code":"icdcat1-3","icd_sub_code_description":"(A20-A28) Certain zoonotic bacterial diseases"}}

and hence the following ajax success code is not working:

success: function(data){
    var subcode = data.icd_sub_code;
    var subcodedescription = data.icd_sub_code_description;
    subcode = JSON.parse(subcode);  
    alert(subcode); 
    .....

What am i doing wrong ?? How can i resolve it ??

1
  • You are returning an JSON array of objects. So your javascript needs to process data as an array. Assuming you have taken @AbraCadaver advice on the PHP Code Commented Nov 28, 2017 at 18:14

1 Answer 1

2

Normally you would build an array, encode and then display:

foreach($row as $key => $value)
{
    $data[] = array($key => $value);
}
echo json_encode($data);

But you actually have it all already in that type of array, so no need to loop:

echo json_encode($row);

Also, just FYI empty checks isset so just:

if (!empty($_POST["icdmaincode"]))
Sign up to request clarification or add additional context in comments.

2 Comments

You might want to also add some array processing into the javascript code
@AbraCadaver oops..I overlooked the fact that $row was an array. Newbie programmer oversight. Thank you very much :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.