Jump to content

From Database to JavaScript


Spunky

Recommended Posts

I'm trying to retrieve data from a database and be able to utilize it in JavaScript. I'd finally found a way to send info from JavaScript to PHP to place it in my database using AJAX, and I am attempting to use the same strategy to retrieve it. This is what I have so far:

    xmlhttp.onreadystatechange = function() {    	if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {    		retrieve = xmlhttp.responseText;			alert(retrieve);    	}    }		xmlhttp.open("GET","loadAddress.php?",true);	xmlhttp.send();

The alert successfully alerts the content of multiple rows from the database. Ultimately I want to be able to individually use the rows in a JavaScript function, all the same thing, so if I could get each row into an array, I'd be able to loop through it, individually placing them in the function. I'm stuck how to proceed from here.

echo $row['location'];

The PHP echos the rows, which is the only way I know how to get it to the JavaScript onreadystatechange function, perhaps there is another way I need to do? I'm just stumped how to proceed.

Link to comment
Share on other sites

You can put lots of data in the responseText, you just have to encode and decode it.

 

You could, for example, separate values with commas:

// PHPecho $row['a'] . ',' . $row['b'] . ',' . $row['c'];
// Javascriptvar data = xmlhttp.responseText.split(",");alert(data[0]);alert(data[1]);

One of the most common ways these days is to encode it in JSON.

// PHPecho json_encode($row);
// Javascriptvar data = JSON.parse(xmlhttp.reponseText);
Link to comment
Share on other sites

This is great, thanks. Could you help me understand the parse and encode? I mean, I have the code working just fine without it:

      while ($row = mysql_fetch_assoc($result))      {	echo $row['location'] . '*';

(used a asterisk instead because there are already commas in the data)

retrieve = xmlhttp.responseText.split("*");alert(retrieve[0]);alert(retrieve[1]);

Does it perfectly. When I research json_encode though to understand it further, I get stuff about sending an array from PHP to JavaScript etc, but it seems to work without it?

 

Anyway I wasn't able to get it working with my attempt but I am probably not doing it right...

retrieve = JSON.parse(xmlhttp.responseText.split("*"));alert(retrieve[0]);alert(retrieve[1]);
      while ($row = mysql_fetch_assoc($result))      {	$myRow = $row['location'] . '*';	echo json_encode($myRow);

I get the error: Uncaught SyntaxError: Unexpected string index.html:1

 

It's working without so I am happy, but if there is a proper way to do this or problems that could result from it, I'd like to make sure I'm doing it right. :dirol:

Link to comment
Share on other sites

JSON is an interchange format.

http://www.json.org/

 

It is a standard that is meant to be used when transferring data between languages, like PHP and Javascript. So in this case you would just encode your data with PHP (json_encode), and decode with Javascript (JSON.parse). You shouldn't have to manipulate your data with anything else.

Link to comment
Share on other sites

  • 4 weeks later...

Alright well I seem to be missing some tidbit of how to format the PHP. You say I don't have to manipulate it in any way but I must need to initially set it up for sending. This is what I have and I still cannot get it to work.

$data = $row['location'] . $row['address'] . $row['price'] . $row['mortgage'] . $row['numBeds'] . $row['numBaths'] . $row['taxes'] . $row['year'] . $row['house'] . $row['livingRoom'] . $row['kitchen'] . $row['bedroom1'] . $row['bedroom2'] . $row['bedroom3'] . $row['bedroom4'] . $row['bedroom5'] . $row['fenced'] .$row['basement'] . $row['garage'] . $row['notes'];echo json_encode($data);

^ This is my code without commas or asterisks.

If you're using json_encode then don't use commas or asterisks. Just give the array as it is. PHP converts the array into a format that Javascript can read.

 

I think what I am missing is "the array" for PHP to convert. I never had this data in an array originally. Right now I've been passing over a string. Am I suppose to put it in a PHP array? Use PHP to write a JSON object?

 

The way I send it with commas an asterisks gives JavaScript a way to split it into an array. Otherwise I'm lost.

Link to comment
Share on other sites

How about this?

echo json_encode($row);

That's it, just pass the array itself. No string concatenation or anything.

The $row variable you're getting is an array.

Link to comment
Share on other sites

How about this?

echo json_encode($row);

That's it, just pass the array itself. No string concatenation or anything.

The $row variable you're getting is an array.

 

OH. That was said before but I thought it was just a generalization that I'd send the $row information, thought to myself well I'm sending a lot of stuff...But I get it, $row is an array of ALL the data and by saying $row['location'] I am just specifying which piece in the array I am using.

 

Ok so, tried it, get the error:

 

Uncaught SyntaxError: Unexpected token { index.html:1

 

Doesn't say much, I tried adding:

echo json_encode($row) or die(mysql_error());

To try and see the error I might be getting. I alerted the variable on the other end that retrieves the data:

var data = JSON.parse(xmlhttp.responseText);alert(data);

And I get the alert 1111 (with the 'or die' bit, no alert occurs, just that error). Not sure what that is about. I checked my PHP error logs, nothing there.

Link to comment
Share on other sites

If you're getting a PHP error, show the entire contents of the PHP file so we can see where it is. It's probably a simple mistake like a missing semi-colon.

 

If you're getting a Javascript error, for debugging you can check the value of xmlhttp.responseText without parsing it.

try {    var data = JSON.parse(xmlhttp.responseText);} catch(e) {    // If it' not working, debug by checking the responseText    alert(xmlhttp.responseText);}
Link to comment
Share on other sites

 

If you're getting a PHP error, show the entire contents of the PHP file so we can see where it is. It's probably a simple mistake like a missing semi-colon.

 

If you're getting a Javascript error, for debugging you can check the value of xmlhttp.responseText without parsing it.

try {    var data = JSON.parse(xmlhttp.responseText);} catch(e) {    // If it' not working, debug by checking the responseText    alert(xmlhttp.responseText);}

 

Ran that code and yes, the alert contains the proper value. It displays the array in JSON format. So what does this tell me?

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...