Hello all,
I'm having a problem with having code execute when I'm adding javascript/ajax to my php. When I do the following piece of code, nothing happens. This is just a test line of code, my real code links to more javascript which uses ajax, but I have to figure out this first.

echo '<a href=# onclick = "alert('. $update_array['amsg_id'] .');">Show Comments</a>';

Thank you!!

Dani AI

Generated

Quick summary: the quoting/echo problem raised in the first posts was resolved (good call ), and was right to point out that your external file must not include wrapping <script> tags. The remaining failure is that the AJAX response isn't being parsed/used correctly. The root causes in this thread are a mix of PHP output mistakes (so the browser never gets valid XML) and fragile DOM access in the client code.

Checklist to work through (in order)

  • Use the browser dev tools Network tab: inspect the GET to view_comment.php, confirm HTTP 200, and view the raw responseText. If it’s not valid XML you must fix the PHP output.
  • Make view_comment.php emit a proper XML header and Content-Type (text/xml) and build the output with a correct loop (not a single fetch then while($row)). Avoid nested-quote errors in your SQL—better: one SELECT with a JOIN to get username.
  • If responseXML is null in JS, parse responseText with DOMParser. Don’t rely on numeric childNode indices — use getElementsByTagName(...)[0].textContent or firstChild.nodeValue so whitespace/text nodes don’t break you.
  • In createXMLHttpRequest the alert didn’t fire because your alert was only in the ActiveX branch; add logging after object creation (or use one creation pattern that covers both modern and old IE).

Concrete fixes (high-level)

  • PHP: set header('Content-Type: text/xml; charset=utf-8'); use while($row = mysqli_fetch_assoc(...)) { ... }; prefer a JOIN to fetch username in the same query; wrap free text (comment_text, poster_name) in CDATA or escape HTML entities so XML stays valid.
  • JS: use a robust XHR creation pattern, check xhr.readyState / xhr.status, and then do:
// parse XML (fallback if responseXML is null)
var xml = xhr.responseXML || new DOMParser().parseFromString(xhr.responseText, 'text/xml');
var comments = xml.getElementsByTagName('comment');
var container = document.getElementById('comments_' + id);
for (var i = 0; i < comments.length; i++) {
  var name = comments[i].getElementsByTagName('poster_name')[0].textContent;
  var body = comments[i].getElementsByTagName('comment_text')[0].textContent;
  // create elements, set textContent, append to container
}

Tiebacks: ’s approach of echoing a PHP variable into JS is fine, but the server must first return valid XML. ’s hint to check generated HTML/JS and ’s advice on escaping quotes are both things you already applied; focus now on fixing the PHP output and switching to tag-based XML access in JS. Once the server returns well-formed XML and your JS uses tag lookups (not childNode indices), the alerts and DOM updates should appear.

Recommended Answers

All 12 Replies

echo '<a href="#" onclick = "alert(\'$update_array[amsg_id]\')">Show Comments</a>';

that might work :)

Thank you for your response, and when I did what you said with the alert function, I just replaced the variable with text and it worked. Now when I go back to try it with the variable it doesn't work.

echo '<a href="#" onclick = "alert(\''.$update_array['amsg_id'] .' \')">Show Comments</a>';

EDIT: Actually that worked, but now I'm running into a problem with my javascript. I replaced the alert function with a function from another sheet that was imported by doing this:

<script type="text/javascript" src="/resources/viewComment.js"></script>

Here is the code for that file, and the function that should activate is startRequest(), and there are alert functions in there from when I tried to debug.

