简体   繁体   English

通过调用php页面的javascript Ajax将数据发布到数据库

[英]Posting Data to a database through javascript Ajax which calls a php page

So basically I want to have a Javascript function that posts data to a table in my database. 因此,基本上我想拥有一个Javascript函数,可将数据发布到数据库中的表中。 i know that I need to call a php page to do this. 我知道我需要调用php页面来做到这一点。 But the code I have written doesn't work. 但是我编写的代码不起作用。 The js fucntion is triggered by a button press in html. js功能由html中的按钮按下触发。 I need to do this in js ajax and not jquery ajax 我需要在js ajax而不是jquery ajax中执行此操作

The Javascript Javascript

function comment_sub(){
 var xhttp = new XMLHttpRequest();
 xhttp.onreadystatechange = function() 
{
    if (this.readyState == 4 && this.status == 200) 
    {    
    }
};
xhttp.open("POST", "static/setcomments.php", true);
xhttp.send(encodeURIComponent(document.getElementById('comment-textbox').value));  
}

The PHP 的PHP

<?php
echo "Hello";
$mydb = mysqli_connect("localhost", "root","", "website");
if (!$mydb){
    die("Connection failed".mysqli_connect_error());
}
$sql = "INSERT INTO 'comments'('comment_text') VALUES ('{$_GET['comment-textbox']}')";
$query = mysqli_query($mydb, $sql);
if (!$query)
{
  die('Error: ' . mysql_error());
}
echo "1 record added"
?>

Checked the network and console log. 检查网络和控制台日志。 The JS function is being called fine but the network logs gives me a 404 error for the post request JS函数被很好地调用了,但是网络日志给我发了404错误的发布请求

You are only sending the value itself, not the name comment-textbox . 您只发送值本身,而不是名称comment-textbox

Try this: 尝试这个:

xhttp.send(JSON.stringify({
    'comment-textbox': document.getElementById('comment-textbox').value
}));

On the PHP page, you are doing a HTTP POST and not a HTTP GET. 在PHP页面上,您正在执行HTTP POST而不是HTTP GET。 So rewrite it as this: 因此,将其重写为:

$sql = "INSERT INTO 'comments'('comment_text') VALUES ('{$_POST['comment-textbox']}')"; $ sql =“ INSERT INTO'comments'('comment_text')VALUES('{$ _POST ['comment-textbox']}')”;

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

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