使用ajax插入到数据库

问题描述:

我有一个锚标记,我想用它来转到某个页面,但同时我想使用onclick函数插入数据库。使用ajax插入到数据库

这里就是我有这么远: HTML:

<script type="text/javascript"> 
function showUser(str) 
{ 
if (str=="") 
    { 
    alert("txtHint"); 
    } 
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","submit.php?click="+str,true); 
xmlhttp.send(); 
} 
</script> 

<a onclick="showUser('test')" href="http:www.google.com">click here</a> 

和这里的PHP文件:

mysql_connect("localhost", "username", "password") or die(mysql_error()); 
mysql_select_db("db_name") or die(mysql_error()); 

// Retrieve all the data from the "example" table 
$result = mysql_query(" 
SELECT `clicked` FROM `links` 
WHERE open = ".$_GET['link']) 
or die(mysql_error()); 
$row = mysql_fetch_array($result) 
$x = $row['clicked']; 
$y = $x++; 

$result2 = mysql_query(" 
UPDATE `db_name`.`links` 
SET `clicked` = $y 
WHERE `links`.`open` = '".$_GET['link']."' 
") 
or die(mysql_error()); 
mysql_fetch_array($result2); 

这将谷歌,因为它应该,但它不插入到数据库。

任何想法?

在此先感谢,

里斯

编辑 - 我已经在PHP文件感谢大家固定的所有错误,现在插入正确刚刚访问网址中包含一个点击PHP页面时。

但它仍然不插入使用ajax。显然有一些我已经做了错误的代码。

有什么想法?

感谢

EDIT2解决 -

的人那有兴趣,与Ajax代码的问题是这条线:

xmlhttp.open("GET","submit.php?click="+str,true); 

它需要是这样

xmlhttp.open("GET","/submit.php?click="+str,true); 
+0

请求是否到达服务器?服务器是否记录error_log中的任何错误?您是否尝试过使用任何工具进行调试? – DKSan 2011-06-07 12:39:48

我发现的第一个错误是: 你想在你的php代码中使用$_GET['link']),但只发送一个在JS中的click参数。所以,你应该改变你的JS代码:

xmlhttp.open("GET","submit.php?link="+str,true); 

尝试运行PHP脚本没有Ajax最终发现更多的错误。

似乎你忘了;马克这里:$row = mysql_fetch_array($result)

It's going to google as it should, but it isn't inserting into the database.

是的,但请确保调用PHP脚本的实际工作和脚本本身没有错误,然后看看数据库。

你使用mysql_fetch_array($ result2);对于更新使用的mysql_query($结果2)

及其也不$ _GET [ '链接']的$ _GET [ '点击']

+0

他实际上是用mysql_query()更新的。你的代码会引发错误。 – 2011-06-07 12:50:57

+0

sry我看到它,谢谢你..... – praneeth 2011-06-07 12:54:48

我建议使用jQuery &。员额()方法。这 语法将是更具可读性人类:)

// submit here ... 
$.post(
    "answer.php", 
    { 
     start: $("#ancor_id") . attr("title") 

    }, 
    function(ret) { 

     if (!ret.success) 
     { 
     alert(1); 
     } 
     else 
     { 
     alert("Update Ok"); 
     } 
    }, 
    'json' 
); 

其中的答案。php

<? 
    header("Content-Type: application/json"); 
    $arr_json = array(); 
    $arr_json[ "success" ] = "true"; 
    echo json_encode($arr_json); 
    exit; 
?> 
+0

你能详细说明一下吗? – Reece 2011-06-07 13:27:14