Jump to content

Updating a MySql database using PHP via an onClick javascript function


123pf

Recommended Posts

Hi,

 

Sorry this is my first post on a forum.

 

I am creating a web game for learning new words aimed at children.

 

I have a set of four links each displaying a specific word retrieved from my database and a clue, I need to check that the word which has been selected matches the correct word for that clue.  This MUST be done onClick() of the link.

 

I know that I need to use javascript because of the onClick function and I can successfully check whether the word selected matches the correct word.  However, I then need to update a score held in the database if the word is matched correctly, therefore I would need to use php.

 

From what I can gather this means I must use AJAX but I can't find a good example of anyone using AJAX onClick of a link to then update a database.

 

I have attempted to do this...but its probably completely wrong as I couldn't get it to work properly:

 

//This is my link that I need to use in my game.php file

<a onClick=originalUpdateScore('$newarray[0]','$newarray[$rand_keys]')>$newarray[0]</a>

//my attempt at ajax in a score.js file

var xmlHttp;

function originalUpdateScore(obj,corr){
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
	alert ("Browser does not support HTTP Request");
	return;
}

if(corr == obj){

var url="getscore.php";
//url=url+"?q="+str;
//url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
//xmlHttp.open("GET",url,true);
xmlHttp.open(url,true);
xmlHttp.send(null);

	alert('Correct');

}
else
{
	alert('AHHHHH!!!');
}

window.location.reload(true);
}


function stateChanged() 
{ 
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	{ 
		document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
	} 
}
function GetXmlHttpObject()
{
	var xmlHttp=null;
	try
	{
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch (e)
	{
		//Internet Explorer
		try
		{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
return xmlHttp;
}

//attempting to update the database in a getscore.php file

<?php
//$q=$_GET["q"];
include("dbstuff.inc");
$con = mysqli_connect($host, $user, $passwd, $dbname)
or die ("Query died: connection");

$sql= "UPDATE `temp` SET `tempScore`= `tempScore`+1 WHERE (temp.Username='$_SESSION[logname]')";

$showsql = "SELECT `tempScore` FROM `temp` WHERE (temp.Username='$_SESSION[logname]')";
$result = mysqli_query($con, $showsql);

echo "$result";

mysqli_close($con);
?>

 

Thanks for any help in advance.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.