<script language="javascript" type="text/javascript">
	var xmlHttp;
	var requestType = "";
	var id;
	var div_id
	
	function createXMLHttpRequest(){
		if (window.ActiveXObject){
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		else if (window.XMLHttpRequest){
			xmlHttp = new XMLHttpRequest();
		}
		else{
			alert("failure");
		}
	}
	
	function startRequest(parentId){
		id = parentId;
		alert(id);
		createXMLHttpRequest();
		xmlHttp.onreadystatechange = handleStateChange;
		url = "www.wwit.comlu.com/view_comment.php?parent_id=" + parentId;
		xmlHttp.open("GET", url, true);
		xmlHttp.send(null);
	}
	
	function handleStateChange(){
		if(xmlHttp.readyState == 4){
			if(xmlHttp.status == 200){
				displayComments(id);
			}
		}
	}
	
	function displayComments(id){
		div_id = "comments_" + id;
		document.getElementById(div_id).innerHTML = xmlHttp.responseText;
	
	
		div_id = "comments_" + id;
		var comments = document.getElementById(div_id);
		var results = xmlHttp.responseXML.getElementsByTagName("comment");
		var name = null;
		var div = null;
		var url = null;
		alert("somethings working");
		
		for(var i=0; i< results.length; i++){
			div = document.createElement("div");
			div.setAttribute('id', "comment");
			name = document.createElement("a");
			url = "www.wwit.comlu.com/viewprofile.php?user_id=" + results[i].childNode[2].nodeValue;
			name.setAttribute('href', url);
			name.nodeValue = results[i].childNode[2].nodeValue;
			
			text = document.createElement("p");
			text.setAttribute('class', 'comment_text');
			text.nodeValue = results[i].childNode[3].nodeValue;
			
			time = document.createElement("p");
			time.setAttribute("id", "comment_time");
			time.nodeValue = results[i].childNode[4].nodeValue;
			
			div.appendChild(name);
			div.appendChild(text);
			div.appendChild(time);
			comments.appendChild(div);
		}
	}
</script>

Thank you!!

that's because ' inside: $update_array are probably breaking the echo function try putting: $update_array[\'amsg_id\'] if that doesn't work perhaps if you are using an if or else you could be more expressive with your echo by doing...
<? if(){ ?>
<a href="#" onclick = "alert('<? echo"$update_array"; ?>')">Show Comments</a>
<? }else{ ?>
No alert :)
<? } ?>

That sort of thing :) what ever suits you

erm why not make your current alert a function and call the other documents function within its function

I would prefer not to because its in a loop, but now I know that the variable displays, but I have a problem with the actual javascript & ajax code working.

You will figure this by checking your html source code as you go.
php is rendered before javascript, and you're just having syntax similarity problems with your quotation marks.

Hello all,
I'm having a problem with having code execute when I'm adding javascript/ajax to my php. When I do the following piece of code, nothing happens. This is just a test line of code, my real code links to more javascript which uses ajax, but I have to figure out this first.

echo '<a href=# onclick = "alert('. $update_array['amsg_id'] .');">Show Comments</a>';

Thank you!!

Do something like this

<?php 
   if(...your condition){  ?>
     <a href="#" onclick="myFun('<?php echo $update_array['amsg_id'];');"></a>
<?php } ?>  

<script type="text/javascript">
function myFun(data)
{
    alert(data);
    ....do something with data
}
</script>

You can directly acces the $update_array in your javaScript block

<script type="text/javascript">
var myData = <?php echo $update_array['amsg_id']; ?>;
alert(myData);
...do something 
</script>

So I tried this piece of code (its in a loop) and everything displays, but obviously the javascript is not executing as none of the alert messages I inserted into the code (shown in previous post) displays.

?> <a href="#" onclick = "startRequest('<?php echo $update_array['amsg_id']; ?>');">Show Comments</a> <?php

EDIT: I added an alert behind the startRequest function to occur when the link is clicked, and that alert displays with the right id number, but the startRequest function is still not working. Am I linking to the javascript file correctly? (the way I imported it is shown above)

<script language="javascript" type="text/javascript"> does not need to be in your /resources/ file line 1 and the last line 72 can be removed as well: </script>

Ok, I edited that Javascript file, and now some of the alert messages that I put in to the code are working. The first two alerts in the startRequest function below are working.

