1

I have an input box in html. The input searches an database through ajax and return the results in front-end. The problem is that I don't get the result from PHP. I don't know what I did wrong, so I hope you guys have a better understanding from me.

HTML

<body onload="AjaxFindPerson()">
.....
</body>

JS

    var xmlHttp = createXmlHttpRequestObject();



function AjaxFindPerson() {
    if ((xmlHttp.readyState == 0 || xmlHttp.readyState == 4) && document.getElementById("PersonSearchInput").value != "") {
        person = encodeURIComponent(document.getElementById("PersonSearchInput").value);
        xmlHttp.open("GET", "../lib/search.php?email=" + person, true);
        xmlHttp.onreadystatechange = handleServerResponse;
        xmlHttp.send(null);

    }
    else {
        document.getElementById('Label-Result').innerHTML = "";
        document.getElementById('UserNameSearchResult').innerHTML = "";
        $('#add-person-btn').attr("disabled", "disabled");
        setTimeout('AjaxFindPerson()', 1000);
    }
}


function handleServerResponse() {
    if (xmlHttp.readyState == 4 ) {
        if (xmlHttp.status == 200) {
            xmlResponse = xmlHttp.responseXML;
            xmlDocumentElement = xmlResponse.documentElement;
            result = xmlDocumentElement.firstChild.data;

            if (result[0] != false) {
                document.getElementById('Label-Result').innerHTML = result[1];
                document.getElementById('UserNameSearchResult').innerHTML = result[0];
                $('#add-person-btn').removeAttr("disabled", "disabled");
            }
            else {
                document.getElementById('Label-Result').innerHTML = result[1];
            }

            setTimeout('AjaxFindPerson()', 1000);
        }
        else {
            alert('Somenthing went wrong when tried to get data from server'+ xmlHttp.readyState);
        }
    }
}

PHP

<?php
    header('Content-Type: text/xml');
    echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
    session_start();
    define("DB_HOST", 'mysql6.000webhost.com');
    define("DB_USER", '');
    define("DB_PASSWORD", '');
    define("DB_DATABSE", '');

    echo '<response>';

    $email = $_GET['email'];

    $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
    mysql_select_db(DB_DATABSE, $conn);
    $sq = mysql_query("SELECT UserEmail FROM Users");

    $UserInfo = array();

    while ($row = mysql_fetch_array($sq, MYSQL_ASSOC)) {
      $UserInfo[] =  $row['UserEmail'];  
    }


    if (in_array($email, $UserInfo)) {
      $result = mysql_query("SELECT UserName FROM Users WHERE UserEmail = '".$email."'");
      $row = mysql_fetch_row($result);
      $returnRes = array($row[0], "We found results"); //row[0] holds the UserN
      echo $returnRes;
    }
    else {
      $returnRes = array(false, "We couldn't find results");
      echo $returnRes;
    }

    echo '</response>';


?>

If we check the php-xml file alone will see the image bellow : enter image description here

Do I need to pass the values to xml-php with another way?

UPDATE 1 in PHP I manage to found a way to return the data correctly. Here are the update 'touch'

 header('Content-Type: application/json');

and

if (in_array($email, $UserInfo)) {
  $result = mysql_query("SELECT UserName FROM Users WHERE UserEmail = '".$email."'");
  $row = mysql_fetch_row($result);
  echo json_encode(array( 'found' => $row[0], 'msg' => "We found results"));
}
else {
  echo json_encode(array( 'found' => null, 'msg' => "We couldn't find results"));
}

The problem now is how to manipulate the js file to handle the return array. I made a try but it didn't worked:

result = xmlDocumentElement.firstChild.data;

            if (result['found'] != null) {
                document.getElementById('Label-Result').innerHTML = result['msg'];
                document.getElementById('UserNameSearchResult').innerHTML = result['found'];
                $('#add-person-btn').removeAttr("disabled");
            }
            else {
                document.getElementById('Label-Result').innerHTML = result['msg'];
            }

