New to Javascript Question

I am trying to set up a rating and content changer via AJAX with a PHP response.

Basically, the user will see a post generated at random and some rating controls (for for or against.) When the user clicks on the vote button, the post text changes to the next one and the vote count is sent to the mysql database.

This is what I see happening with the event:

  1. Vote is sent to the processing PHP file that updates the record for the new vote.
  2. A new post is generated as the output.

#2 is working fine.

The trouble is with #1. How can I send data (through a POST) to the php file with information about the text being voted on? Each of my posts have a corresponding unique ID number. What I tried was to send the output of the responseText with a <span id=“currentid”>13</span> in the response html div. Then I (noob move) tried to use a document.getelementbyid(“currentid”).innerHTML to retrieve the current id number. Since the AJAX script is in the <head> of the document, it of course failed to return anything.

Is there some other way to approach this?

Place your js at the end of your HTML.
Your JS isn’t aware of any HTML elements just yet when its loaded from the head.

Now, click your vote, record your id and send via http request.
You can process using POST by passing your parameters into the http.send(params) method.

If it’s easier, use a framework like Prototype or jQuery.

If you want to retrieve that, you have to append that innerHTML to the DOM, then access it via getElementById. It seems like a laborious way of doing it, though.

Is your PHP script returning HTML? If so, you can just set some attribute in it to your id, like a “rev” attribute. If you’re not returning HTML for the new post, you can just return the new id as pure text, which makes it all a lot easier.

It’ll be easier to answer your question if you show a sample of exactly what the responseText looks like.

OK I am by no means a Javascript guru but I know enough to be dangerous… :x

Here is a basic example of what you are trying to achieve. I have used buttons as the clickable object but you can use anything you like really.

Page 1 - Display page.
Holds the displayed objects and the div to be updated.


<html>
<head>
<script>
var xhrobj;

function ajax_request(id) {
  if(navigator.appName == "Microsoft Internet Explorer") {
    xhrobj = new ActiveXObject("Microsoft.XMLHTTP");
  } else {
    xhrobj = new XMLHttpRequest();
  }
  
  xhrobj.open('get', 'response.php?id=' + id );
  xhrobj.onreadystatechange = ajax_response;
  xhrobj.send(null);
}

function ajax_response() {
  if(xhrobj.readyState == 4) {
    document.getElementById('ajaxUpdate').innerHTML = xhrobj.responseText;
  }
}
</script>
</head>
<body>
<button onclick="ajax_request(1)">Click Me, I am number 1</button><br />
<button onclick="ajax_request(2)">Click Me, I am number 2</button><br />
<button onclick="ajax_request(3)">Click Me, I am number 3</button><br />
<button onclick="ajax_request(4)">Click Me, I am number 4</button><br />
<button onclick="ajax_request(5)">Click Me, I am number 5</button><br />
<button onclick="ajax_request(6)">Click Me, I am number 6</button><br />
<button onclick="ajax_request(7)">Click Me, I am number 7</button><br />

<div id="ajaxUpdate">..(spike)..</div>
</body>
</html>

Pages - response.php.
Handles what php does with the GET variable after it has been sent by the ajax call.
You can do whatever you would normally do with it!

<?php


$id = $_GET['id'];

echo 'This is the response text...<br /> Number '. $id .' was clicked<br />';

echo 'I am updating the database and serving you with a new quote.....<br />';


?>

Bare bones example but it gives you an idea :slight_smile:

Hey, thanks for the replies. I tried some of the things mentioned here–I tried moving this script to the end of the document, but it didn’t help. I am have been reading through the books but cannot figure out what I’m doing wrong; if anyone here can take a look and tell me if there is anything wrong, I’d appreciate it!

The javascript:

var xhrobj = "";
var id = "";

function vote_up(id) {
  if(navigator.appName == "Microsoft Internet Explorer") {
    xhrobj = new ActiveXObject("Microsoft.XMLHTTP");
  } else {
    xhrobj = new XMLHttpRequest();
  }

  xhrobj.open('GET', 'quickvote.php?id='+id+'&quickvote=up', true);
  xhrobj.onreadystatechange = responsefor(id);
  xhrobj.send(null);
}

function vote_down(id) {
  if(navigator.appName == "Microsoft Internet Explorer") {
    xhrobj = new ActiveXObject("Microsoft.XMLHTTP");
  } else {
    xhrobj = new XMLHttpRequest();
  }

  xhrobj.open('GET', 'quickvote.php?id='+id+'&quickvote=down', true);
  xhrobj.onreadystatechange = responseagainst(id);
  xhrobj.send(null);
}

function responsefor(id) {
	  if(xhrobj.readyState == 4) {
		document.getElementById('for'+id).innerHTML=xhrobj.responseText;
	  }
	}

function responseagainst(id) {
  if(xhrobj.readyState == 4) {
    document.getElementById('against'+id).innerHTML=xhrobj.responseText;
  }
}

The HTML:

<div class="meta">

   <span class="quickvote"> 

 <span id="for15">
       <a onclick="vote_up(15);">I like! (number of votes here)</a>
 </span>

 <span id="against15">
       <a onclick="vote_down(15);">I don't like (number of votes here)</a>
 </span>

   </span>

</div>

The PHP Processing:

switch ($_GET["quickvote'"]) {
	case "up":
	include("config.php");
	$id = $_GET["id"];
	$upq = "UPDATE `submissions` SET votes_up=votes_up+1 WHERE id='$id'";
	mysql_query($upq, $cxn);
	$sql = "SELECT votes_up FROM submissions WHERE id='$id'";
	$query = mysql_query($sql, $cxn);
	$grab = mysql_fetch_assoc($query);
	echo '&lt;a class="assholer" &gt;Ugh! What An *******! (' . $grab['votes_up']+1 . ')&lt;/a&gt;';
	break;
	case "down":
	include("config.php");
	$id = $_GET["id"];
	$downq = "UPDATE `submissions` SET votes_down=votes_down+1 WHERE id='$id'";
	mysql_query($downq, $cxn);
	$sql = "SELECT votes_down FROM submissions WHERE id='$id'";
	$query = mysql_query($sql, $cxn);
	$grab = mysql_fetch_assoc($query);
	echo '&lt;a class="joer"&gt;Meh, Just An Average Joe...(' . $grab['votes_down']+1 . ')&lt;/a&gt;';
	break;
}

If anyone has any input for me, I’d appreciate it! I’m still trying to learn this.

Oh, and that’s a simpler version of what I’m trying to do in the original post–I think my issue with the two are related and I will try to fix this one first.

Your code may have other problems. I stopped looking when I saw this.


xhrobj.onreadystatechange = responsefor(id);

Because you wrote responsefor(id), with the parenthesis, you actually call the function right then and there, and assign the return value of the function to the onreadystatechange property. What you need to be doing is assign a function, which javascript will call for you later automatically.

Normally, you would do it like


xhrobj.onreadystatechange = responsefor;

But your function needs that id argument to work. You can use an anonymous function to wrap it


xhrobj.onreadystatechange = function(){
    responsefor(id);
}

I won’t get into the details of explaining that part. google for anonymous function or closure to learn more about it in javascript. It’s something you may use pretty frequently in javascript.

Interesting…I will look that up.