1

EDIT #2

I added var_dump($res) and I can see that there is array when typing something:

enter image description here

But th ehtml table is not changing at all to add the result. So the error is in the JavaScript.

END

I have a page that I can search a long list of patients using jQuery events with Ajax calls to my PHP server.

Here is my jQuery/Ajax function that sends a variable called searchTxt to server:

var searchFunction = function(){
var searchTxt = $("#searchTxt").val();
searchTxt = $.trim(searchTxt);
//console.log(searchTxt);
$.ajax({
    url: '../php/searchPatient.php',
    type: 'POST',
    data: {searchTxt: searchTxt},
    dataType: 'JSON',

    success:function(resp)
    {
        //append data
        $("#patient_table tr").fadeOut(400);
        $("#after_tr").before("<tr class='bg-info'><th>ID</th><th>Name</th><th>Date Of Birth</th><th>Phone</th><th>Status</th><th>Change Status</th><th colspan='5' style='text-align:center'>Actions</th></tr>");
        $.each( resp, function(key, result)
        {
            var pid = result['patient_id'];
            var profileBtn = "<a id='profileBtn'><span class='badge badge badge-info' style='background-color: #0090ff'>Patient Profile</span></a>"
            $("#after_tr").after("<tr id="+result['patient_id']+"><td>"+result['patient_id']+"</td><td>"+result['patient_name_en']+"</td><td>"
                +result['dob']+"</td><td>"+result['patient_phone']+"</td><td>"
                +result['patient_status']+"</td><td><select style='color: #0090ff; ' class='form-control select patient_status' name='patient_status'><option value='select'>Select</option><option value='Active'>Active</option><option value='Deceased'>Deceased</option><option value='Discharged'>Discharged</option><option value='Defaulter'>Defaulter</option></select><td>"+profileBtn+"</td>");

            //if visit button clicked
            $("#patient_table #profileBtn").on('click', function(){
                var id = $(this).closest('tr').attr('id');
                window.location.href = "patient_profile_page.php?pid="+id;
            })
            $(document).on('change', '.patient_status', function() {
                var $select = $(this);
                var $tr = $select.closest('tr');
                var pid = $tr.attr('id');
                var $status = $tr.children('td.change_status');
                var current_status = $status.text();
                var new_status = $select.val();
                console.log(new_status);
                if (current_status == new_status) {
                  alert("The status selected is already the same!");
                }

                else {
                  //if (confirm("Are you sure you want to change the status of a patient ?")) {

                    //console.log(pid + " " + new_status);
                    $.ajax({
                      url: '../php/changeStatus.php',
                      type: 'POST',
                      dataType: 'TEXT',
                      data: { pid: pid, new_status: new_status },
                      success: function(resp) {
                        if(resp=="updated")
                        {
                            $status.text(new_status);
                            //console.log(resp);
                        }
                      },
                      error: function(resp) {}
                    });
                  //}
                }
              });
        });
    },
    error:function(resp)
    {
        console.log(resp);
    }
});
}

And here the events at the same file:

$(document).ready(function()
{
    $("#searchTxt").on('keyup', searchFunction);
    $("#searchBtn").on('click', searchFunction);
    $("#searchBtn").on('change', searchFunction);
});

The php script is searchPatient.php:

$res = array();
$cid = $_SESSION['clinic_id'];
$searchTxt = '%'.$_POST['searchTxt'].'%';

$searchPatient = "SELECT patient_id, aes_decrypt(patient_name_en, 'key1') as patient_name_en, patient_name_ar, dob, patient_phone, patient_status
                  FROM patient WHERE clinic_id = :cid AND patient_id LIKE :searchTxt
                  OR aes_decrypt(patient_name_en, 'key1') LIKE :searchTxt OR dob LIKE :searchTxt OR aes_decrypt(patient_phone, 'key1') LIKE :searchTxt OR aes_decrypt(patient_name_ar, 'key1') LIKE :searchTxt";
$execSearchPatient = $conn->prepare($searchPatient);
$execSearchPatient->bindValue(':cid', $cid);
$execSearchPatient->bindValue(':searchTxt', $searchTxt);
$execSearchPatient->execute();

$execSearchPatientResult = $execSearchPatient->fetchAll();

$i = 0;
foreach($execSearchPatientResult as $result)
{
    $res[$i] = $result;
    $i++;
}

