Jump to content
Larry Ullman's Book Forums
Sign in to follow this  
David John

Ajax/Php Question

Recommended Posts

Happy New Year!


Here's my scenario: I need to return database values from a PHP script using AJAX to an HTML page, and for some reason it's not working.


The js code:

function getXMLHttpRequestObject() {
var ajax = null;
if(window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
} else if (window.ActiveXObject) {
ajax = new ActiveXObject('MSXML2.XMLHTTP.3.0');
return ajax;
function showLocation() {
var ajax = getXMLHttpRequestObject();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4) {
if ( ( ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304 )) {
var ajaxDisplay = document.getElementById("uslocations");
ajaxDisplay.value = ajax.responseText;
var state_lookup = document.getElementById("state_lookup").value;


<div data-role="page" id="something">
<div data-role="header">
 <a href="#page" data-icon="arrow-l" data-iconpos="left">Back</a>
<h1>Find a City</h1>
<div data-role="content">
<select id="state_lookup" onchange="showLocation()">
<option value="">Select a state:</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>

<div id="uslocations">
Here is the placeholder for content.
<div data-role="footer">


And finally, the PHP:

require ('Connections/oopConnect.php');
$state = $_GET['state'];
$q = "SELECT schedule_id, state_id, address, city, state, zip FROM dbTable WHERE state = '$state' ORDER BY city ASC";
$r = $mysqli->query($q);
$num = $r->num_rows;
if($num > 0 ) {
while ($row = $r->fetch_object()) {
echo '
<div class="headline"> ' . $row->state . '</div><br><br>
<ul data-role="listview"><br>
<li><a href="http://mysite.com?address= ' . $row->address . ' ">
<div class="address">' . $row->address . ' </div>
<div class="city1"> ' . $row->city . ' </div>
 <div class="state"> ' . $row->state . ' </div>
<div class="zip"> ' . $row->zip . '</div>
} else {
echo '<p>Nothing to see here.';


Is there a syntactical issue with what I am doing? I tested the PHP, and it is properly returning data, but I am not getting the AJAX to work properly. Any help would be appreciated.

Share this post

Link to post
Share on other sites

Hi, Dave.


That was a great suggestion! It was outputting in the console, so I made one small change in the js. Instead of this:

ajaxDisplay.value = ajax.responseText;

I switched it to this:

ajaxDisplay.innerHTML = ajax.responseText;

And now it works!

Thanks again for the idea.


I'd also like to thank Larry for not only the "Modern Javascript" book, but the PHP books as well. I've learned a lot from them.

Share this post

Link to post
Share on other sites

Great, glad it's working and glad you mentioned the PHP books - I'm planning on heading to the Advanced OOP PHP book next - just about finished with this one.


That does bring up an interesting question - is the value property only available with form fields? Does it just not make any sense to try and set the value property on a DIV element as tried above. I do remember reading about innerHTML risks vs innerText/textContent and some stuff regarding a separate text node (guess I'll have to review that chapter). Does anyone have a good explanation about how they approach setting various values?

Share this post

Link to post
Share on other sites

DaveCoast, I think you are right in that the value property is only available for form elements.


The innerHTML property can only be used for elements that have a start tag and an end tag. For that reason, the innerHTML property cannot be used with empty elements, which all form input elements are. It's worth noting that the textarea element has an end tag, but still requires the value property to get/set the text within it (there are exceptions to every rule).


As for innerHTML vs. innerText, there is a big difference. innerText is used to get/set the text within an HTML element, whereas the innerHTML property is used to get/set the text and the HTML tags with an HTML element.


Does that help at all?

Share this post

Link to post
Share on other sites

As a follow-up, what's the best way to style the data that AJAX returns from the database? I know that jQuery has a command for refreshing an HTML element, but what is the equivalent in Javascript?

Share this post

Link to post
Share on other sites

To answer your questions:


1) There is no "best" way. Your main choices are XML, JSON or a standard string. JSON seems to be the dominant choice these days for APIs, but for personal use (i.e., you're the only one that will ever manipulate the data), I generally prefer a standard string with custom-defined delimiters as necessary.


2) I'm not quite sure what you mean by "refresh an HTML element", but assuming you're talking about changing the content of an HTML element, the innerHTML property in vanilla JS should suffice. What jQuery method in particular are you talking about?

  • Upvote 1

Share this post

Link to post
Share on other sites

David John, thanks for clarifying your question.


To answer your question, there are two basic ways to dynamically update the DOM with JS:

1) Use the innerHTML property (as discussed before).

2) Use DOM methods such as createElement, appendChild, etc.


Those are the only two ways in vanilla JS. I imagine there are many different ways in jQuery, including the get and load methods referenced in the article you linked to. Because jQuery is coded entirely in JS though, regardless of how many methods jQuery has for updating the DOM, they all ultimately have to be using one of the two methods I mentioned above for regular JS.


As a side note, the article linked in the SO answer you linked to was pretty bad. The guy's entire problem seemed related to a complete lack of understanding of HTML and CSS and he didn't even seem to be aware of that fact.

  • Upvote 1

Share this post

Link to post
Share on other sites

Thank you, HartleySan.


Here's another thing I was wondering:


In my PHP above, when the user clicks the link, he/she goes to http://mysite.com?address= ' . $row->address . '


Is it possible to pass in a PHP variable to js? (In other words, can $row->address be grabbed and used in a js variable?)

var city_details = document.getElementById("php variable will go here").value;


Hopefully, that question is not too ambiguous.

Share this post

Link to post
Share on other sites

Yes, you can pass PHP values to JS. Just be sure to use the proper PHP start and end tags with an echo statement.


If you don't get what you want/expect, keep checking the HTML/JS generated by your PHP until you get what you want.

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

  • Create New...