简体   繁体   English

通过onClick javascript函数使用PHP更新MySql数据库

[英]Updating a MySql database using PHP via an onClick javascript function

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. 我有一组四个链接,每个链接显示从我的数据库中检索到的特定单词和线索,我需要检查已选择的单词是否与该线索的正确单词匹配。

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. 我知道我需要使用javascript因为onClick功能,我可以成功检查所选单词是否与正确的单词匹配。 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. 但是,如果单词匹配正确,我需要更新数据库中保存的分数,因此我需要使用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. 从我可以收集到的这意味着我必须使用AJAX,但我找不到任何人使用AJAX onClick链接然后更新数据库的好例子。

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 where $newarray[0] is that answer I want to check against $newarray[$rand_keys]

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

//my attempt at ajax in a score.js file //我在score.js文件中尝试ajax

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);
?>

I would highly recommend learning AJAX properly - it won't take you ages but will help you understand what you can and can't do with it. 我强烈建议正确学习AJAX - 它不会花费你很多年,但会帮助你理解你能做什么,不能用它做什么。

Updating a DB from a web page via AJAX is very common. 通过AJAX从网页更新数据库非常常见。 I would suggest simplifying your JavaScript development using jQuery (a JavaScript library). 我建议使用jQuery (JavaScript库)简化JavaScript开发。 There is a good introduction to jQuery and AJAX here . 这是一个很好的介绍jQuery和AJAX 在这里

Basically what jQuery will do is write a lot of the boilerplate code for you. 基本上jQuery会做的就是为你编写很多样板代码。 What you will end up writing is something like this: 你最终写的是这样的:

function updateScore(answer, correct) {
  if (answer == correct) {
    $.post('updatescore.php');
  }
}

...

<a onclick="updateScore(this, correct)" ...> </a>

What you're doing here is sending a POST request to updatescore.php when the answer is correct. 你在这里做的是在答案正确时向updatescore.php发送POST请求。

Then, in your updatescore.php, you just need to have PHP code like you already do which will update the score in the database. 然后,在您的updatescore.php中,您只需要拥有像您已经做过的PHP代码,这将更新数据库中的分数。

You can obviously do many more complicate things than this, but hopefully that will be enough to get you started. 显然你可以做比这更复杂的事情,但希望这足以让你开始。

I noticed you have "window.location.reload(true);" 我注意到你有“window.location.reload(true);” in your code. 在你的代码中。 Why? 为什么? That seems like it would make things not work. 这似乎会让事情变得不起作用。

You should try to analyze your program to find out where the problem is happening. 您应该尝试分析您的程序以找出问题发生的位置。 Then you will be able to ask us a very specific question like "why does Firefox not fire the onClick handler when I click on this link" instead of just posting three pages of code. 然后,您将能够向我们提出一个非常具体的问题,例如“为什么Firefox在点击此链接时不会触发onClick处理程序”而不是仅发布三页代码。 When you paste so much code, it's pretty hard for us to find your bug. 当你粘贴这么多代码时,我们很难找到你的bug。

So here are the questions you should ask: 所以这是你应该问的问题:

  1. Is my HTML being parsed correctly? 我的HTML是否正确解析? To me, it looks like it might not be parsed correctly because you did not put quotes around the value of onClick. 对我来说,它看起来可能无法正确解析,因为你没有在onClick的值周围加上引号。 You should use quotes, like: onClick="..." To find out if your HTML is being parsed nicely, you can use Firefox's View->Source feature and look at the colors it prints. 您应该使用引号,例如:onClick =“...”要查看您的HTML是否被很好地解析,您可以使用Firefox的View-> Source功能并查看它打印的颜色。

  2. Is my onClick handler getting called? 我的onClick处理程序是否被调用? It looks like you are using alert()'s effectively so that's good. 看起来你正在有效地使用alert(),所以这很好。

  3. Does the request actually get sent to my server? 请求是否实际发送到我的服务器? To determine this, you should use Firefox, and install the Firebug extension. 要确定这一点,您应该使用Firefox,并安装Firebug扩展。 In the "Net" panel, it will show you all the AJAX requests that are being made by your page, and it will show you the results that were returned from the server. 在“Net”面板中,它将显示您的页面所做的所有AJAX请求,它将显示从服务器返回的结果。

  4. Is the script on my server doing the right thing? 我服务器上的脚本是否做正确的事情? So on the server side, you can now add lines like "echo 'hello world';" 所以在服务器端,你现在可以添加像“echo'hello world';”这样的行。 and you will see that output in the Firebug Net panel, which will help you debug the behavior of your server-side script. 您将在Firebug Net面板中看到该输出,它将帮助您调试服务器端脚本的行为。

  5. Is my stateChanged function getting called? 我的stateChanged函数被调用了吗? Once again, use alert() statements, or write to Firebug's debug console . 再一次,使用alert()语句,或写入Firebug的调试控制台

Once you've narrowed your problem down, try to reduce your code to the simplest possible code that still fails. 一旦缩小了问题范围,请尝试将代码减少到仍然失败的最简单代码。 Then show us the code and tell us exactly what the symptoms of the error are. 然后向我们展示代码并告诉我们错误的症状是什么。

On another note, I recommend getting this book: Javascript: The Deinitive Guide, 5th Edition by O'Reilly . 另外,我推荐这本书: Javascript:The Reinitive Guide,第5版,由O'Reilly撰写 It covers lots of cool stuff like AJAX and closures. 它涵盖了许多很酷的东西,如AJAX和闭包。 It costs $50 but it's definitely a good investment because it explains things in a much more coherent way then you'll ever get from free websites. 它的成本是50美元,但它肯定是一项很好的投资,因为它以更加连贯的方式解释事物,然后你就可以从免费网站获得。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM