Transmitting database information from php to javascript - mysql_fetch_array not acting as expected

StackOverflow https://stackoverflow.com/questions/16747268

Вопрос

I apologise if someone is aware of an available answer to my question, however after a week of looking on the web and trialling stuff I thought I would ask the experts.

Aim: Query an SQL database via server side code (in this case php), then pass this database information to javascript on a web page to allow buttons to be dynamically generated. Note, there will be multiple lines from the database returned. Once the buttons are generated they will call php code to change values in the database, however it is the first part I am struggling with at the moment.

Current solution (not quite working): I recognise there is optimisation to do on this code, however as it is still me trying to sort the problem I will review the little bits myself later and do not require details on that.

Overview: PHP sends a mysql query via mysql_query to get the information from the database. AJAX is then used with json_encode to encode the information in php and then echo is used to print out the answer to the javascript.

PHP code:

    <?php //start php code
include 'DatabasePhp/openDatabase.php'; //includes my mysql_connect code to connect to the database. Works.
$query = 'SELECT `users`.`user_name`, `users`.`user_id`, `users`.`join_date`'
. ' FROM users'
. ' LIMIT 0, 30 ';
$result= mysql_query($query);
include 'DatabasePhp/closeDatabase.php';
$aa = mysql_fetch_array($result, MYSQL_ASSOC);
$total_array[0] = $aa;
$total_array[1] = array('user_name' => 'bb','day' => '5');
$formatted_variable_pass = json_encode($total_array);
echo $formatted_variable_pass;
?>

PHP notes: I will use a while loop once I fix the issue to run through each line of my database results and add them to the $total_array. Currently it is setup for only two array indexes to highlight my issue. $total_array[0] is storing the answer from the mysql query, $total_array[1] is me generating an associative array (like I thought I was getting from the mysql_fetch_array).

Javascript code:

    <script type="text/javascript" language="JavaScript">
document.write("Well your starting javascript");
var btn_num = 0;

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

xmlhttp.onreadystatechange=function() // the function called when a result is returned from the php
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
var responce_json = JSON.parse(xmlhttp.responseText);
    document.getElementById("txtHint").innerHTML="got responce "+responce_json[0]['user_name']+"  "+responce_json[1]['user_name'];
}else if(xmlhttp.status==404){
    document.getElementById("txtHint").innerHTML="Not found";
}else if(xmlhttp.readyState==0){
    document.getElementById("txtHint").innerHTML="Responce was 0";
}else{
    document.getElementById("txtHint").innerHTML="Not completed the responce";
}
}
xmlhttp.open("POST","DatabasePhp/getUsers.php",true);
xmlhttp.setRequestHeader("Content-type","application/json;charset=UTF-8");
xmlhttp.send(null);

document.write("and the results are .... ");

</script>

Javascript notes: The code basically creates a XMLHttpRequest type class based on the browser in use, then sends a POST request via xmlhttp.open. The responce is dealt with through the xmlhttp.onreadystatechange=function(), ie the answer is only written once it has been confirmed the answer is complete, ie when xmlhttp.readyState==4 && xmlhttp.status==200.

The issue: I am having trouble passing the mysql_fetch_array data to javascript. The reason I have placed a php associative array into the $total_array[1] is because I wanted to prove that I could pass variables. The code successfully passes that array within the other array and I can access in javascript via responce_json[1]['user_name']. Unfortunately no matter how I try to get the associative array returned from the mysql_fetch_array (which is set to return an associative array), in the current code done by responce_json[0]['user_name'], I do not get an answer. During my trials I have had a mix of 'null' being returned when I try to get the aa associative array at [0], and generally my code does not complete the code when I try to access the ['user_name'] of the mysql returned associative array.

So the question is: Am I missing something about the associative array that is returned by the mysql_fetch_array(set to return associative array via MYSQL_ASSOC), it isn't responding like the manually created associative array (once in javascript - works properly in php) and I can't figure out why. Does anyone understand how I can convert/ensure the mysql array reacts like my manual one?

Additional: It isn't the sql that is having a problem as when I include the php into my web page rather than passing to javascript, the echo responce written to the web page is '[{"user_name":"Frank","user_id":"1","join_date":"2013-05-15"},{"user_name":"bb","day":"5"}]'. Therefore it is successfully retrieving the information from the database and to me this looks like one array with sub associative arrays inside, which is what I was after, but I can only retrieve user_name of 'bb', can't get Frank out in javascript. PS I realise that the two arrays only have user_name in common, but that is the only one I am trying to access at the moment.

Sorry for the long post, just trying to get all my thoughts down.

Results from suggestions: mysql_fetch_assoc – Orangepill; I tried this, no change. From all the documentation I can review on the web I understand that this returns the same as mysql_fetch_array($result, MYSQL_ASSOC);

Moving closeDatabase.php - Michel Feldheim; Moving this has no effect on the output.

console.log(responce_json) – Orangepill; Thanks for that, didn't realise I could review it this way. When I interrogate the XMLHttpRequest I get the following returned through the console: XMLHttpRequest {statusText: "OK", status: 200, response: "[null,{"user_name":"bb","day":"5"}]", responseType: "", responseXML: null…}. From this I can see that the mysql_fetch_array answer is transmitted as null, which is caused by the error I receive which is 'uncaught Error: InvalidStateError: DOM Exception 11'. Can't seem to figure out what this is enough to fix it.

Это было полезно?

Решение 2

So after all that I was mistaken.

It would appear that the issue was that when the php script was called to generate the web page, the include statements within the script were able to be accessed. When the script was called from the javascript code my included statements which dealt with opening and closing the database were not able to be found.

This lead to the answers not being returned.

Другие советы

You are including a script called closeDatabase.php. If this does what the name suggests, you should do this after you have fetched all data.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top