0

I'm trying to build a simple "I viewed this" function in a php directory for an intranet site.

So when a user has read the page, they click a button at the bottom that says "I've read this" that sends the users User ID and the page ID to a simple database table that I can then harvest for other uses.

I'm trying to do it with AJAX and PHP.

Here's my code:

<SCRIPT LANGUAGE="JavaScript">
function viewSave(form) {
var itemid = <?php echo $itemid; ?>;
var userid = <?php echo $userid; ?>;

var xmlhttp;

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

 xmlhttp.open("GET","saveView.php?q=itemid="+itemid+"&userid="+userid,true);
 xmlhttp.send();
}

</script>   

and I've set up a simple form with hidden fields:

<form onSubmit="return viewSave(this)" >
<input type="submit" name="submit" value="Save" />
</form>

When I click submit, the URL changes and I get my variables, like this:

thispage.php?itemid=455&userid=999&submit=Save

but "saveView.php" is not called and the data is not sent.

Here's what's in saveView.php:

<?php


$userid =$_GET["userid"];
$itemid = $_GET["itemid"];

  // Connect to the database
            $dbc = mysqli_connect('localhost', 'root', '', 'viewsave');

            // Write the data to the database
            $query = "INSERT INTO saves (entryID, userid, itemid) VALUES ( '0', '$userid', '$itemid')";
            mysqli_query($dbc, $query);

?>

I'm guessing the URL params are only appearing because of the form and that there's something wrong with the JavaScript.

I'm only a beginner with JS.

Help appreciated.

Ray.

2
  • 1
    Off-topic, but You could save yourself a lot of time and headaches over browser compatibility if you'd use jQuery Commented Feb 5, 2013 at 20:43
  • why are you embedding the values into your JS AND into the form? ...php?q="+itemid,userid is also not doing what you expect. Commented Feb 5, 2013 at 20:50

1 Answer 1

1

Firstly, your php file needs a name:

xmlhttp.open("GET","save.php?

Then your parameters need names:

xmlhttp.open("GET","save.php?q=itemid="+itemid+"&userid="+userid,true);

Then, in PHP you can use $_GET to get the data (and check it's a number):

if(array_key_exists('itemid', $_GET) && !is_nan($_GET['itemid'])) {
    $itemid = $_GET['itemid'];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Adam! I tried your code but I'm still not getting the data through to the database... I've made edits to the code above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.