**UPDATE 2 WORKING JS **

I figure out how to retrieve the data from PHP.

xmlResponse = xmlHttp.responseXML;
            xmlDocumentElement = xmlResponse.documentElement;
            var result = JSON.parse(xmlDocumentElement.firstChild.data);

            if (result['found'] != null) {
                document.getElementById('Label-Result').innerHTML = result['msg'];
                document.getElementById('UserNameSearchResult').innerHTML = result['found'];
                $('#add-person-btn').removeAttr("disabled");
            }
            else {
                document.getElementById('Label-Result').innerHTML = result['msg'];
            }

NOW ALL THE CODE IS WORKING! THANK YOU VERY MUCH GUYS!

+1 to all of you!

2
  • 1
    You cant print an array using echo.... Commented Dec 20, 2015 at 15:39
  • @Lipsyor Oh really? And what is the right way? JSON? HOW? Commented Dec 20, 2015 at 15:40

3 Answers 3

3

Four things :

  1. Usage of send(null) doesn't seems to be right, just don't pass null in it.
  2. Second one is timeout method. Instead the way you are using it, you can call it in the callback function or instead of string use the name at the function call.
  3. The usage to remove the attribute is also wrong. It is currently using a set method as you have supplied a second argument. The remove attribute method only takes a attribute name.
  4. I would rather suggest you to set a header for the application/json and use json_encode() method to return data.
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, but this won't help the actual problem. But thanks! :)
If I understand, I use echo json_encode($returnRes); in my PHP but how do I handle the return value in js?
0

For printing an array, you can either use json_encode(), or do somehow else transform your array into a string.

8 Comments

I think of it but how I manage the data in js? Cause ,if you saw, I use them to update my html file.
Well, JSON is pretty easily handable in Javascript. See http://www.json.org/js.html
Yeap but I don't know if the values are passed correctly to $returnRes.
Well that depends on what you define as "correct" and is inherent to your application. I do not see how we could help you with that, to be honest :)
Can you debug the xhr response in the browser and tell what is passed back? I presume by now you are print_r correctly for the array
|
0

If we were to ignore the white elephant in the room and gloss over the use of mysql_* functions then a slightly different approach

<?php
    session_start();

    define('DB_HOST', 'mysql6.000webhost.com');
    define('DB_USER', '');
    define('DB_PASSWORD', '');
    define('DB_DATABASE', '');


    $dom=new DOMDocument('1.0','utf-8');
    $root=$dom->createElement('response');
    $dom->appendChild( $root );     

    if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['email'] ) ){


        /* Basic filtering IF mysql_* functions are used! */
        $email = trim( strip_tags( filter_input( INPUT_GET, 'email', FILTER_SANITIZE_EMAIL ) ) );

        $conn = mysql_connect( DB_HOST, DB_USER, DB_PASSWORD );
                mysql_select_db( DB_DATABASE, $conn ) or die('error: database connection failed');

        /* By the looks of the original there should be no need for two queries and then an array lookup */
        $result = mysql_query("SELECT `UserName` FROM `Users` WHERE `UserEmail` = '".$email."';");

        /* If there are results, add nodes to the dom object */
        if( mysql_num_rows( $result ) > 0 ){
            while( $rs=mysql_fetch_object( $result ) ){
                $root->appendChild( $dom->createElement( 'user', $rs->UserName ) );
            }
        } else {
            /* Otherwise add error message */
            $root->appendChild( $dom->createElement( 'error', 'We couldn\'t find any results!' ) );
        }
    }

    /* Send the xml back to the js client */
    header('Content-Type: text/xml');
    $xml=$dom->saveXML();
    $dom=null;

    exit( $xml );
?>

1 Comment

thank you very much. I figure out the PHP (as you can see in my UPDATE) The problem is how to use the return data in js.

Your Answer

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