function startRequest(parentId){
		alert("work");
		id = parentId;
		alert(id);
		createXMLHttpRequest();
		xmlHttp.onreadystatechange = handleStateChange;
		url = "www.wwit.comlu.com/view_comment.php?parent_id=" + parentId;
		xmlHttp.open("GET", url, true);
		xmlHttp.send(null);
	}

Next, the alert that I put in createXMLHttpRequest() isn't working, and thats the next line of code in the startRequest() function from above.

Is there a reason why this may not work?

function createXMLHttpRequest(){
		if (window.ActiveXObject){
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			alert("work");
		}
		else if (window.XMLHttpRequest){
			xmlHttp = new XMLHttpRequest();
		}
		else{
			alert("failure");
		}
	}

Sorry for the double post, but I've now pinpointed the problem to my displayComments() function, at the point where I store the xml results from a php script in a variable named results.

The xml is in this format:

<comments>
<comment>
<comment_id></comment_id>
<poster_id></poster_id>
<poster_name></poster_name>
<comment_text></comment_text>
<comment_time></comment_time>
</comment>
</comments>

And there are multiple instances of comments
The javascript is below for that function:

function displayComments(){
		div_id = "comments_" + id;
		alert(div_id);
		var comments = document.getElementById(div_id);
		alert("get div_id works");
		var results = xmlHttp.responseXML.getElementsByTagName("comment");
		alert("get comment works");
		var name = null;
		var div = null;
		var url = null;
		alert("somethings working");
		
		for(var i=0; i< results.length; i++){
			div = document.createElement("div");
			div.setAttribute('id', "comment");
			name = document.createElement("a");
			url = "www.wwit.comlu.com/viewprofile.php?user_id=" + results[i].childNode[2].nodeValue;
			name.setAttribute('href', url);
			name.nodeValue = results[i].childNode[2].nodeValue;
			
			text = document.createElement("p");
			text.setAttribute('class', 'comment_text');
			text.nodeValue = results[i].childNode[3].nodeValue;
			
			time = document.createElement("p");
			time.setAttribute("id", "comment_time");
			time.nodeValue = results[i].childNode[4].nodeValue;
			
			div.appendChild(name);
			div.appendChild(text);
			div.appendChild(time);
			comments.appendChild(div);
		}
	}

Here's the view_comment.php script to output the xml from the server:

<?php
	$parent_id = $_GET['parent_id'];
	
	$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
	$comment_query = "SELECT * FROM comment WHERE parent_id = '$parent_id' ORDER BY post_time ASC";
	$comment_data = mysqli_query($dbc, $comment_query);
	$comment_rows = mysqli_fetch_array($comment_data);
	
	xmlOutput = '<comments>';
	while($comment_rows){
		xmlOutput .= '<comment>';
		xmlOutput .= '<comment_id>'. $comment_rows['comment_id'] .'</comment_id>';
		xmlOutput .= '<poster_id>'. $comment_rows['poster_id'] . '</poster_id>';
		
		//Get username
		$username_query = "SELECT username FROM wwit_user WHERE user_id = '$comment_rows['poster_id']'";
		$username_data = mysqli_query($dbc, $username_query);
		$username_rows = mysqli_fetch_array($username_data);
		
		xmlOutput .= '<poster_name>'. $username_rows['username'] .'</poster_name>';
		xmlOutput .= '<comment_text>'. $comment_rows['comment_text'] .'</comment_text>';
		xmlOutput .= '<comment_time>'. $comment_rows['post_time'] .'</comment_time>';
		xmlOutput .= '</comment>';
	}
	xmlOutput .= '</comments>';
	echo xmlOutput;
?>

Thanks again!!

line 8. should not have a variable called "name". not sure if that is the problem you are working on right now, but that should be changed.

Thank you for that, I changed the variable and all of the time its referred to as 'user' but I'm still not getting the alert function after trying to get the xml from my php script.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.