简体   繁体   English

使用onClick执行表单

[英]Execute form with onClick

I have a link 我有一个链接

<a href="/post/$postid" class="link">Update</a>

When I click on it it goes to a unique page defined by a variable $postid . 当我单击它时,将转到由变量$postid定义的唯一页面。

However, I want to add an onclick event which will update the database too. 但是,我想添加一个onclick事件,它也会更新数据库。

I have read on here that AJAX is the best way to do this, but I'm struggling on how to write it. 我在这里读到,AJAX是实现此目的的最佳方法,但是我在如何编写它方面苦苦挣扎。 From reading various questions I have come up with this: 通过阅读各种问题,我得出了以下结论:

<script>
$(".link").click(function() {
  // sql request
  UPDATE comments SET status='updated' WHERE user_id='$myid' AND id='$postid';
});
</script>

Obviously this syntax is wrong. 显然,这种语法是错误的。 Could somebody point me in the right direction of the type of syntax I can use to update my MySQL database with? 有人可以为我指出可用于更新MySQL数据库的语法类型的正确方向吗?

UPDATED WITH ATTEMPT: 尝试更新:

Here is one attempt I have tried... 这是我尝试过的一种尝试...

<form>
<a href="/post/$postid" class="link">Update</a>
</form>

<script>
$(".link").click(function() {
  $.ajax({
        type: "GET",
        url:"/application/views/notification_action.php",
        data: "myid=$user_id&postid=$postid"
        }).done(function( data ) {
            doAsYouPlease();
        }
    );
});
</script>

notification_action.php notification_action.php

<?php

$myid = $_POST['user_id'];
$postid = $_POST['pin_id'];

$query("UPDATE comments SET status='updated' WHERE user_id='$myid' AND id='$postid'");

$result = mysql_query($query);

However nothing works. 但是,没有任何效果。 The link just surfs to the post page like normal. 链接只是像往常一样浏览到帖子页面。 nothing gets updated. 没有任何更新。

You need to create a file(or files) that handle(s) ajax requests ( ajax.php in this example). 您需要创建一个或多个处理ajax请求的文件(在此示例中为ajax.php )。

<script>
$(".link").click(function() {
  $.ajax({
        type: "GET",
        url:"ajax.php",
        data: "ajax=1"
        }).done(function( data ) {
            doAsYouPlease();
        }
    );
});
</script>

You can also use 您也可以使用

<input type="submit">

then change your form action to a page that submits the query, then use the 然后将您的表单操作更改为提交查询的页面,然后使用

header("location: $postid");

on the same page that does the query, and it will redirect you 在执行查询的同一页面上,它将重定向您

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

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