echo json_encode($res);

I then changed it and add the try{} catch{} to catch errors:

try
{
    $res = array();
    $cid = $_SESSION['clinic_id'];
    $searchTxt = '%'.$_POST['searchTxt'].'%';

    $searchPatient = "SELECT patient_id, aes_decrypt(patient_name_en, 'key1') as patient_name_en, patient_name_ar, dob, patient_phone, patient_status
                      FROM patient WHERE clinic_id = :cid AND patient_id LIKE :searchTxt
                      OR aes_decrypt(patient_name_en, 'key1') LIKE :searchTxt OR dob LIKE :searchTxt OR aes_decrypt(patient_phone, 'key1') LIKE :searchTxt OR aes_decrypt(patient_name_ar, 'key1') LIKE :searchTxt";
    $execSearchPatient = $conn->prepare($searchPatient);
    $execSearchPatient->bindValue(':cid', $cid);
    $execSearchPatient->bindValue(':searchTxt', $searchTxt);
    $execSearchPatient->execute();

    $execSearchPatientResult = $execSearchPatient->fetchAll();

    $i = 0;
    foreach($execSearchPatientResult as $result)
    {
        $res[$i] = $result;
        $i++;
    }

    echo json_encode($res);
}
catch(PDOException $e)
{
    echo $e->getMessage();
}

Here is my current 2 patient list:

enter image description here

Now if I typed inside the text box 0361 which is in my database as a part of an ID, I can't see any result:

enter image description here

And at the console, there is no error but I have this:

Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}

P.S.

I tested the query in MySQL workbench and it is returning results.

alim1990
  • 4,656
  • 12
  • 67
  • 130

2 Answers2

0

there can be multiple causes to this, did you try to log the function on the backend side and see what data do you send to the backend? And what do you send back? I had some same problems one was solved by:

1.adding event.preventDefault();

  1. and the other was solved by this fix Chrome jQuery AJAX failing, not a cross-domain issue

My recommendation would be try to generate a request over postman and see the returned result and log what happens on the backend and what it is trying to return.

Hope it helps a bit!

Isandel
  • 1
  • 1
  • JSON.stringify() the response in both the success and error ajax function to see the full error message . – Isandel Jul 26 '17 at 10:07
  • can you see my answer on this question. I figured out the solution but can't understand why this error happened https://stackoverflow.com/questions/45321331/php-ajax-calls-is-not-getting-an-existing-json-array-of-result-when-aes-encrypti?answertab=votes#tab-top – alim1990 Jul 26 '17 at 11:11
0

I found the answer.

  1. I am using aes_encrypt() in my database, so I think there was a problem converting the result into JSON array without decrypting all encrypted columns in the query;
  2. Then, we should convert the result using utf8 or other encoding according to what you used in your database:

So the wrong query was:

SELECT patient_id, aes_decrypt(patient_name_en, 'key1') as patient_name_en, 
patient_name_ar, 
dob, 
patient_phone, 
patient_status

FROM patient WHERE clinic_id = :cid AND 
patient_id LIKE :searchTxt
OR aes_decrypt(patient_name_en, 'key1') LIKE :searchTxt 
OR dob LIKE :searchTxt 
OR aes_decrypt(patient_phone, 'key1') LIKE :searchTxt 
OR aes_decrypt(patient_name_ar, 'key1') LIKE :searchTxt

Here I was decrypting the patient_phone and the patient_name_ar without decrypting them in the columns selection section.

The correct query is:

SELECT patient_id, 
convert(aes_decrypt(patient_name_en, 'key1') USING utf8) as patient_name_en, 
convert(aes_decrypt(patient_name_ar, 'key1') USING utf8) as patient_name_ar, 
dob, 
convert(aes_decrypt(patient_phone, 'key1') USING utf8) as patient_phone, 
patient_status
FROM patient
WHERE clinic_id = :cid 
AND (patient_id LIKE :searchTxt
OR aes_decrypt(patient_name_en, 'key1') LIKE :searchTxt 
OR dob LIKE :searchTxt 
OR aes_decrypt(patient_phone, 'key1') LIKE :searchTxt 
OR aes_decrypt(patient_name_ar, 'key1') LIKE :searchTxt)
alim1990
  • 4,656
  • 12
  • 67
  • 130